blob: 9f9390195f62976b2df3204a63cf01fb7f3f30a7 [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;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023import static android.net.ConnectivityManager.isNetworkTypeValid;
24import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070025import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070026
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080027import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080028import android.content.ContentResolver;
29import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090030import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080031import android.content.Intent;
32import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090033import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070034import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080035import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080036import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080037import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080038import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070039import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070040import android.net.INetworkPolicyListener;
41import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070042import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070043import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080044import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070045import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070047import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070049import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070050import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070051import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080052import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070053import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070054import android.net.Proxy;
55import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070056import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090058import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040060import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080061import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070062import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070063import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070064import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.os.Looper;
66import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070067import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070068import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070069import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080070import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070071import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.os.SystemProperties;
73import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070074import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080076import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070077import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080078
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070079import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070080import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070081import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -070082import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -070083import com.android.server.am.BatteryStatsService;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080084import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070085import com.android.server.connectivity.Vpn;
Jeff Sharkey21062e72011-05-28 20:56:34 -070086import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070087import com.google.android.collect.Sets;
tk.mun093f55c2011-10-13 22:51:57 +090088import dalvik.system.DexClassLoader;
The Android Open Source Project28527d22009-03-03 19:31:44 -080089import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070090import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080091import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +090092import java.lang.reflect.Constructor;
93import java.lang.reflect.Method;
94import java.lang.reflect.Modifier;
95import java.lang.reflect.InvocationTargetException;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070096import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070097import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070098import java.net.InetAddress;
99import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700100import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700101import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700102import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700103import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700104import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700105import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106
107/**
108 * @hide
109 */
110public class ConnectivityService extends IConnectivityManager.Stub {
111
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700112 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700113 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800114 private static final String TAG = "ConnectivityService";
115
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700116 private static final boolean LOGD_RULES = false;
117
Robert Greenwalt2034b912009-08-12 16:08:25 -0700118 // how long to wait before switching back to a radio's default network
119 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
120 // system property that can override the above value
121 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
122 "android.telephony.apn-restore";
123
Robert Greenwaltbd492212011-05-06 17:10:53 -0700124 // used in recursive route setting to add gateways for the host for which
125 // a host route was requested.
126 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
127
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800128 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800129 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800130
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700131 private Vpn mVpn;
132
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700133 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
134 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700135 /** Currently active network rules by UID. */
136 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700137 /** Set of ifaces that are costly. */
138 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700139
The Android Open Source Project28527d22009-03-03 19:31:44 -0800140 /**
141 * Sometimes we want to refer to the individual network state
142 * trackers separately, and sometimes we just want to treat them
143 * abstractly.
144 */
145 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700146
147 /**
Wink Saville051a6642011-07-13 13:44:13 -0700148 * The link properties that define the current links
149 */
150 private LinkProperties mCurrentLinkProperties[];
151
152 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153 * A per Net list of the PID's that requested access to the net
154 * used both as a refcount and for per-PID DNS selection
155 */
156 private List mNetRequestersPids[];
157
Robert Greenwalt2034b912009-08-12 16:08:25 -0700158 // priority order of the nettrackers
159 // (excluding dynamically set mNetworkPreference)
160 // TODO - move mNetworkTypePreference into this
161 private int[] mPriorityList;
162
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163 private Context mContext;
164 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700165 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700166 // 0 is full bad, 100 is full good
167 private int mDefaultInetCondition = 0;
168 private int mDefaultInetConditionPublished = 0;
169 private boolean mInetConditionChangeInFlight = false;
170 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800171
Chia-chi Yehcc844502011-07-14 18:01:57 -0700172 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800173 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700174 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800175
176 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700177 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800178
Robert Greenwalt355205c2011-05-10 15:05:02 -0700179 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700180 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700181
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700182 private static final int ENABLED = 1;
183 private static final int DISABLED = 0;
184
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700185 private static final boolean ADD = true;
186 private static final boolean REMOVE = false;
187
188 private static final boolean TO_DEFAULT_TABLE = true;
189 private static final boolean TO_SECONDARY_TABLE = false;
190
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700191 // Share the event space with NetworkStateTracker (which can't see this
192 // internal class but sends us events). If you change these, change
193 // NetworkStateTracker.java too.
194 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
195 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
196
197 /**
198 * used internally as a delayed event to make us switch back to the
199 * default network
200 */
201 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
202 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
203
204 /**
205 * used internally to change our mobile data enabled flag
206 */
207 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
208 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
209
210 /**
211 * used internally to change our network preference setting
212 * arg1 = networkType to prefer
213 */
214 private static final int EVENT_SET_NETWORK_PREFERENCE =
215 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
216
217 /**
218 * used internally to synchronize inet condition reports
219 * arg1 = networkType
220 * arg2 = condition (0 bad, 100 good)
221 */
222 private static final int EVENT_INET_CONDITION_CHANGE =
223 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
224
225 /**
226 * used internally to mark the end of inet condition hold periods
227 * arg1 = networkType
228 */
229 private static final int EVENT_INET_CONDITION_HOLD_END =
230 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
231
232 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700233 * used internally to set enable/disable cellular data
234 * arg1 = ENBALED or DISABLED
235 */
236 private static final int EVENT_SET_MOBILE_DATA =
237 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
238
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700239 /**
240 * used internally to clear a wakelock when transitioning
241 * from one net to another
242 */
243 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
244 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
245
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700246 /**
247 * used internally to reload global proxy settings
248 */
249 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
250 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
251
Robert Greenwalt34848c02011-03-25 13:09:25 -0700252 /**
253 * used internally to set external dependency met/unmet
254 * arg1 = ENABLED (met) or DISABLED (unmet)
255 * arg2 = NetworkType
256 */
257 private static final int EVENT_SET_DEPENDENCY_MET =
258 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
259
Chia-chi Yehcc844502011-07-14 18:01:57 -0700260 /**
261 * used internally to restore DNS properties back to the
262 * default network
263 */
264 private static final int EVENT_RESTORE_DNS =
265 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
266
Wink Saville7e4333c2011-08-05 11:40:22 -0700267 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700268 * used internally to send a sticky broadcast delayed.
269 */
270 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville7e4333c2011-08-05 11:40:22 -0700271 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700272
Jeff Sharkey805662d2011-08-19 02:24:24 -0700273 /**
274 * Used internally to
275 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
276 */
277 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
278
Robert Greenwalt2034b912009-08-12 16:08:25 -0700279 private Handler mHandler;
280
281 // list of DeathRecipients used to make sure features are turned off when
282 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500283 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700284
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400285 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800286 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400287
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700288 private PowerManager.WakeLock mNetTransitionWakeLock;
289 private String mNetTransitionWakeLockCausedBy = "";
290 private int mNetTransitionWakeLockSerialNumber;
291 private int mNetTransitionWakeLockTimeout;
292
Robert Greenwalt94daa182010-09-01 11:34:05 -0700293 private InetAddress mDefaultDns;
294
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700295 // this collection is used to refcount the added routes - if there are none left
296 // it's time to remove the route from the route table
297 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
298
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700299 // used in DBG mode to track inet condition reports
300 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
301 private ArrayList mInetLog;
302
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700303 // track the current default http proxy - tell the world if we get a new one (real change)
304 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700305 private Object mDefaultProxyLock = new Object();
306 private boolean mDefaultProxyDisabled = false;
307
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700308 // track the global proxy.
309 private ProxyProperties mGlobalProxy = null;
310 private final Object mGlobalProxyLock = new Object();
311
312 private SettingsObserver mSettingsObserver;
313
Robert Greenwalt34848c02011-03-25 13:09:25 -0700314 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700315 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700316
Robert Greenwalt12c44552009-12-07 11:33:18 -0800317 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700318 public int mSimultaneity;
319 public int mType;
320 public RadioAttributes(String init) {
321 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700322 mType = Integer.parseInt(fragments[0]);
323 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700324 }
325 }
326 RadioAttributes[] mRadioAttributes;
327
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700328 // the set of network types that can only be enabled by system/sig apps
329 List mProtectedNetworks;
330
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700331 public ConnectivityService(Context context, INetworkManagementService netd,
332 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800333 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800334
Wink Saville775aad62010-09-02 19:23:52 -0700335 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
336 handlerThread.start();
337 mHandler = new MyHandler(handlerThread.getLooper());
338
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800339 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800340 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
341 String id = Settings.Secure.getString(context.getContentResolver(),
342 Settings.Secure.ANDROID_ID);
343 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700344 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800345 SystemProperties.set("net.hostname", name);
346 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800347 }
348
Robert Greenwalt94daa182010-09-01 11:34:05 -0700349 // read our default dns server ip
350 String dns = Settings.Secure.getString(context.getContentResolver(),
351 Settings.Secure.DEFAULT_DNS_SERVER);
352 if (dns == null || dns.length() == 0) {
353 dns = context.getResources().getString(
354 com.android.internal.R.string.config_default_dns_server);
355 }
356 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800357 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
358 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800359 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700360 }
361
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700362 mContext = checkNotNull(context, "missing Context");
363 mNetd = checkNotNull(netd, "missing INetworkManagementService");
364 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700365
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700366 try {
367 mPolicyManager.registerListener(mPolicyListener);
368 } catch (RemoteException e) {
369 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700370 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700371 }
372
373 final PowerManager powerManager = (PowerManager) context.getSystemService(
374 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700375 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
376 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
377 com.android.internal.R.integer.config_networkTransitionTimeout);
378
Robert Greenwalt2034b912009-08-12 16:08:25 -0700379 mNetTrackers = new NetworkStateTracker[
380 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700381 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700382
The Android Open Source Project28527d22009-03-03 19:31:44 -0800383 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700384
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700385 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700386 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700387
Robert Greenwalt2034b912009-08-12 16:08:25 -0700388 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700389 String[] raStrings = context.getResources().getStringArray(
390 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 for (String raString : raStrings) {
392 RadioAttributes r = new RadioAttributes(raString);
393 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800394 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700395 continue;
396 }
397 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800398 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700399 r.mType);
400 continue;
401 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700402 mRadioAttributes[r.mType] = r;
403 }
404
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700405 String[] naStrings = context.getResources().getStringArray(
406 com.android.internal.R.array.networkAttributes);
407 for (String naString : naStrings) {
408 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700409 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700410 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800411 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700412 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700413 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700414 }
Wink Savillef2a62832011-04-07 14:23:45 -0700415 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800416 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700417 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700418 continue;
419 }
Wink Savillef2a62832011-04-07 14:23:45 -0700420 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800421 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700422 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700423 continue;
424 }
Wink Savillef2a62832011-04-07 14:23:45 -0700425 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700426 mNetworksDefined++;
427 } catch(Exception e) {
428 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700429 }
430 }
431
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700432 mProtectedNetworks = new ArrayList<Integer>();
433 int[] protectedNetworks = context.getResources().getIntArray(
434 com.android.internal.R.array.config_protectedNetworks);
435 for (int p : protectedNetworks) {
436 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
437 mProtectedNetworks.add(p);
438 } else {
439 if (DBG) loge("Ignoring protectedNetwork " + p);
440 }
441 }
442
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700443 // high priority first
444 mPriorityList = new int[mNetworksDefined];
445 {
446 int insertionPoint = mNetworksDefined-1;
447 int currentLowest = 0;
448 int nextLowest = 0;
449 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700450 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700451 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700452 if (na.priority < currentLowest) continue;
453 if (na.priority > currentLowest) {
454 if (na.priority < nextLowest || nextLowest == 0) {
455 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 }
457 continue;
458 }
Wink Savillef2a62832011-04-07 14:23:45 -0700459 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700460 }
461 currentLowest = nextLowest;
462 nextLowest = 0;
463 }
464 }
465
466 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
467 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700468 mNetRequestersPids[i] = new ArrayList();
469 }
470
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500471 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700472
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700473 mNumDnsEntries = 0;
474
475 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
476 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800477 /*
478 * Create the network state trackers for Wi-Fi and mobile
479 * data. Maybe this could be done with a factory class,
480 * but it's not clear that it's worth it, given that
481 * the number of different network types is not going
482 * to change very often.
483 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700484 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700485 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700486 case ConnectivityManager.TYPE_WIFI:
repo syncf5de5572011-07-29 23:55:49 -0700487 mNetTrackers[netType] = new WifiStateTracker(netType,
488 mNetConfigs[netType].name);
489 mNetTrackers[netType].startMonitoring(context, mHandler);
490 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700491 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700492 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700493 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700494 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700495 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800496 case ConnectivityManager.TYPE_DUMMY:
497 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700498 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800499 mNetTrackers[netType].startMonitoring(context, mHandler);
500 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800501 case ConnectivityManager.TYPE_BLUETOOTH:
502 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
503 mNetTrackers[netType].startMonitoring(context, mHandler);
504 break;
tk.mun093f55c2011-10-13 22:51:57 +0900505 case ConnectivityManager.TYPE_WIMAX:
506 mNetTrackers[netType] = makeWimaxStateTracker();
Robert Greenwalte72c4ac2011-11-08 10:12:25 -0800507 if (mNetTrackers[netType]!= null) {
tk.mun093f55c2011-10-13 22:51:57 +0900508 mNetTrackers[netType].startMonitoring(context, mHandler);
509 }
510 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800511 case ConnectivityManager.TYPE_ETHERNET:
512 mNetTrackers[netType] = EthernetDataTracker.getInstance();
513 mNetTrackers[netType].startMonitoring(context, mHandler);
514 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700515 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800516 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700517 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700518 continue;
519 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700520 mCurrentLinkProperties[netType] = null;
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800521 if (mNetTrackers[netType] != null && mNetConfigs[netType].isDefault()) {
522 mNetTrackers[netType].reconnect();
523 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700524 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800525
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700526 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
527 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
528
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700529 mTethering = new Tethering(mContext, nmService, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700530 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700531 mTethering.getTetherableWifiRegexs().length != 0 ||
532 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700533 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800534
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700535 mVpn = new Vpn(mContext, new VpnCallback());
536
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700537 try {
538 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700539 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700540 } catch (RemoteException e) {
541 loge("Error registering observer :" + e);
542 }
543
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700544 if (DBG) {
545 mInetLog = new ArrayList();
546 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700547
548 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
549 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800550
Haoyu Baib5da5752012-06-20 14:29:57 -0700551 INetworkManagementEventObserver netdObserver = new NetdObserver();
552 try {
553 mNetd.registerObserver(netdObserver);
554 } catch (RemoteException e) {
555 loge("Error registering observer :" + e);
556 }
557
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800558 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800559 }
tk.mun093f55c2011-10-13 22:51:57 +0900560private NetworkStateTracker makeWimaxStateTracker() {
561 //Initialize Wimax
562 DexClassLoader wimaxClassLoader;
563 Class wimaxStateTrackerClass = null;
564 Class wimaxServiceClass = null;
565 Class wimaxManagerClass;
566 String wimaxJarLocation;
567 String wimaxLibLocation;
568 String wimaxManagerClassName;
569 String wimaxServiceClassName;
570 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800571
tk.mun093f55c2011-10-13 22:51:57 +0900572 NetworkStateTracker wimaxStateTracker = null;
573
574 boolean isWimaxEnabled = mContext.getResources().getBoolean(
575 com.android.internal.R.bool.config_wimaxEnabled);
576
577 if (isWimaxEnabled) {
578 try {
579 wimaxJarLocation = mContext.getResources().getString(
580 com.android.internal.R.string.config_wimaxServiceJarLocation);
581 wimaxLibLocation = mContext.getResources().getString(
582 com.android.internal.R.string.config_wimaxNativeLibLocation);
583 wimaxManagerClassName = mContext.getResources().getString(
584 com.android.internal.R.string.config_wimaxManagerClassname);
585 wimaxServiceClassName = mContext.getResources().getString(
586 com.android.internal.R.string.config_wimaxServiceClassname);
587 wimaxStateTrackerClassName = mContext.getResources().getString(
588 com.android.internal.R.string.config_wimaxStateTrackerClassname);
589
590 log("wimaxJarLocation: " + wimaxJarLocation);
591 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
592 new ContextWrapper(mContext).getCacheDir().getAbsolutePath(),
593 wimaxLibLocation, ClassLoader.getSystemClassLoader());
594
595 try {
596 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
597 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
598 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
599 } catch (ClassNotFoundException ex) {
600 loge("Exception finding Wimax classes: " + ex.toString());
601 return null;
602 }
603 } catch(Resources.NotFoundException ex) {
604 loge("Wimax Resources does not exist!!! ");
605 return null;
606 }
607
608 try {
609 log("Starting Wimax Service... ");
610
611 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
612 (new Class[] {Context.class, Handler.class});
613 wimaxStateTracker = (NetworkStateTracker)wmxStTrkrConst.newInstance(mContext,
614 mHandler);
615
616 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
617 (new Class[] {Context.class, wimaxStateTrackerClass});
618 wmxSrvConst.setAccessible(true);
619 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(mContext, wimaxStateTracker);
620 wmxSrvConst.setAccessible(false);
621
622 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
623
624 } catch(Exception ex) {
625 loge("Exception creating Wimax classes: " + ex.toString());
626 return null;
627 }
628 } else {
629 loge("Wimax is not enabled or not added to the network attributes!!! ");
630 return null;
631 }
632
633 return wimaxStateTracker;
634 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800635 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700636 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800637 * @param preference the new preference
638 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700639 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800640 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700641
642 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800643 }
644
645 public int getNetworkPreference() {
646 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700647 int preference;
648 synchronized(this) {
649 preference = mNetworkPreference;
650 }
651 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800652 }
653
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700654 private void handleSetNetworkPreference(int preference) {
655 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700656 mNetConfigs[preference] != null &&
657 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700658 if (mNetworkPreference != preference) {
659 final ContentResolver cr = mContext.getContentResolver();
660 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
661 synchronized(this) {
662 mNetworkPreference = preference;
663 }
664 enforcePreference();
665 }
666 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800667 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700668
Wink Saville4f0de1e2011-08-04 15:01:58 -0700669 private int getConnectivityChangeDelay() {
670 final ContentResolver cr = mContext.getContentResolver();
671
672 /** Check system properties for the default value then use secure settings value, if any. */
673 int defaultDelay = SystemProperties.getInt(
674 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
675 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
676 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
677 defaultDelay);
678 }
679
The Android Open Source Project28527d22009-03-03 19:31:44 -0800680 private int getPersistedNetworkPreference() {
681 final ContentResolver cr = mContext.getContentResolver();
682
683 final int networkPrefSetting = Settings.Secure
684 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
685 if (networkPrefSetting != -1) {
686 return networkPrefSetting;
687 }
688
689 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
690 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700691
The Android Open Source Project28527d22009-03-03 19:31:44 -0800692 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700693 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800694 * In this method, we only tear down a non-preferred network. Establishing
695 * a connection to the preferred network is taken care of when we handle
696 * the disconnect event from the non-preferred network
697 * (see {@link #handleDisconnect(NetworkInfo)}).
698 */
699 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700700 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800701 return;
702
Robert Greenwalt2034b912009-08-12 16:08:25 -0700703 if (!mNetTrackers[mNetworkPreference].isAvailable())
704 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800705
Robert Greenwalt2034b912009-08-12 16:08:25 -0700706 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700707 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700708 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700709 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800710 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700711 " in enforcePreference");
712 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700713 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800714 }
715 }
716 }
717
718 private boolean teardown(NetworkStateTracker netTracker) {
719 if (netTracker.teardown()) {
720 netTracker.setTeardownRequested(true);
721 return true;
722 } else {
723 return false;
724 }
725 }
726
727 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700728 * Check if UID should be blocked from using the network represented by the
729 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700730 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700731 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
732 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700733
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700734 final boolean networkCostly;
735 final int uidRules;
736 synchronized (mRulesLock) {
737 networkCostly = mMeteredIfaces.contains(iface);
738 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700739 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700740
741 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
742 return true;
743 }
744
745 // no restrictive rules; network is visible
746 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700747 }
748
749 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700750 * Return a filtered {@link NetworkInfo}, potentially marked
751 * {@link DetailedState#BLOCKED} based on
752 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700753 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700754 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
755 NetworkInfo info = tracker.getNetworkInfo();
756 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700757 // network is blocked; clone and override state
758 info = new NetworkInfo(info);
759 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700760 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700761 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700762 }
763
764 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800765 * Return NetworkInfo for the active (i.e., connected) network interface.
766 * It is assumed that at most one network is active at a time. If more
767 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700768 * @return the info for the active network, or {@code null} if none is
769 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800770 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700771 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800772 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700773 enforceAccessPermission();
774 final int uid = Binder.getCallingUid();
775 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 }
777
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700778 @Override
779 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
780 enforceConnectivityInternalPermission();
781 return getNetworkInfo(mActiveDefaultNetwork, uid);
782 }
783
784 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800785 public NetworkInfo getNetworkInfo(int networkType) {
786 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700787 final int uid = Binder.getCallingUid();
788 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789 }
790
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700791 private NetworkInfo getNetworkInfo(int networkType, int uid) {
792 NetworkInfo info = null;
793 if (isNetworkTypeValid(networkType)) {
794 final NetworkStateTracker tracker = mNetTrackers[networkType];
795 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700796 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700797 }
798 }
799 return info;
800 }
801
802 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800803 public NetworkInfo[] getAllNetworkInfo() {
804 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700805 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700806 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700807 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700808 for (NetworkStateTracker tracker : mNetTrackers) {
809 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700810 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700811 }
812 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700814 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800815 }
816
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700817 @Override
818 public boolean isNetworkSupported(int networkType) {
819 enforceAccessPermission();
820 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
821 }
822
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700823 /**
824 * Return LinkProperties for the active (i.e., connected) default
825 * network interface. It is assumed that at most one default network
826 * is active at a time. If more than one is active, it is indeterminate
827 * which will be returned.
828 * @return the ip properties for the active network, or {@code null} if
829 * none is active
830 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700831 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700832 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700833 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700834 }
835
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700836 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700837 public LinkProperties getLinkProperties(int networkType) {
838 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700839 if (isNetworkTypeValid(networkType)) {
840 final NetworkStateTracker tracker = mNetTrackers[networkType];
841 if (tracker != null) {
842 return tracker.getLinkProperties();
843 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700844 }
845 return null;
846 }
847
Jeff Sharkey21062e72011-05-28 20:56:34 -0700848 @Override
849 public NetworkState[] getAllNetworkState() {
850 enforceAccessPermission();
851 final int uid = Binder.getCallingUid();
852 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700853 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700854 for (NetworkStateTracker tracker : mNetTrackers) {
855 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700856 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700857 result.add(new NetworkState(
858 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
859 }
860 }
861 }
862 return result.toArray(new NetworkState[result.size()]);
863 }
864
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700865 private NetworkState getNetworkStateUnchecked(int networkType) {
866 if (isNetworkTypeValid(networkType)) {
867 final NetworkStateTracker tracker = mNetTrackers[networkType];
868 if (tracker != null) {
869 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
870 tracker.getLinkCapabilities());
871 }
872 }
873 return null;
874 }
875
876 @Override
877 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
878 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700879
880 final long token = Binder.clearCallingIdentity();
881 try {
882 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
883 if (state != null) {
884 try {
885 return mPolicyManager.getNetworkQuotaInfo(state);
886 } catch (RemoteException e) {
887 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700888 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700889 return null;
890 } finally {
891 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700892 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700893 }
894
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700895 @Override
896 public boolean isActiveNetworkMetered() {
897 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700898 final long token = Binder.clearCallingIdentity();
899 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700900 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700901 } finally {
902 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700903 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700904 }
905
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700906 private boolean isNetworkMeteredUnchecked(int networkType) {
907 final NetworkState state = getNetworkStateUnchecked(networkType);
908 if (state != null) {
909 try {
910 return mPolicyManager.isNetworkMetered(state);
911 } catch (RemoteException e) {
912 }
913 }
914 return false;
915 }
916
The Android Open Source Project28527d22009-03-03 19:31:44 -0800917 public boolean setRadios(boolean turnOn) {
918 boolean result = true;
919 enforceChangePermission();
920 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700921 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800922 }
923 return result;
924 }
925
926 public boolean setRadio(int netType, boolean turnOn) {
927 enforceChangePermission();
928 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
929 return false;
930 }
931 NetworkStateTracker tracker = mNetTrackers[netType];
932 return tracker != null && tracker.setRadio(turnOn);
933 }
934
Haoyu Baib5da5752012-06-20 14:29:57 -0700935 private class NetdObserver extends INetworkManagementEventObserver.Stub {
936 public void interfaceClassDataActivityChanged(String label, boolean active) {
937 int deviceType = Integer.parseInt(label);
938 sendDataActivityBroadcast(deviceType, active);
939 }
940
941 public void interfaceStatusChanged(String iface, boolean up) {}
942 public void interfaceLinkStateChanged(String iface, boolean up) {}
943 public void interfaceAdded(String iface) {}
944 public void interfaceRemoved(String iface) {}
945 public void limitReached(String limitName, String iface) {}
946 }
947
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700948 /**
949 * Used to notice when the calling process dies so we can self-expire
950 *
951 * Also used to know if the process has cleaned up after itself when
952 * our auto-expire timer goes off. The timer has a link to an object.
953 *
954 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700955 private class FeatureUser implements IBinder.DeathRecipient {
956 int mNetworkType;
957 String mFeature;
958 IBinder mBinder;
959 int mPid;
960 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800961 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700962
963 FeatureUser(int type, String feature, IBinder binder) {
964 super();
965 mNetworkType = type;
966 mFeature = feature;
967 mBinder = binder;
968 mPid = getCallingPid();
969 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800970 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700971
Robert Greenwalt2034b912009-08-12 16:08:25 -0700972 try {
973 mBinder.linkToDeath(this, 0);
974 } catch (RemoteException e) {
975 binderDied();
976 }
977 }
978
979 void unlinkDeathRecipient() {
980 mBinder.unlinkToDeath(this, 0);
981 }
982
983 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800984 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800985 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
986 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700987 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700988 }
989
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700990 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700991 if (VDBG) {
992 log("ConnectivityService FeatureUser expire(" +
993 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
994 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
995 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700996 stopUsingNetworkFeature(this, false);
997 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800998
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500999 public boolean isSameUser(FeatureUser u) {
1000 if (u == null) return false;
1001
1002 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1003 }
1004
1005 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1006 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1007 TextUtils.equals(mFeature, feature)) {
1008 return true;
1009 }
1010 return false;
1011 }
1012
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001013 public String toString() {
1014 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1015 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1016 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001017 }
1018
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001019 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001020 public int startUsingNetworkFeature(int networkType, String feature,
1021 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001022 long startTime = 0;
1023 if (DBG) {
1024 startTime = SystemClock.elapsedRealtime();
1025 }
Wink Savillea7d56572011-09-21 11:05:43 -07001026 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001027 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1028 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001029 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001031 try {
1032 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1033 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001034 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001035 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001036
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001037 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001038
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001039 // TODO - move this into individual networktrackers
1040 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001041
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001042 if (mProtectedNetworks.contains(usedNetworkType)) {
1043 enforceConnectivityInternalPermission();
1044 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001045
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001046 // if UID is restricted, don't allow them to bring up metered APNs
1047 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1048 final int uidRules;
1049 synchronized (mRulesLock) {
1050 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1051 }
1052 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001053 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001054 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001055
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001056 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1057 if (network != null) {
1058 Integer currentPid = new Integer(getCallingPid());
1059 if (usedNetworkType != networkType) {
1060 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001061
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001062 if (ni.isAvailable() == false) {
1063 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1064 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001065 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001066 } else {
1067 // else make the attempt anyway - probably giving REQUEST_STARTED below
1068 if (DBG) {
1069 log("special network not available, but try anyway ni=" +
1070 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001071 }
1072 }
1073 }
1074
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001075 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001076
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001077 synchronized(this) {
1078 boolean addToList = true;
1079 if (restoreTimer < 0) {
1080 // In case there is no timer is specified for the feature,
1081 // make sure we don't add duplicate entry with the same request.
1082 for (FeatureUser u : mFeatureUsers) {
1083 if (u.isSameUser(f)) {
1084 // Duplicate user is found. Do not add.
1085 addToList = false;
1086 break;
1087 }
1088 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001089 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001090
1091 if (addToList) mFeatureUsers.add(f);
1092 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1093 // this gets used for per-pid dns when connected
1094 mNetRequestersPids[usedNetworkType].add(currentPid);
1095 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001096 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001097
1098 if (restoreTimer >= 0) {
1099 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1100 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1101 }
1102
1103 if ((ni.isConnectedOrConnecting() == true) &&
1104 !network.isTeardownRequested()) {
1105 if (ni.isConnected() == true) {
1106 final long token = Binder.clearCallingIdentity();
1107 try {
1108 // add the pid-specific dns
1109 handleDnsConfigurationChange(usedNetworkType);
1110 if (VDBG) log("special network already active");
1111 } finally {
1112 Binder.restoreCallingIdentity(token);
1113 }
Wink Saville64e3f782012-07-10 12:37:54 -07001114 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001115 }
1116 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001117 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001118 }
1119
1120 // check if the radio in play can make another contact
1121 // assume if cannot for now
1122
1123 if (DBG) {
1124 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1125 feature);
1126 }
1127 network.reconnect();
Wink Saville64e3f782012-07-10 12:37:54 -07001128 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001129 } else {
1130 // need to remember this unsupported request so we respond appropriately on stop
1131 synchronized(this) {
1132 mFeatureUsers.add(f);
1133 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1134 // this gets used for per-pid dns when connected
1135 mNetRequestersPids[usedNetworkType].add(currentPid);
1136 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001137 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001138 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001139 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001140 }
Wink Saville64e3f782012-07-10 12:37:54 -07001141 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001142 } finally {
1143 if (DBG) {
1144 final long execTime = SystemClock.elapsedRealtime() - startTime;
1145 if (execTime > 250) {
1146 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1147 } else {
1148 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1149 }
1150 }
1151 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001152 }
1153
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001154 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001156 enforceChangePermission();
1157
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001158 int pid = getCallingPid();
1159 int uid = getCallingUid();
1160
1161 FeatureUser u = null;
1162 boolean found = false;
1163
1164 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001165 for (FeatureUser x : mFeatureUsers) {
1166 if (x.isSameUser(pid, uid, networkType, feature)) {
1167 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001168 found = true;
1169 break;
1170 }
1171 }
1172 }
1173 if (found && u != null) {
1174 // stop regardless of how many other time this proc had called start
1175 return stopUsingNetworkFeature(u, true);
1176 } else {
1177 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001178 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001179 return 1;
1180 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001181 }
1182
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001183 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1184 int networkType = u.mNetworkType;
1185 String feature = u.mFeature;
1186 int pid = u.mPid;
1187 int uid = u.mUid;
1188
1189 NetworkStateTracker tracker = null;
1190 boolean callTeardown = false; // used to carry our decision outside of sync block
1191
Wink Savillea7d56572011-09-21 11:05:43 -07001192 if (VDBG) {
1193 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001194 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001195
The Android Open Source Project28527d22009-03-03 19:31:44 -08001196 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001197 if (DBG) {
1198 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1199 ", net is invalid");
1200 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001201 return -1;
1202 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001203
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001204 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1205 // sync block
1206 synchronized(this) {
1207 // check if this process still has an outstanding start request
1208 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001209 if (VDBG) {
1210 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1211 ", ignoring");
1212 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001213 return 1;
1214 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001215 u.unlinkDeathRecipient();
1216 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1217 // If we care about duplicate requests, check for that here.
1218 //
1219 // This is done to support the extension of a request - the app
1220 // can request we start the network feature again and renew the
1221 // auto-shutoff delay. Normal "stop" calls from the app though
1222 // do not pay attention to duplicate requests - in effect the
1223 // API does not refcount and a single stop will counter multiple starts.
1224 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001225 for (FeatureUser x : mFeatureUsers) {
1226 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001227 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001228 return 1;
1229 }
1230 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001231 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001232
repo syncf5de5572011-07-29 23:55:49 -07001233 // TODO - move to individual network trackers
1234 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1235
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001236 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001237 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001238 if (DBG) {
1239 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1240 " no known tracker for used net type " + usedNetworkType);
1241 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001242 return -1;
1243 }
1244 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001245 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001246 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001247 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001248 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001249 if (VDBG) {
1250 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1251 " others still using it");
1252 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001253 return 1;
1254 }
1255 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001256 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001257 if (DBG) {
1258 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1259 " not a known feature - dropping");
1260 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001261 }
1262 }
Wink Savillea7d56572011-09-21 11:05:43 -07001263
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001264 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001265 if (DBG) {
1266 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1267 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001268 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001269 return 1;
1270 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001271 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001272 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001273 }
1274
1275 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001276 * @deprecated use requestRouteToHostAddress instead
1277 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001278 * Ensure that a network route exists to deliver traffic to the specified
1279 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001280 * @param networkType the type of the network over which traffic to the
1281 * specified host is to be routed
1282 * @param hostAddress the IP address of the host to which the route is
1283 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001284 * @return {@code true} on success, {@code false} on failure
1285 */
1286 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001287 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1288
1289 if (inetAddress == null) {
1290 return false;
1291 }
1292
1293 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1294 }
1295
1296 /**
1297 * Ensure that a network route exists to deliver traffic to the specified
1298 * host via the specified network interface.
1299 * @param networkType the type of the network over which traffic to the
1300 * specified host is to be routed
1301 * @param hostAddress the IP address of the host to which the route is
1302 * desired
1303 * @return {@code true} on success, {@code false} on failure
1304 */
1305 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001306 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001307 if (mProtectedNetworks.contains(networkType)) {
1308 enforceConnectivityInternalPermission();
1309 }
1310
The Android Open Source Project28527d22009-03-03 19:31:44 -08001311 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001312 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 return false;
1314 }
1315 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001316
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001317 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1318 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001319 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001320 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001321 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001322 }
1323 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001324 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001325 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001326 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001327 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001328 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001329 return addRouteToAddress(lp, addr);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001330 } catch (UnknownHostException e) {
1331 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1332 } finally {
1333 Binder.restoreCallingIdentity(token);
1334 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001335 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001336 }
1337
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001338 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1339 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001340 }
1341
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001342 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1343 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001344 }
1345
Robert Greenwalt98107422011-07-22 11:55:33 -07001346 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001347 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001348 }
1349
1350 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001351 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001352 }
1353
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001354 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1355 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001356 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1357 if (bestRoute == null) {
1358 bestRoute = RouteInfo.makeHostRoute(addr);
1359 } else {
1360 if (bestRoute.getGateway().equals(addr)) {
1361 // if there is no better route, add the implied hostroute for our gateway
1362 bestRoute = RouteInfo.makeHostRoute(addr);
1363 } else {
1364 // if we will connect to this through another route, add a direct route
1365 // to it's gateway
1366 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1367 }
1368 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001369 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001370 }
1371
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001372 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001373 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001374 if ((ifaceName == null) || (lp == null) || (r == null)) {
1375 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1376 return false;
1377 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001378
1379 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001380 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001381 return false;
1382 }
1383
1384 if (r.isHostRoute() == false) {
1385 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1386 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001387 if (bestRoute.getGateway().equals(r.getGateway())) {
1388 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001389 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001390 } else {
1391 // if we will connect to our gateway through another route, add a direct
1392 // route to it's gateway
1393 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001394 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001395 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001396 }
1397 }
1398 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001399 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001400 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001401 if (toDefaultTable) {
1402 mAddedRoutes.add(r); // only track default table - only one apps can effect
1403 mNetd.addRoute(ifaceName, r);
1404 } else {
1405 mNetd.addSecondaryRoute(ifaceName, r);
1406 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001407 } catch (Exception e) {
1408 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001409 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001410 return false;
1411 }
1412 } else {
1413 // if we remove this one and there are no more like it, then refcount==0 and
1414 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001415 if (toDefaultTable) {
1416 mAddedRoutes.remove(r);
1417 if (mAddedRoutes.contains(r) == false) {
1418 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1419 try {
1420 mNetd.removeRoute(ifaceName, r);
1421 } catch (Exception e) {
1422 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001423 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001424 return false;
1425 }
1426 } else {
1427 if (VDBG) log("not removing " + r + " as it's still in use");
1428 }
1429 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001430 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001431 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001432 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001433 } catch (Exception e) {
1434 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001435 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001436 return false;
1437 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001438 }
1439 }
1440 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001441 }
1442
1443 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001444 * @see ConnectivityManager#getMobileDataEnabled()
1445 */
1446 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001447 // TODO: This detail should probably be in DataConnectionTracker's
1448 // which is where we store the value and maybe make this
1449 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001450 enforceAccessPermission();
1451 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1452 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001453 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001454 return retVal;
1455 }
1456
Robert Greenwalt34848c02011-03-25 13:09:25 -07001457 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001458 enforceConnectivityInternalPermission();
1459
Robert Greenwalt34848c02011-03-25 13:09:25 -07001460 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1461 (met ? ENABLED : DISABLED), networkType));
1462 }
1463
1464 private void handleSetDependencyMet(int networkType, boolean met) {
1465 if (mNetTrackers[networkType] != null) {
1466 if (DBG) {
1467 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1468 }
1469 mNetTrackers[networkType].setDependencyMet(met);
1470 }
1471 }
1472
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001473 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1474 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001475 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001476 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001477 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001478 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001479 }
1480
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001481 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001482 // skip update when we've already applied rules
1483 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1484 if (oldRules == uidRules) return;
1485
1486 mUidRules.put(uid, uidRules);
1487 }
1488
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001489 // TODO: notify UID when it has requested targeted updates
1490 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001491
1492 @Override
1493 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001494 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001495 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001496 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001497 }
1498
1499 synchronized (mRulesLock) {
1500 mMeteredIfaces.clear();
1501 for (String iface : meteredIfaces) {
1502 mMeteredIfaces.add(iface);
1503 }
1504 }
1505 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001506
1507 @Override
1508 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1509 // caller is NPMS, since we only register with them
1510 if (LOGD_RULES) {
1511 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1512 }
1513
1514 // kick off connectivity change broadcast for active network, since
1515 // global background policy change is radical.
1516 final int networkType = mActiveDefaultNetwork;
1517 if (isNetworkTypeValid(networkType)) {
1518 final NetworkStateTracker tracker = mNetTrackers[networkType];
1519 if (tracker != null) {
1520 final NetworkInfo info = tracker.getNetworkInfo();
1521 if (info != null && info.isConnected()) {
1522 sendConnectedBroadcast(info);
1523 }
1524 }
1525 }
1526 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001527 };
1528
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001529 /**
1530 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1531 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001532 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001533 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001534 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001535
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001537 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001538 }
1539
1540 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001541 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001542 if (VDBG) {
1543 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001544 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001545 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1546 }
tk.mun5eee1042012-01-06 10:43:52 +09001547 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1548 if (VDBG) {
1549 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1550 }
1551 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1552 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001553 }
1554
1555 @Override
1556 public void setPolicyDataEnable(int networkType, boolean enabled) {
1557 // only someone like NPMS should only be calling us
1558 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1559
1560 mHandler.sendMessage(mHandler.obtainMessage(
1561 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1562 }
1563
1564 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1565 if (isNetworkTypeValid(networkType)) {
1566 final NetworkStateTracker tracker = mNetTrackers[networkType];
1567 if (tracker != null) {
1568 tracker.setPolicyDataEnable(enabled);
1569 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001570 }
1571 }
1572
The Android Open Source Project28527d22009-03-03 19:31:44 -08001573 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001574 mContext.enforceCallingOrSelfPermission(
1575 android.Manifest.permission.ACCESS_NETWORK_STATE,
1576 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001577 }
1578
1579 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001580 mContext.enforceCallingOrSelfPermission(
1581 android.Manifest.permission.CHANGE_NETWORK_STATE,
1582 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001583 }
1584
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001585 // TODO Make this a special check when it goes public
1586 private void enforceTetherChangePermission() {
1587 mContext.enforceCallingOrSelfPermission(
1588 android.Manifest.permission.CHANGE_NETWORK_STATE,
1589 "ConnectivityService");
1590 }
1591
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001592 private void enforceTetherAccessPermission() {
1593 mContext.enforceCallingOrSelfPermission(
1594 android.Manifest.permission.ACCESS_NETWORK_STATE,
1595 "ConnectivityService");
1596 }
1597
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001598 private void enforceConnectivityInternalPermission() {
1599 mContext.enforceCallingOrSelfPermission(
1600 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1601 "ConnectivityService");
1602 }
1603
The Android Open Source Project28527d22009-03-03 19:31:44 -08001604 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001605 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1606 * network, we ignore it. If it is for the active network, we send out a
1607 * broadcast. But first, we check whether it might be possible to connect
1608 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001609 * @param info the {@code NetworkInfo} for the network
1610 */
1611 private void handleDisconnect(NetworkInfo info) {
1612
Robert Greenwalt2034b912009-08-12 16:08:25 -07001613 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001614
Robert Greenwalt2034b912009-08-12 16:08:25 -07001615 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 /*
1617 * If the disconnected network is not the active one, then don't report
1618 * this as a loss of connectivity. What probably happened is that we're
1619 * getting the disconnect for a network that we explicitly disabled
1620 * in accordance with network preference policies.
1621 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001622 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001623 List pids = mNetRequestersPids[prevNetType];
1624 for (int i = 0; i<pids.size(); i++) {
1625 Integer pid = (Integer)pids.get(i);
1626 // will remove them because the net's no longer connected
1627 // need to do this now as only now do we know the pids and
1628 // can properly null things that are no longer referenced.
1629 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001630 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001631 }
1632
The Android Open Source Project28527d22009-03-03 19:31:44 -08001633 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1634 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1635 if (info.isFailover()) {
1636 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1637 info.setFailover(false);
1638 }
1639 if (info.getReason() != null) {
1640 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1641 }
1642 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001643 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1644 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001645 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001646
Robert Greenwalt34848c02011-03-25 13:09:25 -07001647 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001648 tryFailover(prevNetType);
1649 if (mActiveDefaultNetwork != -1) {
1650 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001651 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1652 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001653 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001654 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1655 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001656 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001657 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001658
1659 // Reset interface if no other connections are using the same interface
1660 boolean doReset = true;
1661 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1662 if (linkProperties != null) {
1663 String oldIface = linkProperties.getInterfaceName();
1664 if (TextUtils.isEmpty(oldIface) == false) {
1665 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1666 if (networkStateTracker == null) continue;
1667 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1668 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1669 LinkProperties l = networkStateTracker.getLinkProperties();
1670 if (l == null) continue;
1671 if (oldIface.equals(l.getInterfaceName())) {
1672 doReset = false;
1673 break;
1674 }
1675 }
1676 }
1677 }
1678 }
1679
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001680 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001681 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001682
Jeff Sharkey971cd162011-08-29 16:02:57 -07001683 final Intent immediateIntent = new Intent(intent);
1684 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1685 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001686 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001687 /*
1688 * If the failover network is already connected, then immediately send
1689 * out a followup broadcast indicating successful failover
1690 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001691 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001692 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1693 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001694 }
1695 }
1696
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001697 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001698 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001699 * If this is a default network, check if other defaults are available.
1700 * Try to reconnect on all available and let them hash it out when
1701 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001702 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001703 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001704 if (mActiveDefaultNetwork == prevNetType) {
1705 mActiveDefaultNetwork = -1;
1706 }
1707
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001708 // don't signal a reconnect for anything lower or equal priority than our
1709 // current connected default
1710 // TODO - don't filter by priority now - nice optimization but risky
1711// int currentPriority = -1;
1712// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001713// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001714// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001715 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001716 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001717 if (mNetConfigs[checkType] == null) continue;
1718 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001719 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001720
1721// Enabling the isAvailable() optimization caused mobile to not get
1722// selected if it was in the middle of error handling. Specifically
1723// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1724// would not be available and we wouldn't get connected to anything.
1725// So removing the isAvailable() optimization below for now. TODO: This
1726// optimization should work and we need to investigate why it doesn't work.
1727// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1728// complete before it is really complete.
1729// if (!mNetTrackers[checkType].isAvailable()) continue;
1730
Robert Greenwalt34848c02011-03-25 13:09:25 -07001731// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001732
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001733 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1734 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1735 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1736 checkInfo.setFailover(true);
1737 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001738 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001739 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001740 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001741 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001742 }
1743
1744 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001745 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1746 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001747 }
1748
Wink Saville4f0de1e2011-08-04 15:01:58 -07001749 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001750 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1751 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001752 }
1753
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001754 private void sendInetConditionBroadcast(NetworkInfo info) {
1755 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1756 }
1757
Wink Saville4f0de1e2011-08-04 15:01:58 -07001758 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001759 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001760 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1761 if (info.isFailover()) {
1762 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1763 info.setFailover(false);
1764 }
1765 if (info.getReason() != null) {
1766 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1767 }
1768 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001769 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1770 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001771 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001772 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001773 return intent;
1774 }
1775
1776 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1777 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1778 }
1779
1780 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1781 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001782 }
1783
Haoyu Baib5da5752012-06-20 14:29:57 -07001784 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1785 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1786 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1787 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1788 mContext.sendOrderedBroadcast(intent, RECEIVE_DATA_ACTIVITY_CHANGE);
1789 }
1790
The Android Open Source Project28527d22009-03-03 19:31:44 -08001791 /**
1792 * Called when an attempt to fail over to another network has failed.
1793 * @param info the {@link NetworkInfo} for the failed network
1794 */
1795 private void handleConnectionFailure(NetworkInfo info) {
1796 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001797
Robert Greenwalt2034b912009-08-12 16:08:25 -07001798 String reason = info.getReason();
1799 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001800
Robert Greenwalte981bc52010-10-08 16:35:52 -07001801 String reasonText;
1802 if (reason == null) {
1803 reasonText = ".";
1804 } else {
1805 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001806 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001807 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001808
1809 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1810 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1811 if (getActiveNetworkInfo() == null) {
1812 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1813 }
1814 if (reason != null) {
1815 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1816 }
1817 if (extraInfo != null) {
1818 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1819 }
1820 if (info.isFailover()) {
1821 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1822 info.setFailover(false);
1823 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001824
Robert Greenwalt34848c02011-03-25 13:09:25 -07001825 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001826 tryFailover(info.getType());
1827 if (mActiveDefaultNetwork != -1) {
1828 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001829 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1830 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001831 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001832 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1833 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001834 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001835
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001836 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001837
1838 final Intent immediateIntent = new Intent(intent);
1839 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1840 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001841 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001842 /*
1843 * If the failover network is already connected, then immediately send
1844 * out a followup broadcast indicating successful failover
1845 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001846 if (mActiveDefaultNetwork != -1) {
1847 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001848 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001849 }
1850
1851 private void sendStickyBroadcast(Intent intent) {
1852 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001853 if (!mSystemReady) {
1854 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001855 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001856 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001857 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001858 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001859 }
1860
Dianne Hackborna417ff82009-12-08 19:45:14 -08001861 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001862 }
1863 }
1864
Wink Saville4f0de1e2011-08-04 15:01:58 -07001865 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1866 if (delayMs <= 0) {
1867 sendStickyBroadcast(intent);
1868 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001869 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001870 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1871 + intent.getAction());
1872 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001873 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1874 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1875 }
1876 }
1877
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001878 void systemReady() {
1879 synchronized(this) {
1880 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001881 if (mInitialBroadcast != null) {
1882 mContext.sendStickyBroadcast(mInitialBroadcast);
1883 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001884 }
1885 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001886 // load the global proxy at startup
1887 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001888 }
1889
1890 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001891 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001892
1893 // snapshot isFailover, because sendConnectedBroadcast() resets it
1894 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001895 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001896
Robert Greenwalt2034b912009-08-12 16:08:25 -07001897 // if this is a default net and other default is running
1898 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001899 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001900 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1901 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001902 mNetConfigs[mActiveDefaultNetwork].priority >
1903 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001904 mNetworkPreference == mActiveDefaultNetwork) {
1905 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001906 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001907 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001908 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001909 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001910 teardown(thisNet);
1911 return;
1912 } else {
1913 // tear down the other
1914 NetworkStateTracker otherNet =
1915 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001916 if (DBG) {
1917 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001918 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001919 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001920 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001921 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001922 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001923 return;
1924 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001925 }
1926 }
1927 synchronized (ConnectivityService.this) {
1928 // have a new default network, release the transition wakelock in a second
1929 // if it's held. The second pause is to allow apps to reconnect over the
1930 // new network
1931 if (mNetTransitionWakeLock.isHeld()) {
1932 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001933 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001934 mNetTransitionWakeLockSerialNumber, 0),
1935 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001936 }
1937 }
1938 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001939 // this will cause us to come up initially as unconnected and switching
1940 // to connected after our normal pause unless somebody reports us as reall
1941 // disconnected
1942 mDefaultInetConditionPublished = 0;
1943 mDefaultConnectionSequence++;
1944 mInetConditionChangeInFlight = false;
1945 // Don't do this - if we never sign in stay, grey
1946 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001947 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001948 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001949 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001950 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001951 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001952
1953 // notify battery stats service about this network
1954 final String iface = thisNet.getLinkProperties().getInterfaceName();
1955 if (iface != null) {
1956 try {
1957 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1958 } catch (RemoteException e) {
1959 // ignored; service lives in system_server
1960 }
1961 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001962 }
1963
The Android Open Source Project28527d22009-03-03 19:31:44 -08001964 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001965 * After a change in the connectivity state of a network. We're mainly
1966 * concerned with making sure that the list of DNS servers is set up
1967 * according to which networks are connected, and ensuring that the
1968 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001969 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001970 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001971 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1972
The Android Open Source Project28527d22009-03-03 19:31:44 -08001973 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001974 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001975 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001976 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001977 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001978
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001979 LinkProperties curLp = mCurrentLinkProperties[netType];
1980 LinkProperties newLp = null;
1981
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001982 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001983 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001984 if (VDBG) {
1985 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1986 " doReset=" + doReset + " resetMask=" + resetMask +
1987 "\n curLp=" + curLp +
1988 "\n newLp=" + newLp);
1989 }
1990
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001991 if (curLp != null) {
1992 if (curLp.isIdenticalInterfaceName(newLp)) {
1993 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1994 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1995 for (LinkAddress linkAddr : car.removed) {
1996 if (linkAddr.getAddress() instanceof Inet4Address) {
1997 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1998 }
1999 if (linkAddr.getAddress() instanceof Inet6Address) {
2000 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2001 }
Wink Saville051a6642011-07-13 13:44:13 -07002002 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002003 if (DBG) {
2004 log("handleConnectivityChange: addresses changed" +
2005 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2006 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002007 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002008 } else {
2009 if (DBG) {
2010 log("handleConnectivityChange: address are the same reset per doReset" +
2011 " linkProperty[" + netType + "]:" +
2012 " resetMask=" + resetMask);
2013 }
Wink Saville051a6642011-07-13 13:44:13 -07002014 }
2015 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002016 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002017 if (DBG) {
2018 log("handleConnectivityChange: interface not not equivalent reset both" +
2019 " linkProperty[" + netType + "]:" +
2020 " resetMask=" + resetMask);
2021 }
Wink Saville051a6642011-07-13 13:44:13 -07002022 }
Wink Saville051a6642011-07-13 13:44:13 -07002023 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002024 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002025 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002026 }
2027 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002028 if (VDBG) {
2029 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2030 " doReset=" + doReset + " resetMask=" + resetMask +
2031 "\n curLp=" + curLp +
2032 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002033 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002034 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002035 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002036 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002037
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002038 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002039 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2040 if (linkProperties != null) {
2041 String iface = linkProperties.getInterfaceName();
2042 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002043 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07002044 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2045 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002046
2047 // Tell VPN the interface is down. It is a temporary
2048 // but effective fix to make VPN aware of the change.
2049 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2050 mVpn.interfaceStatusChanged(iface, false);
2051 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002052 }
2053 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07002054 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002055 try {
2056 mNetd.flushInterfaceDnsCache(iface);
2057 } catch (Exception e) {
2058 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07002059 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002060 }
2061 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002062 }
2063 }
2064 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002065
2066 // TODO: Temporary notifying upstread change to Tethering.
2067 // @see bug/4455071
2068 /** Notify TetheringService if interface name has been changed. */
2069 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002070 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002071 if (isTetheringSupported()) {
2072 mTethering.handleTetherIfaceChange();
2073 }
2074 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 }
2076
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002077 /**
2078 * Add and remove routes using the old properties (null if not previously connected),
2079 * new properties (null if becoming disconnected). May even be double null, which
2080 * is a noop.
2081 * Uses isLinkDefault to determine if default routes should be set or conversely if
2082 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002083 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002084 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002085 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2086 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002087 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002088 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2089 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002090 if (curLp != null) {
2091 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002092 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002093 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002094 } else if (newLp != null) {
2095 routeDiff.added = newLp.getRoutes();
2096 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002097 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002098
Robert Greenwalt8d777252011-08-15 12:31:55 -07002099 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2100
Robert Greenwalt98107422011-07-22 11:55:33 -07002101 for (RouteInfo r : routeDiff.removed) {
2102 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002103 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2104 }
2105 if (isLinkDefault == false) {
2106 // remove from a secondary route table
2107 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002108 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002109 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002110
Robert Greenwalt98107422011-07-22 11:55:33 -07002111 for (RouteInfo r : routeDiff.added) {
2112 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002113 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002114 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002115 // add to a secondary route table
2116 addRoute(newLp, r, TO_SECONDARY_TABLE);
2117
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002118 // many radios add a default route even when we don't want one.
2119 // remove the default route unless somebody else has asked for it
2120 String ifaceName = newLp.getInterfaceName();
2121 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002122 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002123 try {
2124 mNetd.removeRoute(ifaceName, r);
2125 } catch (Exception e) {
2126 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002127 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002128 }
2129 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002130 }
2131 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002132
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002133 if (!isLinkDefault) {
2134 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002135 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002136 // routes changed - remove all old dns entries and add new
2137 if (curLp != null) {
2138 for (InetAddress oldDns : curLp.getDnses()) {
2139 removeRouteToAddress(curLp, oldDns);
2140 }
2141 }
2142 if (newLp != null) {
2143 for (InetAddress newDns : newLp.getDnses()) {
2144 addRouteToAddress(newLp, newDns);
2145 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002146 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002147 } else {
2148 // no change in routes, check for change in dns themselves
2149 for (InetAddress oldDns : dnsDiff.removed) {
2150 removeRouteToAddress(curLp, oldDns);
2151 }
2152 for (InetAddress newDns : dnsDiff.added) {
2153 addRouteToAddress(newLp, newDns);
2154 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002155 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002156 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002157 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002158 }
2159
2160
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002161 /**
2162 * Reads the network specific TCP buffer sizes from SystemProperties
2163 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2164 * wide use
2165 */
2166 public void updateNetworkSettings(NetworkStateTracker nt) {
2167 String key = nt.getTcpBufferSizesPropName();
2168 String bufferSizes = SystemProperties.get(key);
2169
2170 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002171 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002172
2173 // Setting to default values so we won't be stuck to previous values
2174 key = "net.tcp.buffersize.default";
2175 bufferSizes = SystemProperties.get(key);
2176 }
2177
2178 // Set values in kernel
2179 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002180 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002181 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002182 + "] which comes from [" + key + "]");
2183 }
2184 setBufferSize(bufferSizes);
2185 }
2186 }
2187
2188 /**
2189 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2190 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2191 *
2192 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2193 * writeMin, writeInitial, writeMax"
2194 */
2195 private void setBufferSize(String bufferSizes) {
2196 try {
2197 String[] values = bufferSizes.split(",");
2198
2199 if (values.length == 6) {
2200 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002201 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2202 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2203 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2204 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2205 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2206 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002207 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002208 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002209 }
2210 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002211 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002212 }
2213 }
2214
Robert Greenwalt2034b912009-08-12 16:08:25 -07002215 /**
2216 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2217 * on the highest priority active net which this process requested.
2218 * If there aren't any, clear it out
2219 */
2220 private void reassessPidDns(int myPid, boolean doBump)
2221 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002222 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002223 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002224 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002225 continue;
2226 }
2227 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002228 if (nt.getNetworkInfo().isConnected() &&
2229 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002230 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002231 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002232 List pids = mNetRequestersPids[i];
2233 for (int j=0; j<pids.size(); j++) {
2234 Integer pid = (Integer)pids.get(j);
2235 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002236 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002237 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002238 if (doBump) {
2239 bumpDns();
2240 }
2241 return;
2242 }
2243 }
2244 }
2245 }
2246 // nothing found - delete
2247 for (int i = 1; ; i++) {
2248 String prop = "net.dns" + i + "." + myPid;
2249 if (SystemProperties.get(prop).length() == 0) {
2250 if (doBump) {
2251 bumpDns();
2252 }
2253 return;
2254 }
2255 SystemProperties.set(prop, "");
2256 }
2257 }
2258
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002259 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002260 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002261 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002262 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002263 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002264 String dnsString = dns.getHostAddress();
2265 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2266 changed = true;
yoonsung.nam48d18332012-03-02 19:56:16 +09002267 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002268 }
yoonsung.nam48d18332012-03-02 19:56:16 +09002269 j++;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002270 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002271 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002272 }
2273
2274 private void bumpDns() {
2275 /*
2276 * Bump the property that tells the name resolver library to reread
2277 * the DNS server list from the properties.
2278 */
2279 String propVal = SystemProperties.get("net.dnschange");
2280 int n = 0;
2281 if (propVal.length() != 0) {
2282 try {
2283 n = Integer.parseInt(propVal);
2284 } catch (NumberFormatException e) {}
2285 }
2286 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002287 /*
2288 * Tell the VMs to toss their DNS caches
2289 */
2290 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2291 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002292 /*
2293 * Connectivity events can happen before boot has completed ...
2294 */
2295 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002296 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002297 }
2298
Chia-chi Yehcc844502011-07-14 18:01:57 -07002299 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002300 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002301 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002302 boolean changed = false;
2303 int last = 0;
2304 if (dnses.size() == 0 && mDefaultDns != null) {
2305 ++last;
2306 String value = mDefaultDns.getHostAddress();
2307 if (!value.equals(SystemProperties.get("net.dns1"))) {
2308 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002309 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002310 }
2311 changed = true;
2312 SystemProperties.set("net.dns1", value);
2313 }
2314 } else {
2315 for (InetAddress dns : dnses) {
2316 ++last;
2317 String key = "net.dns" + last;
2318 String value = dns.getHostAddress();
2319 if (!changed && value.equals(SystemProperties.get(key))) {
2320 continue;
2321 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002322 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002323 log("adding dns " + value + " for " + network);
2324 }
2325 changed = true;
2326 SystemProperties.set(key, value);
2327 }
2328 }
2329 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2330 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002331 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002332 changed = true;
2333 SystemProperties.set(key, "");
2334 }
2335 mNumDnsEntries = last;
2336
Robert Greenwaltfce71862011-07-25 16:06:25 -07002337 if (changed) {
2338 try {
2339 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2340 mNetd.setDefaultInterfaceForDns(iface);
2341 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002342 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002343 }
2344 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002345 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2346 SystemProperties.set("net.dns.search", domains);
2347 changed = true;
2348 }
2349 return changed;
2350 }
2351
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002352 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002353 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002354 NetworkStateTracker nt = mNetTrackers[netType];
2355 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002356 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002357 if (p == null) return;
2358 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002359 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002360 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002361 String network = nt.getNetworkInfo().getTypeName();
2362 synchronized (mDnsLock) {
2363 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002364 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002365 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002366 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002367 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002368 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002369 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002370 NetworkUtils.makeStrings(dnses));
2371 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002372 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002373 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002374 // set per-pid dns for attached secondary nets
2375 List pids = mNetRequestersPids[netType];
2376 for (int y=0; y< pids.size(); y++) {
2377 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002378 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002379 }
2380 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002381 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002382 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002383 }
2384
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002385 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002386 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2387 NETWORK_RESTORE_DELAY_PROP_NAME);
2388 if(restoreDefaultNetworkDelayStr != null &&
2389 restoreDefaultNetworkDelayStr.length() != 0) {
2390 try {
2391 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2392 } catch (NumberFormatException e) {
2393 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002394 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002395 // if the system property isn't set, use the value for the apn type
2396 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2397
2398 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2399 (mNetConfigs[networkType] != null)) {
2400 ret = mNetConfigs[networkType].restoreTime;
2401 }
2402 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002403 }
2404
2405 @Override
2406 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002407 if (mContext.checkCallingOrSelfPermission(
2408 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002409 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002410 pw.println("Permission Denial: can't dump ConnectivityService " +
2411 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2412 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002413 return;
2414 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002415 pw.println();
2416 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002417 if (nst != null) {
2418 if (nst.getNetworkInfo().isConnected()) {
2419 pw.println("Active network: " + nst.getNetworkInfo().
2420 getTypeName());
2421 }
2422 pw.println(nst.getNetworkInfo());
2423 pw.println(nst);
2424 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002425 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002426 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002427
2428 pw.println("Network Requester Pids:");
2429 for (int net : mPriorityList) {
2430 String pidString = net + ": ";
2431 for (Object pid : mNetRequestersPids[net]) {
2432 pidString = pidString + pid.toString() + ", ";
2433 }
2434 pw.println(pidString);
2435 }
2436 pw.println();
2437
2438 pw.println("FeatureUsers:");
2439 for (Object requester : mFeatureUsers) {
2440 pw.println(requester.toString());
2441 }
2442 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002443
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002444 synchronized (this) {
2445 pw.println("NetworkTranstionWakeLock is currently " +
2446 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2447 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2448 }
2449 pw.println();
2450
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002451 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002452
2453 if (mInetLog != null) {
2454 pw.println();
2455 pw.println("Inet condition reports:");
2456 for(int i = 0; i < mInetLog.size(); i++) {
2457 pw.println(mInetLog.get(i));
2458 }
2459 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002460 }
2461
Robert Greenwalt2034b912009-08-12 16:08:25 -07002462 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002463 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002464 public MyHandler(Looper looper) {
2465 super(looper);
2466 }
2467
The Android Open Source Project28527d22009-03-03 19:31:44 -08002468 @Override
2469 public void handleMessage(Message msg) {
2470 NetworkInfo info;
2471 switch (msg.what) {
2472 case NetworkStateTracker.EVENT_STATE_CHANGED:
2473 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002474 int type = info.getType();
2475 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002476
Wink Savillea7d56572011-09-21 11:05:43 -07002477 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2478 (state == NetworkInfo.State.DISCONNECTED)) {
2479 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002480 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002481 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002482 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002483
2484 // Connectivity state changed:
Robert Greenwalt310fa082012-04-25 13:45:02 -07002485 // [31-14] Reserved for future use
2486 // [13-10] Network subtype (for mobile network, as defined
Robert Greenwalt0659da32009-07-16 17:21:39 -07002487 // by TelephonyManager)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002488 // [9-4] Detailed state ordinal (as defined by
Robert Greenwalt0659da32009-07-16 17:21:39 -07002489 // NetworkInfo.DetailedState)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002490 // [3-0] Network type (as defined by ConnectivityManager)
2491 int eventLogParam = (info.getType() & 0xf) |
2492 ((info.getDetailedState().ordinal() & 0x3f) << 4) |
2493 (info.getSubtype() << 10);
Doug Zongker2fc96232009-12-04 10:31:43 -08002494 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002495 eventLogParam);
2496
2497 if (info.getDetailedState() ==
2498 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002499 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002500 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002501 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002502 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002503 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002504 // the logic here is, handle SUSPENDED the same as
2505 // DISCONNECTED. The only difference being we are
2506 // broadcasting an intent with NetworkInfo that's
2507 // suspended. This allows the applications an
2508 // opportunity to handle DISCONNECTED and SUSPENDED
2509 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002510 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002511 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002512 handleConnect(info);
2513 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002514 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002515 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002516 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002517 // TODO: Temporary allowing network configuration
2518 // change not resetting sockets.
2519 // @see bug/4455071
2520 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002521 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002522 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002523 String causedBy = null;
2524 synchronized (ConnectivityService.this) {
2525 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2526 mNetTransitionWakeLock.isHeld()) {
2527 mNetTransitionWakeLock.release();
2528 causedBy = mNetTransitionWakeLockCausedBy;
2529 }
2530 }
2531 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002532 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002533 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002534 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002535 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002536 FeatureUser u = (FeatureUser)msg.obj;
2537 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002538 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002539 case EVENT_INET_CONDITION_CHANGE:
2540 {
2541 int netType = msg.arg1;
2542 int condition = msg.arg2;
2543 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002544 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002545 }
2546 case EVENT_INET_CONDITION_HOLD_END:
2547 {
2548 int netType = msg.arg1;
2549 int sequence = msg.arg2;
2550 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002551 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002552 }
2553 case EVENT_SET_NETWORK_PREFERENCE:
2554 {
2555 int preference = msg.arg1;
2556 handleSetNetworkPreference(preference);
2557 break;
2558 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002559 case EVENT_SET_MOBILE_DATA:
2560 {
2561 boolean enabled = (msg.arg1 == ENABLED);
2562 handleSetMobileData(enabled);
2563 break;
2564 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002565 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2566 {
2567 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002568 break;
2569 }
2570 case EVENT_SET_DEPENDENCY_MET:
2571 {
2572 boolean met = (msg.arg1 == ENABLED);
2573 handleSetDependencyMet(msg.arg2, met);
2574 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002575 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002576 case EVENT_RESTORE_DNS:
2577 {
2578 if (mActiveDefaultNetwork != -1) {
2579 handleDnsConfigurationChange(mActiveDefaultNetwork);
2580 }
2581 break;
2582 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002583 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2584 {
2585 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002586 sendStickyBroadcast(intent);
2587 break;
2588 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002589 case EVENT_SET_POLICY_DATA_ENABLE: {
2590 final int networkType = msg.arg1;
2591 final boolean enabled = msg.arg2 == ENABLED;
2592 handleSetPolicyDataEnable(networkType, enabled);
2593 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002594 }
2595 }
2596 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002597
2598 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002599 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002600 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002601
2602 if (isTetheringSupported()) {
2603 return mTethering.tether(iface);
2604 } else {
2605 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2606 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002607 }
2608
2609 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002610 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002611 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002612
2613 if (isTetheringSupported()) {
2614 return mTethering.untether(iface);
2615 } else {
2616 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2617 }
2618 }
2619
2620 // javadoc from interface
2621 public int getLastTetherError(String iface) {
2622 enforceTetherAccessPermission();
2623
2624 if (isTetheringSupported()) {
2625 return mTethering.getLastTetherError(iface);
2626 } else {
2627 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2628 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002629 }
2630
2631 // TODO - proper iface API for selection by property, inspection, etc
2632 public String[] getTetherableUsbRegexs() {
2633 enforceTetherAccessPermission();
2634 if (isTetheringSupported()) {
2635 return mTethering.getTetherableUsbRegexs();
2636 } else {
2637 return new String[0];
2638 }
2639 }
2640
2641 public String[] getTetherableWifiRegexs() {
2642 enforceTetherAccessPermission();
2643 if (isTetheringSupported()) {
2644 return mTethering.getTetherableWifiRegexs();
2645 } else {
2646 return new String[0];
2647 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002648 }
2649
Danica Chang96567052010-08-11 14:54:43 -07002650 public String[] getTetherableBluetoothRegexs() {
2651 enforceTetherAccessPermission();
2652 if (isTetheringSupported()) {
2653 return mTethering.getTetherableBluetoothRegexs();
2654 } else {
2655 return new String[0];
2656 }
2657 }
2658
Mike Lockwooded4a1742011-07-19 13:04:47 -07002659 public int setUsbTethering(boolean enable) {
2660 enforceTetherAccessPermission();
2661 if (isTetheringSupported()) {
2662 return mTethering.setUsbTethering(enable);
2663 } else {
2664 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2665 }
2666 }
2667
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002668 // TODO - move iface listing, queries, etc to new module
2669 // javadoc from interface
2670 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002671 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002672 return mTethering.getTetherableIfaces();
2673 }
2674
2675 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002676 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002677 return mTethering.getTetheredIfaces();
2678 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002679
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002680 @Override
2681 public String[] getTetheredIfacePairs() {
2682 enforceTetherAccessPermission();
2683 return mTethering.getTetheredIfacePairs();
2684 }
2685
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002686 public String[] getTetheringErroredIfaces() {
2687 enforceTetherAccessPermission();
2688 return mTethering.getErroredIfaces();
2689 }
2690
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002691 // if ro.tether.denied = true we default to no tethering
2692 // gservices could set the secure setting to 1 though to enable it on a build where it
2693 // had previously been turned off.
2694 public boolean isTetheringSupported() {
2695 enforceTetherAccessPermission();
2696 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002697 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2698 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2699 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002700 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002701
2702 // An API NetworkStateTrackers can call when they lose their network.
2703 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2704 // whichever happens first. The timer is started by the first caller and not
2705 // restarted by subsequent callers.
2706 public void requestNetworkTransitionWakelock(String forWhom) {
2707 enforceConnectivityInternalPermission();
2708 synchronized (this) {
2709 if (mNetTransitionWakeLock.isHeld()) return;
2710 mNetTransitionWakeLockSerialNumber++;
2711 mNetTransitionWakeLock.acquire();
2712 mNetTransitionWakeLockCausedBy = forWhom;
2713 }
2714 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002715 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002716 mNetTransitionWakeLockSerialNumber, 0),
2717 mNetTransitionWakeLockTimeout);
2718 return;
2719 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002720
Robert Greenwalt986c7412010-09-08 15:24:47 -07002721 // 100 percent is full good, 0 is full bad.
2722 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002723 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002724 mContext.enforceCallingOrSelfPermission(
2725 android.Manifest.permission.STATUS_BAR,
2726 "ConnectivityService");
2727
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002728 if (DBG) {
2729 int pid = getCallingPid();
2730 int uid = getCallingUid();
2731 String s = pid + "(" + uid + ") reports inet is " +
2732 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2733 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2734 mInetLog.add(s);
2735 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2736 mInetLog.remove(0);
2737 }
2738 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002739 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002740 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2741 }
2742
2743 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002744 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002745 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002746 return;
2747 }
2748 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002749 if (DBG) log("handleInetConditionChange: net=" + netType +
2750 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002751 return;
2752 }
Wink Savillea7d56572011-09-21 11:05:43 -07002753 if (VDBG) {
2754 log("handleInetConditionChange: net=" +
2755 netType + ", condition=" + condition +
2756 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2757 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002758 mDefaultInetCondition = condition;
2759 int delay;
2760 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002761 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002762 // setup a new hold to debounce this
2763 if (mDefaultInetCondition > 50) {
2764 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2765 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2766 } else {
2767 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2768 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2769 }
2770 mInetConditionChangeInFlight = true;
2771 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2772 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2773 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002774 // we've set the new condition, when this hold ends that will get picked up
2775 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002776 }
2777 }
2778
2779 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002780 if (DBG) {
2781 log("handleInetConditionHoldEnd: net=" + netType +
2782 ", condition=" + mDefaultInetCondition +
2783 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002784 }
2785 mInetConditionChangeInFlight = false;
2786
2787 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002788 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002789 return;
2790 }
2791 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002792 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002793 return;
2794 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002795 // TODO: Figure out why this optimization sometimes causes a
2796 // change in mDefaultInetCondition to be missed and the
2797 // UI to not be updated.
2798 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2799 // if (DBG) log("no change in condition - aborting");
2800 // return;
2801 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002802 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2803 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002804 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002805 return;
2806 }
2807 mDefaultInetConditionPublished = mDefaultInetCondition;
2808 sendInetConditionBroadcast(networkInfo);
2809 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002810 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002811
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002812 public ProxyProperties getProxy() {
2813 synchronized (mDefaultProxyLock) {
2814 return mDefaultProxyDisabled ? null : mDefaultProxy;
2815 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002816 }
2817
2818 public void setGlobalProxy(ProxyProperties proxyProperties) {
2819 enforceChangePermission();
2820 synchronized (mGlobalProxyLock) {
2821 if (proxyProperties == mGlobalProxy) return;
2822 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2823 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2824
2825 String host = "";
2826 int port = 0;
2827 String exclList = "";
2828 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2829 mGlobalProxy = new ProxyProperties(proxyProperties);
2830 host = mGlobalProxy.getHost();
2831 port = mGlobalProxy.getPort();
2832 exclList = mGlobalProxy.getExclusionList();
2833 } else {
2834 mGlobalProxy = null;
2835 }
2836 ContentResolver res = mContext.getContentResolver();
2837 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2838 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002839 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002840 exclList);
2841 }
2842
2843 if (mGlobalProxy == null) {
2844 proxyProperties = mDefaultProxy;
2845 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002846 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002847 }
2848
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002849 private void loadGlobalProxy() {
2850 ContentResolver res = mContext.getContentResolver();
2851 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2852 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2853 String exclList = Settings.Secure.getString(res,
2854 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2855 if (!TextUtils.isEmpty(host)) {
2856 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2857 synchronized (mGlobalProxyLock) {
2858 mGlobalProxy = proxyProperties;
2859 }
2860 }
2861 }
2862
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002863 public ProxyProperties getGlobalProxy() {
2864 synchronized (mGlobalProxyLock) {
2865 return mGlobalProxy;
2866 }
2867 }
2868
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002869 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2870 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2871 proxy = null;
2872 }
2873 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002874 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2875 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002876 mDefaultProxy = proxy;
2877
2878 if (!mDefaultProxyDisabled) {
2879 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002880 }
2881 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002882 }
2883
2884 private void handleDeprecatedGlobalHttpProxy() {
2885 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2886 Settings.Secure.HTTP_PROXY);
2887 if (!TextUtils.isEmpty(proxy)) {
2888 String data[] = proxy.split(":");
2889 String proxyHost = data[0];
2890 int proxyPort = 8080;
2891 if (data.length > 1) {
2892 try {
2893 proxyPort = Integer.parseInt(data[1]);
2894 } catch (NumberFormatException e) {
2895 return;
2896 }
2897 }
2898 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2899 setGlobalProxy(p);
2900 }
2901 }
2902
2903 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002904 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002905 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002906 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002907 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2908 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002909 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002910 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002911 }
2912
2913 private static class SettingsObserver extends ContentObserver {
2914 private int mWhat;
2915 private Handler mHandler;
2916 SettingsObserver(Handler handler, int what) {
2917 super(handler);
2918 mHandler = handler;
2919 mWhat = what;
2920 }
2921
2922 void observe(Context context) {
2923 ContentResolver resolver = context.getContentResolver();
2924 resolver.registerContentObserver(Settings.Secure.getUriFor(
2925 Settings.Secure.HTTP_PROXY), false, this);
2926 }
2927
2928 @Override
2929 public void onChange(boolean selfChange) {
2930 mHandler.obtainMessage(mWhat).sendToTarget();
2931 }
2932 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002933
2934 private void log(String s) {
2935 Slog.d(TAG, s);
2936 }
2937
2938 private void loge(String s) {
2939 Slog.e(TAG, s);
2940 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002941
repo syncf5de5572011-07-29 23:55:49 -07002942 int convertFeatureToNetworkType(int networkType, String feature) {
2943 int usedNetworkType = networkType;
2944
2945 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2946 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2947 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2948 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2949 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2950 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2951 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2952 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2953 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2954 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2955 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2956 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2957 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2958 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2959 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2960 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2961 } else {
2962 Slog.e(TAG, "Can't match any mobile netTracker!");
2963 }
2964 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2965 if (TextUtils.equals(feature, "p2p")) {
2966 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2967 } else {
2968 Slog.e(TAG, "Can't match any wifi netTracker!");
2969 }
2970 } else {
2971 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002972 }
repo syncf5de5572011-07-29 23:55:49 -07002973 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002974 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002975
2976 private static <T> T checkNotNull(T value, String message) {
2977 if (value == null) {
2978 throw new NullPointerException(message);
2979 }
2980 return value;
2981 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002982
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002983 /**
2984 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002985 * VpnBuilder and not available in ConnectivityManager. Permissions
2986 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002987 * @hide
2988 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002989 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002990 public boolean protectVpn(ParcelFileDescriptor socket) {
2991 try {
2992 int type = mActiveDefaultNetwork;
2993 if (ConnectivityManager.isNetworkTypeValid(type)) {
2994 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2995 return true;
2996 }
2997 } catch (Exception e) {
2998 // ignore
2999 } finally {
3000 try {
3001 socket.close();
3002 } catch (Exception e) {
3003 // ignore
3004 }
3005 }
3006 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003007 }
3008
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003009 /**
3010 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003011 * and not available in ConnectivityManager. Permissions are checked
3012 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003013 * @hide
3014 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003015 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003016 public boolean prepareVpn(String oldPackage, String newPackage) {
3017 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003018 }
3019
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003020 /**
3021 * Configure a TUN interface and return its file descriptor. Parameters
3022 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003023 * and not available in ConnectivityManager. Permissions are checked in
3024 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003025 * @hide
3026 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003027 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003028 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003029 return mVpn.establish(config);
3030 }
3031
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003032 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003033 * Start legacy VPN and return an intent to VpnDialogs. This method is
3034 * used by VpnSettings and not available in ConnectivityManager.
3035 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003036 * @hide
3037 */
3038 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003039 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
3040 mVpn.startLegacyVpn(config, racoon, mtpd);
3041 }
3042
3043 /**
3044 * Return the information of the ongoing legacy VPN. This method is used
3045 * by VpnSettings and not available in ConnectivityManager. Permissions
3046 * are checked in Vpn class.
3047 * @hide
3048 */
3049 @Override
3050 public LegacyVpnInfo getLegacyVpnInfo() {
3051 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003052 }
3053
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003054 /**
3055 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3056 * through NetworkStateTracker since it works differently. For example, it
3057 * needs to override DNS servers but never takes the default routes. It
3058 * relies on another data network, and it could keep existing connections
3059 * alive after reconnecting, switching between networks, or even resuming
3060 * from deep sleep. Calls from applications should be done synchronously
3061 * to avoid race conditions. As these are all hidden APIs, refactoring can
3062 * be done whenever a better abstraction is developed.
3063 */
3064 public class VpnCallback {
3065
3066 private VpnCallback() {
3067 }
3068
Chia-chi Yehcc844502011-07-14 18:01:57 -07003069 public void override(List<String> dnsServers, List<String> searchDomains) {
3070 if (dnsServers == null) {
3071 restore();
3072 return;
3073 }
3074
3075 // Convert DNS servers into addresses.
3076 List<InetAddress> addresses = new ArrayList<InetAddress>();
3077 for (String address : dnsServers) {
3078 // Double check the addresses and remove invalid ones.
3079 try {
3080 addresses.add(InetAddress.parseNumericAddress(address));
3081 } catch (Exception e) {
3082 // ignore
3083 }
3084 }
3085 if (addresses.isEmpty()) {
3086 restore();
3087 return;
3088 }
3089
3090 // Concatenate search domains into a string.
3091 StringBuilder buffer = new StringBuilder();
3092 if (searchDomains != null) {
3093 for (String domain : searchDomains) {
3094 buffer.append(domain).append(' ');
3095 }
3096 }
3097 String domains = buffer.toString().trim();
3098
3099 // Apply DNS changes.
3100 boolean changed = false;
3101 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07003102 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003103 mDnsOverridden = true;
3104 }
3105 if (changed) {
3106 bumpDns();
3107 }
3108
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003109 // Temporarily disable the default proxy.
3110 synchronized (mDefaultProxyLock) {
3111 mDefaultProxyDisabled = true;
3112 if (mDefaultProxy != null) {
3113 sendProxyBroadcast(null);
3114 }
3115 }
3116
3117 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003118 }
3119
Chia-chi Yehcc844502011-07-14 18:01:57 -07003120 public void restore() {
3121 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003122 if (mDnsOverridden) {
3123 mDnsOverridden = false;
3124 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003125 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003126 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003127 synchronized (mDefaultProxyLock) {
3128 mDefaultProxyDisabled = false;
3129 if (mDefaultProxy != null) {
3130 sendProxyBroadcast(mDefaultProxy);
3131 }
3132 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003133 }
3134 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003135}