blob: eab60a79ee96f7f2e62c469feb71be389e104ea9 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey971cd162011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070022import static android.net.ConnectivityManager.isNetworkTypeValid;
23import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070024import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070025
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080026import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080027import android.content.ContentResolver;
28import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090029import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.content.Intent;
31import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090032import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070033import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080035import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080036import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080037import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070038import android.net.INetworkPolicyListener;
39import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070040import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070041import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080042import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070043import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070045import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070047import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070048import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070049import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080050import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070051import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070052import android.net.Proxy;
53import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070054import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080055import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090056import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040058import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070060import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070061import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070062import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.os.Looper;
64import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070065import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070066import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070067import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068import android.os.ServiceManager;
69import android.os.SystemProperties;
70import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070071import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080073import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070074import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070076import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070077import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070078import com.android.internal.telephony.Phone;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -070079import com.android.server.am.BatteryStatsService;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080080import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070081import com.android.server.connectivity.Vpn;
Jeff Sharkey21062e72011-05-28 20:56:34 -070082import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070083import com.google.android.collect.Sets;
tk.mun093f55c2011-10-13 22:51:57 +090084import dalvik.system.DexClassLoader;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070086import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080087import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +090088import java.lang.reflect.Constructor;
89import java.lang.reflect.Method;
90import java.lang.reflect.Modifier;
91import java.lang.reflect.InvocationTargetException;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070092import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070093import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070094import java.net.InetAddress;
95import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070096import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070097import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070098import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070099import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700100import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700101import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102
103/**
104 * @hide
105 */
106public class ConnectivityService extends IConnectivityManager.Stub {
107
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700108 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700109 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110 private static final String TAG = "ConnectivityService";
111
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700112 private static final boolean LOGD_RULES = false;
113
Robert Greenwalt2034b912009-08-12 16:08:25 -0700114 // how long to wait before switching back to a radio's default network
115 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
116 // system property that can override the above value
117 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
118 "android.telephony.apn-restore";
119
Robert Greenwaltbd492212011-05-06 17:10:53 -0700120 // used in recursive route setting to add gateways for the host for which
121 // a host route was requested.
122 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
123
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800124 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800125 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800126
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700127 private Vpn mVpn;
128
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700129 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
130 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700131 /** Currently active network rules by UID. */
132 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700133 /** Set of ifaces that are costly. */
134 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700135
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136 /**
137 * Sometimes we want to refer to the individual network state
138 * trackers separately, and sometimes we just want to treat them
139 * abstractly.
140 */
141 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700142
143 /**
Wink Saville051a6642011-07-13 13:44:13 -0700144 * The link properties that define the current links
145 */
146 private LinkProperties mCurrentLinkProperties[];
147
148 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700149 * A per Net list of the PID's that requested access to the net
150 * used both as a refcount and for per-PID DNS selection
151 */
152 private List mNetRequestersPids[];
153
Robert Greenwalt2034b912009-08-12 16:08:25 -0700154 // priority order of the nettrackers
155 // (excluding dynamically set mNetworkPreference)
156 // TODO - move mNetworkTypePreference into this
157 private int[] mPriorityList;
158
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159 private Context mContext;
160 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700161 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700162 // 0 is full bad, 100 is full good
163 private int mDefaultInetCondition = 0;
164 private int mDefaultInetConditionPublished = 0;
165 private boolean mInetConditionChangeInFlight = false;
166 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800167
Chia-chi Yehcc844502011-07-14 18:01:57 -0700168 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800169 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700170 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800171
172 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700173 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800174
Robert Greenwalt355205c2011-05-10 15:05:02 -0700175 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700176 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700177
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700178 private static final int ENABLED = 1;
179 private static final int DISABLED = 0;
180
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700181 private static final boolean ADD = true;
182 private static final boolean REMOVE = false;
183
184 private static final boolean TO_DEFAULT_TABLE = true;
185 private static final boolean TO_SECONDARY_TABLE = false;
186
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700187 // Share the event space with NetworkStateTracker (which can't see this
188 // internal class but sends us events). If you change these, change
189 // NetworkStateTracker.java too.
190 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
191 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
192
193 /**
194 * used internally as a delayed event to make us switch back to the
195 * default network
196 */
197 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
198 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
199
200 /**
201 * used internally to change our mobile data enabled flag
202 */
203 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
204 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
205
206 /**
207 * used internally to change our network preference setting
208 * arg1 = networkType to prefer
209 */
210 private static final int EVENT_SET_NETWORK_PREFERENCE =
211 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
212
213 /**
214 * used internally to synchronize inet condition reports
215 * arg1 = networkType
216 * arg2 = condition (0 bad, 100 good)
217 */
218 private static final int EVENT_INET_CONDITION_CHANGE =
219 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
220
221 /**
222 * used internally to mark the end of inet condition hold periods
223 * arg1 = networkType
224 */
225 private static final int EVENT_INET_CONDITION_HOLD_END =
226 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
227
228 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700229 * used internally to set enable/disable cellular data
230 * arg1 = ENBALED or DISABLED
231 */
232 private static final int EVENT_SET_MOBILE_DATA =
233 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
234
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700235 /**
236 * used internally to clear a wakelock when transitioning
237 * from one net to another
238 */
239 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
240 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
241
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700242 /**
243 * used internally to reload global proxy settings
244 */
245 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
246 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
247
Robert Greenwalt34848c02011-03-25 13:09:25 -0700248 /**
249 * used internally to set external dependency met/unmet
250 * arg1 = ENABLED (met) or DISABLED (unmet)
251 * arg2 = NetworkType
252 */
253 private static final int EVENT_SET_DEPENDENCY_MET =
254 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
255
Chia-chi Yehcc844502011-07-14 18:01:57 -0700256 /**
257 * used internally to restore DNS properties back to the
258 * default network
259 */
260 private static final int EVENT_RESTORE_DNS =
261 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
262
Wink Saville7e4333c2011-08-05 11:40:22 -0700263 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700264 * used internally to send a sticky broadcast delayed.
265 */
266 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville7e4333c2011-08-05 11:40:22 -0700267 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700268
Jeff Sharkey805662d2011-08-19 02:24:24 -0700269 /**
270 * Used internally to
271 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
272 */
273 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
274
Robert Greenwalt2034b912009-08-12 16:08:25 -0700275 private Handler mHandler;
276
277 // list of DeathRecipients used to make sure features are turned off when
278 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500279 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700280
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400281 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800282 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400283
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700284 private PowerManager.WakeLock mNetTransitionWakeLock;
285 private String mNetTransitionWakeLockCausedBy = "";
286 private int mNetTransitionWakeLockSerialNumber;
287 private int mNetTransitionWakeLockTimeout;
288
Robert Greenwalt94daa182010-09-01 11:34:05 -0700289 private InetAddress mDefaultDns;
290
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700291 // this collection is used to refcount the added routes - if there are none left
292 // it's time to remove the route from the route table
293 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
294
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700295 // used in DBG mode to track inet condition reports
296 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
297 private ArrayList mInetLog;
298
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700299 // track the current default http proxy - tell the world if we get a new one (real change)
300 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700301 private Object mDefaultProxyLock = new Object();
302 private boolean mDefaultProxyDisabled = false;
303
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700304 // track the global proxy.
305 private ProxyProperties mGlobalProxy = null;
306 private final Object mGlobalProxyLock = new Object();
307
308 private SettingsObserver mSettingsObserver;
309
Robert Greenwalt34848c02011-03-25 13:09:25 -0700310 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700311 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700312
Robert Greenwalt12c44552009-12-07 11:33:18 -0800313 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700314 public int mSimultaneity;
315 public int mType;
316 public RadioAttributes(String init) {
317 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700318 mType = Integer.parseInt(fragments[0]);
319 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700320 }
321 }
322 RadioAttributes[] mRadioAttributes;
323
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700324 // the set of network types that can only be enabled by system/sig apps
325 List mProtectedNetworks;
326
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700327 public ConnectivityService(Context context, INetworkManagementService netd,
328 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800329 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800330
Wink Saville775aad62010-09-02 19:23:52 -0700331 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
332 handlerThread.start();
333 mHandler = new MyHandler(handlerThread.getLooper());
334
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800335 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800336 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
337 String id = Settings.Secure.getString(context.getContentResolver(),
338 Settings.Secure.ANDROID_ID);
339 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700340 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800341 SystemProperties.set("net.hostname", name);
342 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800343 }
344
Robert Greenwalt94daa182010-09-01 11:34:05 -0700345 // read our default dns server ip
346 String dns = Settings.Secure.getString(context.getContentResolver(),
347 Settings.Secure.DEFAULT_DNS_SERVER);
348 if (dns == null || dns.length() == 0) {
349 dns = context.getResources().getString(
350 com.android.internal.R.string.config_default_dns_server);
351 }
352 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800353 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
354 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800355 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700356 }
357
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700358 mContext = checkNotNull(context, "missing Context");
359 mNetd = checkNotNull(netd, "missing INetworkManagementService");
360 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700361
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700362 try {
363 mPolicyManager.registerListener(mPolicyListener);
364 } catch (RemoteException e) {
365 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700366 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700367 }
368
369 final PowerManager powerManager = (PowerManager) context.getSystemService(
370 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700371 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
372 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
373 com.android.internal.R.integer.config_networkTransitionTimeout);
374
Robert Greenwalt2034b912009-08-12 16:08:25 -0700375 mNetTrackers = new NetworkStateTracker[
376 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700377 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700378
The Android Open Source Project28527d22009-03-03 19:31:44 -0800379 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700380
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700382 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700383
Robert Greenwalt2034b912009-08-12 16:08:25 -0700384 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700385 String[] raStrings = context.getResources().getStringArray(
386 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700387 for (String raString : raStrings) {
388 RadioAttributes r = new RadioAttributes(raString);
389 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800390 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 continue;
392 }
393 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800394 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700395 r.mType);
396 continue;
397 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700398 mRadioAttributes[r.mType] = r;
399 }
400
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700401 String[] naStrings = context.getResources().getStringArray(
402 com.android.internal.R.array.networkAttributes);
403 for (String naString : naStrings) {
404 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700405 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700406 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800407 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700408 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700409 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700410 }
Wink Savillef2a62832011-04-07 14:23:45 -0700411 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800412 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700413 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700414 continue;
415 }
Wink Savillef2a62832011-04-07 14:23:45 -0700416 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800417 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700418 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700419 continue;
420 }
Wink Savillef2a62832011-04-07 14:23:45 -0700421 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700422 mNetworksDefined++;
423 } catch(Exception e) {
424 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700425 }
426 }
427
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700428 mProtectedNetworks = new ArrayList<Integer>();
429 int[] protectedNetworks = context.getResources().getIntArray(
430 com.android.internal.R.array.config_protectedNetworks);
431 for (int p : protectedNetworks) {
432 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
433 mProtectedNetworks.add(p);
434 } else {
435 if (DBG) loge("Ignoring protectedNetwork " + p);
436 }
437 }
438
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700439 // high priority first
440 mPriorityList = new int[mNetworksDefined];
441 {
442 int insertionPoint = mNetworksDefined-1;
443 int currentLowest = 0;
444 int nextLowest = 0;
445 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700446 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700448 if (na.priority < currentLowest) continue;
449 if (na.priority > currentLowest) {
450 if (na.priority < nextLowest || nextLowest == 0) {
451 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 }
453 continue;
454 }
Wink Savillef2a62832011-04-07 14:23:45 -0700455 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 }
457 currentLowest = nextLowest;
458 nextLowest = 0;
459 }
460 }
461
462 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
463 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700464 mNetRequestersPids[i] = new ArrayList();
465 }
466
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500467 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700468
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700469 mNumDnsEntries = 0;
470
471 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
472 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800473 /*
474 * Create the network state trackers for Wi-Fi and mobile
475 * data. Maybe this could be done with a factory class,
476 * but it's not clear that it's worth it, given that
477 * the number of different network types is not going
478 * to change very often.
479 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700480 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700481 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700482 case ConnectivityManager.TYPE_WIFI:
repo syncf5de5572011-07-29 23:55:49 -0700483 mNetTrackers[netType] = new WifiStateTracker(netType,
484 mNetConfigs[netType].name);
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700487 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700488 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700489 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700490 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700491 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800492 case ConnectivityManager.TYPE_DUMMY:
493 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700494 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800495 mNetTrackers[netType].startMonitoring(context, mHandler);
496 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800497 case ConnectivityManager.TYPE_BLUETOOTH:
498 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
499 mNetTrackers[netType].startMonitoring(context, mHandler);
500 break;
tk.mun093f55c2011-10-13 22:51:57 +0900501 case ConnectivityManager.TYPE_WIMAX:
502 mNetTrackers[netType] = makeWimaxStateTracker();
Robert Greenwalte72c4ac2011-11-08 10:12:25 -0800503 if (mNetTrackers[netType]!= null) {
tk.mun093f55c2011-10-13 22:51:57 +0900504 mNetTrackers[netType].startMonitoring(context, mHandler);
505 }
506 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800507 case ConnectivityManager.TYPE_ETHERNET:
508 mNetTrackers[netType] = EthernetDataTracker.getInstance();
509 mNetTrackers[netType].startMonitoring(context, mHandler);
510 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800512 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700513 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700514 continue;
515 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700516 mCurrentLinkProperties[netType] = null;
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800517 if (mNetTrackers[netType] != null && mNetConfigs[netType].isDefault()) {
518 mNetTrackers[netType].reconnect();
519 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700520 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800521
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700522 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
523 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
524
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700525 mTethering = new Tethering(mContext, nmService, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700526 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700527 mTethering.getTetherableWifiRegexs().length != 0 ||
528 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700529 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800530
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700531 mVpn = new Vpn(mContext, new VpnCallback());
532
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700533 try {
534 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700535 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700536 } catch (RemoteException e) {
537 loge("Error registering observer :" + e);
538 }
539
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700540 if (DBG) {
541 mInetLog = new ArrayList();
542 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700543
544 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
545 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800546
547 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800548 }
tk.mun093f55c2011-10-13 22:51:57 +0900549private NetworkStateTracker makeWimaxStateTracker() {
550 //Initialize Wimax
551 DexClassLoader wimaxClassLoader;
552 Class wimaxStateTrackerClass = null;
553 Class wimaxServiceClass = null;
554 Class wimaxManagerClass;
555 String wimaxJarLocation;
556 String wimaxLibLocation;
557 String wimaxManagerClassName;
558 String wimaxServiceClassName;
559 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800560
tk.mun093f55c2011-10-13 22:51:57 +0900561 NetworkStateTracker wimaxStateTracker = null;
562
563 boolean isWimaxEnabled = mContext.getResources().getBoolean(
564 com.android.internal.R.bool.config_wimaxEnabled);
565
566 if (isWimaxEnabled) {
567 try {
568 wimaxJarLocation = mContext.getResources().getString(
569 com.android.internal.R.string.config_wimaxServiceJarLocation);
570 wimaxLibLocation = mContext.getResources().getString(
571 com.android.internal.R.string.config_wimaxNativeLibLocation);
572 wimaxManagerClassName = mContext.getResources().getString(
573 com.android.internal.R.string.config_wimaxManagerClassname);
574 wimaxServiceClassName = mContext.getResources().getString(
575 com.android.internal.R.string.config_wimaxServiceClassname);
576 wimaxStateTrackerClassName = mContext.getResources().getString(
577 com.android.internal.R.string.config_wimaxStateTrackerClassname);
578
579 log("wimaxJarLocation: " + wimaxJarLocation);
580 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
581 new ContextWrapper(mContext).getCacheDir().getAbsolutePath(),
582 wimaxLibLocation, ClassLoader.getSystemClassLoader());
583
584 try {
585 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
586 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
587 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
588 } catch (ClassNotFoundException ex) {
589 loge("Exception finding Wimax classes: " + ex.toString());
590 return null;
591 }
592 } catch(Resources.NotFoundException ex) {
593 loge("Wimax Resources does not exist!!! ");
594 return null;
595 }
596
597 try {
598 log("Starting Wimax Service... ");
599
600 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
601 (new Class[] {Context.class, Handler.class});
602 wimaxStateTracker = (NetworkStateTracker)wmxStTrkrConst.newInstance(mContext,
603 mHandler);
604
605 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
606 (new Class[] {Context.class, wimaxStateTrackerClass});
607 wmxSrvConst.setAccessible(true);
608 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(mContext, wimaxStateTracker);
609 wmxSrvConst.setAccessible(false);
610
611 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
612
613 } catch(Exception ex) {
614 loge("Exception creating Wimax classes: " + ex.toString());
615 return null;
616 }
617 } else {
618 loge("Wimax is not enabled or not added to the network attributes!!! ");
619 return null;
620 }
621
622 return wimaxStateTracker;
623 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800624 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700625 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800626 * @param preference the new preference
627 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700628 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800629 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700630
631 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800632 }
633
634 public int getNetworkPreference() {
635 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700636 int preference;
637 synchronized(this) {
638 preference = mNetworkPreference;
639 }
640 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800641 }
642
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700643 private void handleSetNetworkPreference(int preference) {
644 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700645 mNetConfigs[preference] != null &&
646 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700647 if (mNetworkPreference != preference) {
648 final ContentResolver cr = mContext.getContentResolver();
649 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
650 synchronized(this) {
651 mNetworkPreference = preference;
652 }
653 enforcePreference();
654 }
655 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800656 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700657
Wink Saville4f0de1e2011-08-04 15:01:58 -0700658 private int getConnectivityChangeDelay() {
659 final ContentResolver cr = mContext.getContentResolver();
660
661 /** Check system properties for the default value then use secure settings value, if any. */
662 int defaultDelay = SystemProperties.getInt(
663 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
664 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
665 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
666 defaultDelay);
667 }
668
The Android Open Source Project28527d22009-03-03 19:31:44 -0800669 private int getPersistedNetworkPreference() {
670 final ContentResolver cr = mContext.getContentResolver();
671
672 final int networkPrefSetting = Settings.Secure
673 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
674 if (networkPrefSetting != -1) {
675 return networkPrefSetting;
676 }
677
678 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
679 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700680
The Android Open Source Project28527d22009-03-03 19:31:44 -0800681 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700682 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800683 * In this method, we only tear down a non-preferred network. Establishing
684 * a connection to the preferred network is taken care of when we handle
685 * the disconnect event from the non-preferred network
686 * (see {@link #handleDisconnect(NetworkInfo)}).
687 */
688 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700689 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800690 return;
691
Robert Greenwalt2034b912009-08-12 16:08:25 -0700692 if (!mNetTrackers[mNetworkPreference].isAvailable())
693 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800694
Robert Greenwalt2034b912009-08-12 16:08:25 -0700695 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700696 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700697 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700698 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800699 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700700 " in enforcePreference");
701 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700702 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800703 }
704 }
705 }
706
707 private boolean teardown(NetworkStateTracker netTracker) {
708 if (netTracker.teardown()) {
709 netTracker.setTeardownRequested(true);
710 return true;
711 } else {
712 return false;
713 }
714 }
715
716 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700717 * Check if UID should be blocked from using the network represented by the
718 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700719 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700720 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
721 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700722
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700723 final boolean networkCostly;
724 final int uidRules;
725 synchronized (mRulesLock) {
726 networkCostly = mMeteredIfaces.contains(iface);
727 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700728 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700729
730 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
731 return true;
732 }
733
734 // no restrictive rules; network is visible
735 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700736 }
737
738 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700739 * Return a filtered {@link NetworkInfo}, potentially marked
740 * {@link DetailedState#BLOCKED} based on
741 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700742 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700743 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
744 NetworkInfo info = tracker.getNetworkInfo();
745 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700746 // network is blocked; clone and override state
747 info = new NetworkInfo(info);
748 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700749 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700750 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700751 }
752
753 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800754 * Return NetworkInfo for the active (i.e., connected) network interface.
755 * It is assumed that at most one network is active at a time. If more
756 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700757 * @return the info for the active network, or {@code null} if none is
758 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800759 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700760 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800761 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700762 enforceAccessPermission();
763 final int uid = Binder.getCallingUid();
764 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800765 }
766
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700767 @Override
768 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
769 enforceConnectivityInternalPermission();
770 return getNetworkInfo(mActiveDefaultNetwork, uid);
771 }
772
773 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800774 public NetworkInfo getNetworkInfo(int networkType) {
775 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700776 final int uid = Binder.getCallingUid();
777 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800778 }
779
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700780 private NetworkInfo getNetworkInfo(int networkType, int uid) {
781 NetworkInfo info = null;
782 if (isNetworkTypeValid(networkType)) {
783 final NetworkStateTracker tracker = mNetTrackers[networkType];
784 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700785 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700786 }
787 }
788 return info;
789 }
790
791 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800792 public NetworkInfo[] getAllNetworkInfo() {
793 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700794 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700795 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700796 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700797 for (NetworkStateTracker tracker : mNetTrackers) {
798 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700799 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700800 }
801 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800802 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700803 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800804 }
805
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700806 @Override
807 public boolean isNetworkSupported(int networkType) {
808 enforceAccessPermission();
809 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
810 }
811
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700812 /**
813 * Return LinkProperties for the active (i.e., connected) default
814 * network interface. It is assumed that at most one default network
815 * is active at a time. If more than one is active, it is indeterminate
816 * which will be returned.
817 * @return the ip properties for the active network, or {@code null} if
818 * none is active
819 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700820 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700821 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700822 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700823 }
824
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700825 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700826 public LinkProperties getLinkProperties(int networkType) {
827 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700828 if (isNetworkTypeValid(networkType)) {
829 final NetworkStateTracker tracker = mNetTrackers[networkType];
830 if (tracker != null) {
831 return tracker.getLinkProperties();
832 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700833 }
834 return null;
835 }
836
Jeff Sharkey21062e72011-05-28 20:56:34 -0700837 @Override
838 public NetworkState[] getAllNetworkState() {
839 enforceAccessPermission();
840 final int uid = Binder.getCallingUid();
841 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700842 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700843 for (NetworkStateTracker tracker : mNetTrackers) {
844 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700845 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700846 result.add(new NetworkState(
847 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
848 }
849 }
850 }
851 return result.toArray(new NetworkState[result.size()]);
852 }
853
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700854 private NetworkState getNetworkStateUnchecked(int networkType) {
855 if (isNetworkTypeValid(networkType)) {
856 final NetworkStateTracker tracker = mNetTrackers[networkType];
857 if (tracker != null) {
858 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
859 tracker.getLinkCapabilities());
860 }
861 }
862 return null;
863 }
864
865 @Override
866 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
867 enforceAccessPermission();
868 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
869 if (state != null) {
870 try {
871 return mPolicyManager.getNetworkQuotaInfo(state);
872 } catch (RemoteException e) {
873 }
874 }
875 return null;
876 }
877
The Android Open Source Project28527d22009-03-03 19:31:44 -0800878 public boolean setRadios(boolean turnOn) {
879 boolean result = true;
880 enforceChangePermission();
881 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700882 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800883 }
884 return result;
885 }
886
887 public boolean setRadio(int netType, boolean turnOn) {
888 enforceChangePermission();
889 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
890 return false;
891 }
892 NetworkStateTracker tracker = mNetTrackers[netType];
893 return tracker != null && tracker.setRadio(turnOn);
894 }
895
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700896 /**
897 * Used to notice when the calling process dies so we can self-expire
898 *
899 * Also used to know if the process has cleaned up after itself when
900 * our auto-expire timer goes off. The timer has a link to an object.
901 *
902 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700903 private class FeatureUser implements IBinder.DeathRecipient {
904 int mNetworkType;
905 String mFeature;
906 IBinder mBinder;
907 int mPid;
908 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800909 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700910
911 FeatureUser(int type, String feature, IBinder binder) {
912 super();
913 mNetworkType = type;
914 mFeature = feature;
915 mBinder = binder;
916 mPid = getCallingPid();
917 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800918 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700919
Robert Greenwalt2034b912009-08-12 16:08:25 -0700920 try {
921 mBinder.linkToDeath(this, 0);
922 } catch (RemoteException e) {
923 binderDied();
924 }
925 }
926
927 void unlinkDeathRecipient() {
928 mBinder.unlinkToDeath(this, 0);
929 }
930
931 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800932 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800933 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
934 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700935 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700936 }
937
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700938 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700939 if (VDBG) {
940 log("ConnectivityService FeatureUser expire(" +
941 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
942 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
943 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700944 stopUsingNetworkFeature(this, false);
945 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800946
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500947 public boolean isSameUser(FeatureUser u) {
948 if (u == null) return false;
949
950 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
951 }
952
953 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
954 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
955 TextUtils.equals(mFeature, feature)) {
956 return true;
957 }
958 return false;
959 }
960
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800961 public String toString() {
962 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
963 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
964 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700965 }
966
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700967 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700968 public int startUsingNetworkFeature(int networkType, String feature,
969 IBinder binder) {
Wink Savillea7d56572011-09-21 11:05:43 -0700970 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800971 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700972 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800973 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700974 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700975 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700976 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800977 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700978
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700979 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700980
repo syncf5de5572011-07-29 23:55:49 -0700981 // TODO - move this into individual networktrackers
982 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700983
984 if (mProtectedNetworks.contains(usedNetworkType)) {
985 enforceConnectivityInternalPermission();
986 }
987
Robert Greenwalt2034b912009-08-12 16:08:25 -0700988 NetworkStateTracker network = mNetTrackers[usedNetworkType];
989 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800990 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700991 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700992 NetworkInfo ni = network.getNetworkInfo();
993
994 if (ni.isAvailable() == false) {
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800995 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
Wink Saville5030c052012-01-25 13:47:54 -0800996 if (DBG) log("special network not available ni=" + ni.getTypeName());
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800997 return Phone.APN_TYPE_NOT_AVAILABLE;
998 } else {
999 // else make the attempt anyway - probably giving REQUEST_STARTED below
Wink Saville5030c052012-01-25 13:47:54 -08001000 if (DBG) {
1001 log("special network not available, but try anyway ni=" +
1002 ni.getTypeName());
1003 }
Robert Greenwalt2cc87442010-12-29 14:35:21 -08001004 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001005 }
1006
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001007 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1008
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001009 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001010 boolean addToList = true;
1011 if (restoreTimer < 0) {
1012 // In case there is no timer is specified for the feature,
1013 // make sure we don't add duplicate entry with the same request.
1014 for (FeatureUser u : mFeatureUsers) {
1015 if (u.isSameUser(f)) {
1016 // Duplicate user is found. Do not add.
1017 addToList = false;
1018 break;
1019 }
1020 }
1021 }
1022
1023 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001024 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1025 // this gets used for per-pid dns when connected
1026 mNetRequestersPids[usedNetworkType].add(currentPid);
1027 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001028 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001029
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001030 if (restoreTimer >= 0) {
1031 mHandler.sendMessageDelayed(
1032 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1033 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001034
Robert Greenwalta52c75a2009-08-19 20:19:33 -07001035 if ((ni.isConnectedOrConnecting() == true) &&
1036 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001037 if (ni.isConnected() == true) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001038 final long token = Binder.clearCallingIdentity();
1039 try {
1040 // add the pid-specific dns
1041 handleDnsConfigurationChange(usedNetworkType);
1042 if (VDBG) log("special network already active");
1043 } finally {
1044 Binder.restoreCallingIdentity(token);
1045 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001046 return Phone.APN_ALREADY_ACTIVE;
1047 }
Wink Savillea7d56572011-09-21 11:05:43 -07001048 if (VDBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001049 return Phone.APN_REQUEST_STARTED;
1050 }
1051
1052 // check if the radio in play can make another contact
1053 // assume if cannot for now
1054
Wink Savillea7d56572011-09-21 11:05:43 -07001055 if (DBG) {
1056 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1057 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001058 network.reconnect();
1059 return Phone.APN_REQUEST_STARTED;
1060 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -08001061 // need to remember this unsupported request so we respond appropriately on stop
1062 synchronized(this) {
1063 mFeatureUsers.add(f);
1064 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1065 // this gets used for per-pid dns when connected
1066 mNetRequestersPids[usedNetworkType].add(currentPid);
1067 }
1068 }
Robert Greenwaltd391e892010-05-18 10:52:51 -07001069 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001070 }
1071 }
1072 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001073 }
1074
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001075 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001076 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001077 enforceChangePermission();
1078
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001079 int pid = getCallingPid();
1080 int uid = getCallingUid();
1081
1082 FeatureUser u = null;
1083 boolean found = false;
1084
1085 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001086 for (FeatureUser x : mFeatureUsers) {
1087 if (x.isSameUser(pid, uid, networkType, feature)) {
1088 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001089 found = true;
1090 break;
1091 }
1092 }
1093 }
1094 if (found && u != null) {
1095 // stop regardless of how many other time this proc had called start
1096 return stopUsingNetworkFeature(u, true);
1097 } else {
1098 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001099 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001100 return 1;
1101 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001102 }
1103
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001104 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1105 int networkType = u.mNetworkType;
1106 String feature = u.mFeature;
1107 int pid = u.mPid;
1108 int uid = u.mUid;
1109
1110 NetworkStateTracker tracker = null;
1111 boolean callTeardown = false; // used to carry our decision outside of sync block
1112
Wink Savillea7d56572011-09-21 11:05:43 -07001113 if (VDBG) {
1114 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001115 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001116
The Android Open Source Project28527d22009-03-03 19:31:44 -08001117 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001118 if (DBG) {
1119 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1120 ", net is invalid");
1121 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001122 return -1;
1123 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001124
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001125 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1126 // sync block
1127 synchronized(this) {
1128 // check if this process still has an outstanding start request
1129 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001130 if (VDBG) {
1131 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1132 ", ignoring");
1133 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001134 return 1;
1135 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001136 u.unlinkDeathRecipient();
1137 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1138 // If we care about duplicate requests, check for that here.
1139 //
1140 // This is done to support the extension of a request - the app
1141 // can request we start the network feature again and renew the
1142 // auto-shutoff delay. Normal "stop" calls from the app though
1143 // do not pay attention to duplicate requests - in effect the
1144 // API does not refcount and a single stop will counter multiple starts.
1145 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001146 for (FeatureUser x : mFeatureUsers) {
1147 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001148 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001149 return 1;
1150 }
1151 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001152 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001153
repo syncf5de5572011-07-29 23:55:49 -07001154 // TODO - move to individual network trackers
1155 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1156
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001157 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001158 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001159 if (DBG) {
1160 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1161 " no known tracker for used net type " + usedNetworkType);
1162 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001163 return -1;
1164 }
1165 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001166 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001167 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001168 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001169 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001170 if (VDBG) {
1171 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1172 " others still using it");
1173 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001174 return 1;
1175 }
1176 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001177 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001178 if (DBG) {
1179 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1180 " not a known feature - dropping");
1181 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001182 }
1183 }
Wink Savillea7d56572011-09-21 11:05:43 -07001184
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001185 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001186 if (DBG) {
1187 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1188 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001189 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001190 return 1;
1191 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001192 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001193 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001194 }
1195
1196 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001197 * @deprecated use requestRouteToHostAddress instead
1198 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001199 * Ensure that a network route exists to deliver traffic to the specified
1200 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001201 * @param networkType the type of the network over which traffic to the
1202 * specified host is to be routed
1203 * @param hostAddress the IP address of the host to which the route is
1204 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001205 * @return {@code true} on success, {@code false} on failure
1206 */
1207 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001208 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1209
1210 if (inetAddress == null) {
1211 return false;
1212 }
1213
1214 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1215 }
1216
1217 /**
1218 * Ensure that a network route exists to deliver traffic to the specified
1219 * host via the specified network interface.
1220 * @param networkType the type of the network over which traffic to the
1221 * specified host is to be routed
1222 * @param hostAddress the IP address of the host to which the route is
1223 * desired
1224 * @return {@code true} on success, {@code false} on failure
1225 */
1226 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001227 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001228 if (mProtectedNetworks.contains(networkType)) {
1229 enforceConnectivityInternalPermission();
1230 }
1231
The Android Open Source Project28527d22009-03-03 19:31:44 -08001232 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001233 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001234 return false;
1235 }
1236 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001237
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001238 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1239 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001240 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001241 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001242 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001243 }
1244 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001245 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001246 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001247 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001248 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001249 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001250 return addRouteToAddress(lp, addr);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001251 } catch (UnknownHostException e) {
1252 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1253 } finally {
1254 Binder.restoreCallingIdentity(token);
1255 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001256 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001257 }
1258
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001259 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1260 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001261 }
1262
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001263 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1264 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001265 }
1266
Robert Greenwalt98107422011-07-22 11:55:33 -07001267 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001268 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001269 }
1270
1271 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001272 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001273 }
1274
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001275 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1276 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001277 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1278 if (bestRoute == null) {
1279 bestRoute = RouteInfo.makeHostRoute(addr);
1280 } else {
1281 if (bestRoute.getGateway().equals(addr)) {
1282 // if there is no better route, add the implied hostroute for our gateway
1283 bestRoute = RouteInfo.makeHostRoute(addr);
1284 } else {
1285 // if we will connect to this through another route, add a direct route
1286 // to it's gateway
1287 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1288 }
1289 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001290 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001291 }
1292
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001293 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001294 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001295 if ((ifaceName == null) || (lp == null) || (r == null)) {
1296 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1297 return false;
1298 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001299
1300 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001301 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001302 return false;
1303 }
1304
1305 if (r.isHostRoute() == false) {
1306 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1307 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001308 if (bestRoute.getGateway().equals(r.getGateway())) {
1309 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001310 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001311 } else {
1312 // if we will connect to our gateway through another route, add a direct
1313 // route to it's gateway
1314 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001315 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001316 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001317 }
1318 }
1319 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001320 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001321 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001322 if (toDefaultTable) {
1323 mAddedRoutes.add(r); // only track default table - only one apps can effect
1324 mNetd.addRoute(ifaceName, r);
1325 } else {
1326 mNetd.addSecondaryRoute(ifaceName, r);
1327 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001328 } catch (Exception e) {
1329 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001330 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001331 return false;
1332 }
1333 } else {
1334 // if we remove this one and there are no more like it, then refcount==0 and
1335 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001336 if (toDefaultTable) {
1337 mAddedRoutes.remove(r);
1338 if (mAddedRoutes.contains(r) == false) {
1339 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1340 try {
1341 mNetd.removeRoute(ifaceName, r);
1342 } catch (Exception e) {
1343 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001344 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001345 return false;
1346 }
1347 } else {
1348 if (VDBG) log("not removing " + r + " as it's still in use");
1349 }
1350 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001351 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001352 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001353 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001354 } catch (Exception e) {
1355 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001356 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001357 return false;
1358 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001359 }
1360 }
1361 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001362 }
1363
1364 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001365 * @see ConnectivityManager#getMobileDataEnabled()
1366 */
1367 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001368 // TODO: This detail should probably be in DataConnectionTracker's
1369 // which is where we store the value and maybe make this
1370 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001371 enforceAccessPermission();
1372 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1373 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001374 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001375 return retVal;
1376 }
1377
Robert Greenwalt34848c02011-03-25 13:09:25 -07001378 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001379 enforceConnectivityInternalPermission();
1380
Robert Greenwalt34848c02011-03-25 13:09:25 -07001381 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1382 (met ? ENABLED : DISABLED), networkType));
1383 }
1384
1385 private void handleSetDependencyMet(int networkType, boolean met) {
1386 if (mNetTrackers[networkType] != null) {
1387 if (DBG) {
1388 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1389 }
1390 mNetTrackers[networkType].setDependencyMet(met);
1391 }
1392 }
1393
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001394 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1395 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001396 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001397 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001398 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001399 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001400 }
1401
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001402 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001403 // skip update when we've already applied rules
1404 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1405 if (oldRules == uidRules) return;
1406
1407 mUidRules.put(uid, uidRules);
1408 }
1409
1410 // TODO: dispatch into NMS to push rules towards kernel module
1411 // TODO: notify UID when it has requested targeted updates
1412 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001413
1414 @Override
1415 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001416 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001417 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001418 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001419 }
1420
1421 synchronized (mRulesLock) {
1422 mMeteredIfaces.clear();
1423 for (String iface : meteredIfaces) {
1424 mMeteredIfaces.add(iface);
1425 }
1426 }
1427 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001428
1429 @Override
1430 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1431 // caller is NPMS, since we only register with them
1432 if (LOGD_RULES) {
1433 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1434 }
1435
1436 // kick off connectivity change broadcast for active network, since
1437 // global background policy change is radical.
1438 final int networkType = mActiveDefaultNetwork;
1439 if (isNetworkTypeValid(networkType)) {
1440 final NetworkStateTracker tracker = mNetTrackers[networkType];
1441 if (tracker != null) {
1442 final NetworkInfo info = tracker.getNetworkInfo();
1443 if (info != null && info.isConnected()) {
1444 sendConnectedBroadcast(info);
1445 }
1446 }
1447 }
1448 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001449 };
1450
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001451 /**
1452 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1453 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001454 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001455 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001456 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001457
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001458 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001459 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001460 }
1461
1462 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001463 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001464 if (VDBG) {
1465 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001466 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001467 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1468 }
tk.mun5eee1042012-01-06 10:43:52 +09001469 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1470 if (VDBG) {
1471 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1472 }
1473 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1474 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001475 }
1476
1477 @Override
1478 public void setPolicyDataEnable(int networkType, boolean enabled) {
1479 // only someone like NPMS should only be calling us
1480 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1481
1482 mHandler.sendMessage(mHandler.obtainMessage(
1483 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1484 }
1485
1486 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1487 if (isNetworkTypeValid(networkType)) {
1488 final NetworkStateTracker tracker = mNetTrackers[networkType];
1489 if (tracker != null) {
1490 tracker.setPolicyDataEnable(enabled);
1491 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001492 }
1493 }
1494
The Android Open Source Project28527d22009-03-03 19:31:44 -08001495 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001496 mContext.enforceCallingOrSelfPermission(
1497 android.Manifest.permission.ACCESS_NETWORK_STATE,
1498 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001499 }
1500
1501 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001502 mContext.enforceCallingOrSelfPermission(
1503 android.Manifest.permission.CHANGE_NETWORK_STATE,
1504 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001505 }
1506
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001507 // TODO Make this a special check when it goes public
1508 private void enforceTetherChangePermission() {
1509 mContext.enforceCallingOrSelfPermission(
1510 android.Manifest.permission.CHANGE_NETWORK_STATE,
1511 "ConnectivityService");
1512 }
1513
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001514 private void enforceTetherAccessPermission() {
1515 mContext.enforceCallingOrSelfPermission(
1516 android.Manifest.permission.ACCESS_NETWORK_STATE,
1517 "ConnectivityService");
1518 }
1519
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001520 private void enforceConnectivityInternalPermission() {
1521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1523 "ConnectivityService");
1524 }
1525
The Android Open Source Project28527d22009-03-03 19:31:44 -08001526 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001527 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1528 * network, we ignore it. If it is for the active network, we send out a
1529 * broadcast. But first, we check whether it might be possible to connect
1530 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001531 * @param info the {@code NetworkInfo} for the network
1532 */
1533 private void handleDisconnect(NetworkInfo info) {
1534
Robert Greenwalt2034b912009-08-12 16:08:25 -07001535 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001536
Robert Greenwalt2034b912009-08-12 16:08:25 -07001537 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 /*
1539 * If the disconnected network is not the active one, then don't report
1540 * this as a loss of connectivity. What probably happened is that we're
1541 * getting the disconnect for a network that we explicitly disabled
1542 * in accordance with network preference policies.
1543 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001544 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001545 List pids = mNetRequestersPids[prevNetType];
1546 for (int i = 0; i<pids.size(); i++) {
1547 Integer pid = (Integer)pids.get(i);
1548 // will remove them because the net's no longer connected
1549 // need to do this now as only now do we know the pids and
1550 // can properly null things that are no longer referenced.
1551 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001552 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001553 }
1554
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1556 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1557 if (info.isFailover()) {
1558 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1559 info.setFailover(false);
1560 }
1561 if (info.getReason() != null) {
1562 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1563 }
1564 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001565 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1566 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001568
Robert Greenwalt34848c02011-03-25 13:09:25 -07001569 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001570 tryFailover(prevNetType);
1571 if (mActiveDefaultNetwork != -1) {
1572 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001573 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1574 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001575 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001576 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1577 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001578 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001579 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001580
1581 // Reset interface if no other connections are using the same interface
1582 boolean doReset = true;
1583 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1584 if (linkProperties != null) {
1585 String oldIface = linkProperties.getInterfaceName();
1586 if (TextUtils.isEmpty(oldIface) == false) {
1587 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1588 if (networkStateTracker == null) continue;
1589 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1590 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1591 LinkProperties l = networkStateTracker.getLinkProperties();
1592 if (l == null) continue;
1593 if (oldIface.equals(l.getInterfaceName())) {
1594 doReset = false;
1595 break;
1596 }
1597 }
1598 }
1599 }
1600 }
1601
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001602 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001603 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001604
Jeff Sharkey971cd162011-08-29 16:02:57 -07001605 final Intent immediateIntent = new Intent(intent);
1606 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1607 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001608 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001609 /*
1610 * If the failover network is already connected, then immediately send
1611 * out a followup broadcast indicating successful failover
1612 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001613 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001614 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1615 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001616 }
1617 }
1618
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001619 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001620 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001621 * If this is a default network, check if other defaults are available.
1622 * Try to reconnect on all available and let them hash it out when
1623 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001624 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001625 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001626 if (mActiveDefaultNetwork == prevNetType) {
1627 mActiveDefaultNetwork = -1;
1628 }
1629
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001630 // don't signal a reconnect for anything lower or equal priority than our
1631 // current connected default
1632 // TODO - don't filter by priority now - nice optimization but risky
1633// int currentPriority = -1;
1634// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001635// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001636// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001637 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001638 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001639 if (mNetConfigs[checkType] == null) continue;
1640 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001641 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001642
1643// Enabling the isAvailable() optimization caused mobile to not get
1644// selected if it was in the middle of error handling. Specifically
1645// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1646// would not be available and we wouldn't get connected to anything.
1647// So removing the isAvailable() optimization below for now. TODO: This
1648// optimization should work and we need to investigate why it doesn't work.
1649// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1650// complete before it is really complete.
1651// if (!mNetTrackers[checkType].isAvailable()) continue;
1652
Robert Greenwalt34848c02011-03-25 13:09:25 -07001653// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001654
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001655 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1656 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1657 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1658 checkInfo.setFailover(true);
1659 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001660 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001661 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001662 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001663 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001664 }
1665
1666 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001667 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1668 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001669 }
1670
Wink Saville4f0de1e2011-08-04 15:01:58 -07001671 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001672 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1673 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001674 }
1675
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001676 private void sendInetConditionBroadcast(NetworkInfo info) {
1677 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1678 }
1679
Wink Saville4f0de1e2011-08-04 15:01:58 -07001680 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001681 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001682 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1683 if (info.isFailover()) {
1684 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1685 info.setFailover(false);
1686 }
1687 if (info.getReason() != null) {
1688 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1689 }
1690 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001691 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1692 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001693 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001694 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001695 return intent;
1696 }
1697
1698 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1699 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1700 }
1701
1702 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1703 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001704 }
1705
1706 /**
1707 * Called when an attempt to fail over to another network has failed.
1708 * @param info the {@link NetworkInfo} for the failed network
1709 */
1710 private void handleConnectionFailure(NetworkInfo info) {
1711 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001712
Robert Greenwalt2034b912009-08-12 16:08:25 -07001713 String reason = info.getReason();
1714 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001715
Robert Greenwalte981bc52010-10-08 16:35:52 -07001716 String reasonText;
1717 if (reason == null) {
1718 reasonText = ".";
1719 } else {
1720 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001721 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001722 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001723
1724 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1725 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1726 if (getActiveNetworkInfo() == null) {
1727 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1728 }
1729 if (reason != null) {
1730 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1731 }
1732 if (extraInfo != null) {
1733 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1734 }
1735 if (info.isFailover()) {
1736 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1737 info.setFailover(false);
1738 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001739
Robert Greenwalt34848c02011-03-25 13:09:25 -07001740 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001741 tryFailover(info.getType());
1742 if (mActiveDefaultNetwork != -1) {
1743 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001744 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1745 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001746 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001747 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1748 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001749 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001750
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001751 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001752
1753 final Intent immediateIntent = new Intent(intent);
1754 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1755 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001756 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001757 /*
1758 * If the failover network is already connected, then immediately send
1759 * out a followup broadcast indicating successful failover
1760 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001761 if (mActiveDefaultNetwork != -1) {
1762 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001763 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001764 }
1765
1766 private void sendStickyBroadcast(Intent intent) {
1767 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001768 if (!mSystemReady) {
1769 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001770 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001771 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001772 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001773 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001774 }
1775
Dianne Hackborna417ff82009-12-08 19:45:14 -08001776 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001777 }
1778 }
1779
Wink Saville4f0de1e2011-08-04 15:01:58 -07001780 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1781 if (delayMs <= 0) {
1782 sendStickyBroadcast(intent);
1783 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001784 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001785 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1786 + intent.getAction());
1787 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001788 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1789 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1790 }
1791 }
1792
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001793 void systemReady() {
1794 synchronized(this) {
1795 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001796 if (mInitialBroadcast != null) {
1797 mContext.sendStickyBroadcast(mInitialBroadcast);
1798 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001799 }
1800 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001801 // load the global proxy at startup
1802 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001803 }
1804
1805 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001806 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001807
1808 // snapshot isFailover, because sendConnectedBroadcast() resets it
1809 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001810 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001811
Robert Greenwalt2034b912009-08-12 16:08:25 -07001812 // if this is a default net and other default is running
1813 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001814 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001815 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1816 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001817 mNetConfigs[mActiveDefaultNetwork].priority >
1818 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001819 mNetworkPreference == mActiveDefaultNetwork) {
1820 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001821 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001822 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001823 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001824 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001825 teardown(thisNet);
1826 return;
1827 } else {
1828 // tear down the other
1829 NetworkStateTracker otherNet =
1830 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001831 if (DBG) {
1832 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001833 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001834 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001835 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001836 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001837 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001838 return;
1839 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001840 }
1841 }
1842 synchronized (ConnectivityService.this) {
1843 // have a new default network, release the transition wakelock in a second
1844 // if it's held. The second pause is to allow apps to reconnect over the
1845 // new network
1846 if (mNetTransitionWakeLock.isHeld()) {
1847 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001848 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001849 mNetTransitionWakeLockSerialNumber, 0),
1850 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001851 }
1852 }
1853 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001854 // this will cause us to come up initially as unconnected and switching
1855 // to connected after our normal pause unless somebody reports us as reall
1856 // disconnected
1857 mDefaultInetConditionPublished = 0;
1858 mDefaultConnectionSequence++;
1859 mInetConditionChangeInFlight = false;
1860 // Don't do this - if we never sign in stay, grey
1861 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001862 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001863 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001864 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001865 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001866 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001867
1868 // notify battery stats service about this network
1869 final String iface = thisNet.getLinkProperties().getInterfaceName();
1870 if (iface != null) {
1871 try {
1872 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1873 } catch (RemoteException e) {
1874 // ignored; service lives in system_server
1875 }
1876 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001877 }
1878
The Android Open Source Project28527d22009-03-03 19:31:44 -08001879 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001880 * After a change in the connectivity state of a network. We're mainly
1881 * concerned with making sure that the list of DNS servers is set up
1882 * according to which networks are connected, and ensuring that the
1883 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001884 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001885 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001886 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1887
The Android Open Source Project28527d22009-03-03 19:31:44 -08001888 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001889 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001890 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001891 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001892 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001893
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001894 LinkProperties curLp = mCurrentLinkProperties[netType];
1895 LinkProperties newLp = null;
1896
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001897 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001898 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001899 if (VDBG) {
1900 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1901 " doReset=" + doReset + " resetMask=" + resetMask +
1902 "\n curLp=" + curLp +
1903 "\n newLp=" + newLp);
1904 }
1905
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001906 if (curLp != null) {
1907 if (curLp.isIdenticalInterfaceName(newLp)) {
1908 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1909 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1910 for (LinkAddress linkAddr : car.removed) {
1911 if (linkAddr.getAddress() instanceof Inet4Address) {
1912 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1913 }
1914 if (linkAddr.getAddress() instanceof Inet6Address) {
1915 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1916 }
Wink Saville051a6642011-07-13 13:44:13 -07001917 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001918 if (DBG) {
1919 log("handleConnectivityChange: addresses changed" +
1920 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1921 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001922 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001923 } else {
1924 if (DBG) {
1925 log("handleConnectivityChange: address are the same reset per doReset" +
1926 " linkProperty[" + netType + "]:" +
1927 " resetMask=" + resetMask);
1928 }
Wink Saville051a6642011-07-13 13:44:13 -07001929 }
1930 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001931 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001932 if (DBG) {
1933 log("handleConnectivityChange: interface not not equivalent reset both" +
1934 " linkProperty[" + netType + "]:" +
1935 " resetMask=" + resetMask);
1936 }
Wink Saville051a6642011-07-13 13:44:13 -07001937 }
Wink Saville051a6642011-07-13 13:44:13 -07001938 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001939 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07001940 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001941 }
1942 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001943 if (VDBG) {
1944 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1945 " doReset=" + doReset + " resetMask=" + resetMask +
1946 "\n curLp=" + curLp +
1947 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001948 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001949 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001950 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001951 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001952
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001953 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001954 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1955 if (linkProperties != null) {
1956 String iface = linkProperties.getInterfaceName();
1957 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001958 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001959 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1960 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001961
1962 // Tell VPN the interface is down. It is a temporary
1963 // but effective fix to make VPN aware of the change.
1964 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1965 mVpn.interfaceStatusChanged(iface, false);
1966 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001967 }
1968 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07001969 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001970 try {
1971 mNetd.flushInterfaceDnsCache(iface);
1972 } catch (Exception e) {
1973 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001974 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001975 }
1976 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001977 }
1978 }
1979 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001980
1981 // TODO: Temporary notifying upstread change to Tethering.
1982 // @see bug/4455071
1983 /** Notify TetheringService if interface name has been changed. */
1984 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1985 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1986 if (isTetheringSupported()) {
1987 mTethering.handleTetherIfaceChange();
1988 }
1989 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001990 }
1991
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001992 /**
1993 * Add and remove routes using the old properties (null if not previously connected),
1994 * new properties (null if becoming disconnected). May even be double null, which
1995 * is a noop.
1996 * Uses isLinkDefault to determine if default routes should be set or conversely if
1997 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001998 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001999 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002000 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2001 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002002 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002003 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2004 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002005 if (curLp != null) {
2006 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002007 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002008 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002009 } else if (newLp != null) {
2010 routeDiff.added = newLp.getRoutes();
2011 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002012 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002013
Robert Greenwalt8d777252011-08-15 12:31:55 -07002014 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2015
Robert Greenwalt98107422011-07-22 11:55:33 -07002016 for (RouteInfo r : routeDiff.removed) {
2017 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002018 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2019 }
2020 if (isLinkDefault == false) {
2021 // remove from a secondary route table
2022 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002023 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002024 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002025
Robert Greenwalt98107422011-07-22 11:55:33 -07002026 for (RouteInfo r : routeDiff.added) {
2027 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002028 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002029 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002030 // add to a secondary route table
2031 addRoute(newLp, r, TO_SECONDARY_TABLE);
2032
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002033 // many radios add a default route even when we don't want one.
2034 // remove the default route unless somebody else has asked for it
2035 String ifaceName = newLp.getInterfaceName();
2036 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002037 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002038 try {
2039 mNetd.removeRoute(ifaceName, r);
2040 } catch (Exception e) {
2041 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002042 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002043 }
2044 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002045 }
2046 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002047
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002048 if (!isLinkDefault) {
2049 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002050 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002051 // routes changed - remove all old dns entries and add new
2052 if (curLp != null) {
2053 for (InetAddress oldDns : curLp.getDnses()) {
2054 removeRouteToAddress(curLp, oldDns);
2055 }
2056 }
2057 if (newLp != null) {
2058 for (InetAddress newDns : newLp.getDnses()) {
2059 addRouteToAddress(newLp, newDns);
2060 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002061 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002062 } else {
2063 // no change in routes, check for change in dns themselves
2064 for (InetAddress oldDns : dnsDiff.removed) {
2065 removeRouteToAddress(curLp, oldDns);
2066 }
2067 for (InetAddress newDns : dnsDiff.added) {
2068 addRouteToAddress(newLp, newDns);
2069 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002070 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002071 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002072 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002073 }
2074
2075
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002076 /**
2077 * Reads the network specific TCP buffer sizes from SystemProperties
2078 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2079 * wide use
2080 */
2081 public void updateNetworkSettings(NetworkStateTracker nt) {
2082 String key = nt.getTcpBufferSizesPropName();
2083 String bufferSizes = SystemProperties.get(key);
2084
2085 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002086 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002087
2088 // Setting to default values so we won't be stuck to previous values
2089 key = "net.tcp.buffersize.default";
2090 bufferSizes = SystemProperties.get(key);
2091 }
2092
2093 // Set values in kernel
2094 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002095 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002096 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002097 + "] which comes from [" + key + "]");
2098 }
2099 setBufferSize(bufferSizes);
2100 }
2101 }
2102
2103 /**
2104 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2105 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2106 *
2107 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2108 * writeMin, writeInitial, writeMax"
2109 */
2110 private void setBufferSize(String bufferSizes) {
2111 try {
2112 String[] values = bufferSizes.split(",");
2113
2114 if (values.length == 6) {
2115 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002116 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2117 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2118 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2119 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2120 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2121 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002122 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002123 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002124 }
2125 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002126 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002127 }
2128 }
2129
Robert Greenwalt2034b912009-08-12 16:08:25 -07002130 /**
2131 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2132 * on the highest priority active net which this process requested.
2133 * If there aren't any, clear it out
2134 */
2135 private void reassessPidDns(int myPid, boolean doBump)
2136 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002137 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002138 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002139 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002140 continue;
2141 }
2142 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002143 if (nt.getNetworkInfo().isConnected() &&
2144 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002145 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002146 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002147 List pids = mNetRequestersPids[i];
2148 for (int j=0; j<pids.size(); j++) {
2149 Integer pid = (Integer)pids.get(j);
2150 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002151 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002152 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002153 if (doBump) {
2154 bumpDns();
2155 }
2156 return;
2157 }
2158 }
2159 }
2160 }
2161 // nothing found - delete
2162 for (int i = 1; ; i++) {
2163 String prop = "net.dns" + i + "." + myPid;
2164 if (SystemProperties.get(prop).length() == 0) {
2165 if (doBump) {
2166 bumpDns();
2167 }
2168 return;
2169 }
2170 SystemProperties.set(prop, "");
2171 }
2172 }
2173
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002174 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002175 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002176 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002177 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002178 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002179 String dnsString = dns.getHostAddress();
2180 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2181 changed = true;
2182 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2183 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002184 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002185 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002186 }
2187
2188 private void bumpDns() {
2189 /*
2190 * Bump the property that tells the name resolver library to reread
2191 * the DNS server list from the properties.
2192 */
2193 String propVal = SystemProperties.get("net.dnschange");
2194 int n = 0;
2195 if (propVal.length() != 0) {
2196 try {
2197 n = Integer.parseInt(propVal);
2198 } catch (NumberFormatException e) {}
2199 }
2200 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002201 /*
2202 * Tell the VMs to toss their DNS caches
2203 */
2204 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2205 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002206 /*
2207 * Connectivity events can happen before boot has completed ...
2208 */
2209 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002210 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002211 }
2212
Chia-chi Yehcc844502011-07-14 18:01:57 -07002213 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002214 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002215 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002216 boolean changed = false;
2217 int last = 0;
2218 if (dnses.size() == 0 && mDefaultDns != null) {
2219 ++last;
2220 String value = mDefaultDns.getHostAddress();
2221 if (!value.equals(SystemProperties.get("net.dns1"))) {
2222 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002223 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002224 }
2225 changed = true;
2226 SystemProperties.set("net.dns1", value);
2227 }
2228 } else {
2229 for (InetAddress dns : dnses) {
2230 ++last;
2231 String key = "net.dns" + last;
2232 String value = dns.getHostAddress();
2233 if (!changed && value.equals(SystemProperties.get(key))) {
2234 continue;
2235 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002236 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002237 log("adding dns " + value + " for " + network);
2238 }
2239 changed = true;
2240 SystemProperties.set(key, value);
2241 }
2242 }
2243 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2244 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002245 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002246 changed = true;
2247 SystemProperties.set(key, "");
2248 }
2249 mNumDnsEntries = last;
2250
Robert Greenwaltfce71862011-07-25 16:06:25 -07002251 if (changed) {
2252 try {
2253 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2254 mNetd.setDefaultInterfaceForDns(iface);
2255 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002256 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002257 }
2258 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002259 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2260 SystemProperties.set("net.dns.search", domains);
2261 changed = true;
2262 }
2263 return changed;
2264 }
2265
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002266 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002267 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002268 NetworkStateTracker nt = mNetTrackers[netType];
2269 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002270 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002271 if (p == null) return;
2272 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002273 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002274 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002275 String network = nt.getNetworkInfo().getTypeName();
2276 synchronized (mDnsLock) {
2277 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002278 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002279 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002280 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002281 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002282 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002283 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002284 NetworkUtils.makeStrings(dnses));
2285 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002286 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002287 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002288 // set per-pid dns for attached secondary nets
2289 List pids = mNetRequestersPids[netType];
2290 for (int y=0; y< pids.size(); y++) {
2291 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002292 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002293 }
2294 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002295 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002297 }
2298
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002299 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002300 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2301 NETWORK_RESTORE_DELAY_PROP_NAME);
2302 if(restoreDefaultNetworkDelayStr != null &&
2303 restoreDefaultNetworkDelayStr.length() != 0) {
2304 try {
2305 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2306 } catch (NumberFormatException e) {
2307 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002308 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002309 // if the system property isn't set, use the value for the apn type
2310 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2311
2312 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2313 (mNetConfigs[networkType] != null)) {
2314 ret = mNetConfigs[networkType].restoreTime;
2315 }
2316 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 }
2318
2319 @Override
2320 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002321 if (mContext.checkCallingOrSelfPermission(
2322 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002323 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002324 pw.println("Permission Denial: can't dump ConnectivityService " +
2325 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2326 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002327 return;
2328 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002329 pw.println();
2330 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002331 if (nst != null) {
2332 if (nst.getNetworkInfo().isConnected()) {
2333 pw.println("Active network: " + nst.getNetworkInfo().
2334 getTypeName());
2335 }
2336 pw.println(nst.getNetworkInfo());
2337 pw.println(nst);
2338 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002339 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002340 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002341
2342 pw.println("Network Requester Pids:");
2343 for (int net : mPriorityList) {
2344 String pidString = net + ": ";
2345 for (Object pid : mNetRequestersPids[net]) {
2346 pidString = pidString + pid.toString() + ", ";
2347 }
2348 pw.println(pidString);
2349 }
2350 pw.println();
2351
2352 pw.println("FeatureUsers:");
2353 for (Object requester : mFeatureUsers) {
2354 pw.println(requester.toString());
2355 }
2356 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002357
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002358 synchronized (this) {
2359 pw.println("NetworkTranstionWakeLock is currently " +
2360 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2361 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2362 }
2363 pw.println();
2364
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002365 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002366
2367 if (mInetLog != null) {
2368 pw.println();
2369 pw.println("Inet condition reports:");
2370 for(int i = 0; i < mInetLog.size(); i++) {
2371 pw.println(mInetLog.get(i));
2372 }
2373 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002374 }
2375
Robert Greenwalt2034b912009-08-12 16:08:25 -07002376 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002377 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002378 public MyHandler(Looper looper) {
2379 super(looper);
2380 }
2381
The Android Open Source Project28527d22009-03-03 19:31:44 -08002382 @Override
2383 public void handleMessage(Message msg) {
2384 NetworkInfo info;
2385 switch (msg.what) {
2386 case NetworkStateTracker.EVENT_STATE_CHANGED:
2387 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002388 int type = info.getType();
2389 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002390
Wink Savillea7d56572011-09-21 11:05:43 -07002391 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2392 (state == NetworkInfo.State.DISCONNECTED)) {
2393 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002394 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002395 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002396 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002397
2398 // Connectivity state changed:
2399 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002400 // [12-9] Network subtype (for mobile network, as defined
2401 // by TelephonyManager)
2402 // [8-3] Detailed state ordinal (as defined by
2403 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002404 // [2-0] Network type (as defined by ConnectivityManager)
2405 int eventLogParam = (info.getType() & 0x7) |
2406 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2407 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002408 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002409 eventLogParam);
2410
2411 if (info.getDetailedState() ==
2412 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002413 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002414 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002415 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002416 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002417 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002418 // the logic here is, handle SUSPENDED the same as
2419 // DISCONNECTED. The only difference being we are
2420 // broadcasting an intent with NetworkInfo that's
2421 // suspended. This allows the applications an
2422 // opportunity to handle DISCONNECTED and SUSPENDED
2423 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002424 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002425 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002426 handleConnect(info);
2427 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002428 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002429 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002430 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002431 // TODO: Temporary allowing network configuration
2432 // change not resetting sockets.
2433 // @see bug/4455071
2434 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002435 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002436 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002437 String causedBy = null;
2438 synchronized (ConnectivityService.this) {
2439 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2440 mNetTransitionWakeLock.isHeld()) {
2441 mNetTransitionWakeLock.release();
2442 causedBy = mNetTransitionWakeLockCausedBy;
2443 }
2444 }
2445 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002446 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002447 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002448 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002449 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002450 FeatureUser u = (FeatureUser)msg.obj;
2451 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002452 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002453 case EVENT_INET_CONDITION_CHANGE:
2454 {
2455 int netType = msg.arg1;
2456 int condition = msg.arg2;
2457 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002458 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002459 }
2460 case EVENT_INET_CONDITION_HOLD_END:
2461 {
2462 int netType = msg.arg1;
2463 int sequence = msg.arg2;
2464 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002465 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002466 }
2467 case EVENT_SET_NETWORK_PREFERENCE:
2468 {
2469 int preference = msg.arg1;
2470 handleSetNetworkPreference(preference);
2471 break;
2472 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002473 case EVENT_SET_MOBILE_DATA:
2474 {
2475 boolean enabled = (msg.arg1 == ENABLED);
2476 handleSetMobileData(enabled);
2477 break;
2478 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002479 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2480 {
2481 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002482 break;
2483 }
2484 case EVENT_SET_DEPENDENCY_MET:
2485 {
2486 boolean met = (msg.arg1 == ENABLED);
2487 handleSetDependencyMet(msg.arg2, met);
2488 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002489 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002490 case EVENT_RESTORE_DNS:
2491 {
2492 if (mActiveDefaultNetwork != -1) {
2493 handleDnsConfigurationChange(mActiveDefaultNetwork);
2494 }
2495 break;
2496 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002497 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2498 {
2499 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002500 sendStickyBroadcast(intent);
2501 break;
2502 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002503 case EVENT_SET_POLICY_DATA_ENABLE: {
2504 final int networkType = msg.arg1;
2505 final boolean enabled = msg.arg2 == ENABLED;
2506 handleSetPolicyDataEnable(networkType, enabled);
2507 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002508 }
2509 }
2510 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002511
2512 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002513 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002514 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002515
2516 if (isTetheringSupported()) {
2517 return mTethering.tether(iface);
2518 } else {
2519 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2520 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002521 }
2522
2523 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002524 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002525 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002526
2527 if (isTetheringSupported()) {
2528 return mTethering.untether(iface);
2529 } else {
2530 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2531 }
2532 }
2533
2534 // javadoc from interface
2535 public int getLastTetherError(String iface) {
2536 enforceTetherAccessPermission();
2537
2538 if (isTetheringSupported()) {
2539 return mTethering.getLastTetherError(iface);
2540 } else {
2541 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2542 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002543 }
2544
2545 // TODO - proper iface API for selection by property, inspection, etc
2546 public String[] getTetherableUsbRegexs() {
2547 enforceTetherAccessPermission();
2548 if (isTetheringSupported()) {
2549 return mTethering.getTetherableUsbRegexs();
2550 } else {
2551 return new String[0];
2552 }
2553 }
2554
2555 public String[] getTetherableWifiRegexs() {
2556 enforceTetherAccessPermission();
2557 if (isTetheringSupported()) {
2558 return mTethering.getTetherableWifiRegexs();
2559 } else {
2560 return new String[0];
2561 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002562 }
2563
Danica Chang96567052010-08-11 14:54:43 -07002564 public String[] getTetherableBluetoothRegexs() {
2565 enforceTetherAccessPermission();
2566 if (isTetheringSupported()) {
2567 return mTethering.getTetherableBluetoothRegexs();
2568 } else {
2569 return new String[0];
2570 }
2571 }
2572
Mike Lockwooded4a1742011-07-19 13:04:47 -07002573 public int setUsbTethering(boolean enable) {
2574 enforceTetherAccessPermission();
2575 if (isTetheringSupported()) {
2576 return mTethering.setUsbTethering(enable);
2577 } else {
2578 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2579 }
2580 }
2581
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002582 // TODO - move iface listing, queries, etc to new module
2583 // javadoc from interface
2584 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002585 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002586 return mTethering.getTetherableIfaces();
2587 }
2588
2589 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002590 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002591 return mTethering.getTetheredIfaces();
2592 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002593
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002594 @Override
2595 public String[] getTetheredIfacePairs() {
2596 enforceTetherAccessPermission();
2597 return mTethering.getTetheredIfacePairs();
2598 }
2599
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002600 public String[] getTetheringErroredIfaces() {
2601 enforceTetherAccessPermission();
2602 return mTethering.getErroredIfaces();
2603 }
2604
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002605 // if ro.tether.denied = true we default to no tethering
2606 // gservices could set the secure setting to 1 though to enable it on a build where it
2607 // had previously been turned off.
2608 public boolean isTetheringSupported() {
2609 enforceTetherAccessPermission();
2610 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002611 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2612 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2613 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002614 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002615
2616 // An API NetworkStateTrackers can call when they lose their network.
2617 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2618 // whichever happens first. The timer is started by the first caller and not
2619 // restarted by subsequent callers.
2620 public void requestNetworkTransitionWakelock(String forWhom) {
2621 enforceConnectivityInternalPermission();
2622 synchronized (this) {
2623 if (mNetTransitionWakeLock.isHeld()) return;
2624 mNetTransitionWakeLockSerialNumber++;
2625 mNetTransitionWakeLock.acquire();
2626 mNetTransitionWakeLockCausedBy = forWhom;
2627 }
2628 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002629 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002630 mNetTransitionWakeLockSerialNumber, 0),
2631 mNetTransitionWakeLockTimeout);
2632 return;
2633 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002634
Robert Greenwalt986c7412010-09-08 15:24:47 -07002635 // 100 percent is full good, 0 is full bad.
2636 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002637 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002638 mContext.enforceCallingOrSelfPermission(
2639 android.Manifest.permission.STATUS_BAR,
2640 "ConnectivityService");
2641
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002642 if (DBG) {
2643 int pid = getCallingPid();
2644 int uid = getCallingUid();
2645 String s = pid + "(" + uid + ") reports inet is " +
2646 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2647 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2648 mInetLog.add(s);
2649 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2650 mInetLog.remove(0);
2651 }
2652 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002653 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002654 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2655 }
2656
2657 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002658 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002659 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002660 return;
2661 }
2662 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002663 if (DBG) log("handleInetConditionChange: net=" + netType +
2664 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002665 return;
2666 }
Wink Savillea7d56572011-09-21 11:05:43 -07002667 if (VDBG) {
2668 log("handleInetConditionChange: net=" +
2669 netType + ", condition=" + condition +
2670 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2671 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002672 mDefaultInetCondition = condition;
2673 int delay;
2674 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002675 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002676 // setup a new hold to debounce this
2677 if (mDefaultInetCondition > 50) {
2678 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2679 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2680 } else {
2681 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2682 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2683 }
2684 mInetConditionChangeInFlight = true;
2685 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2686 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2687 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002688 // we've set the new condition, when this hold ends that will get picked up
2689 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002690 }
2691 }
2692
2693 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002694 if (DBG) {
2695 log("handleInetConditionHoldEnd: net=" + netType +
2696 ", condition=" + mDefaultInetCondition +
2697 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002698 }
2699 mInetConditionChangeInFlight = false;
2700
2701 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002702 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002703 return;
2704 }
2705 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002706 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002707 return;
2708 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002709 // TODO: Figure out why this optimization sometimes causes a
2710 // change in mDefaultInetCondition to be missed and the
2711 // UI to not be updated.
2712 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2713 // if (DBG) log("no change in condition - aborting");
2714 // return;
2715 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002716 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2717 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002718 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002719 return;
2720 }
2721 mDefaultInetConditionPublished = mDefaultInetCondition;
2722 sendInetConditionBroadcast(networkInfo);
2723 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002724 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002725
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002726 public ProxyProperties getProxy() {
2727 synchronized (mDefaultProxyLock) {
2728 return mDefaultProxyDisabled ? null : mDefaultProxy;
2729 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002730 }
2731
2732 public void setGlobalProxy(ProxyProperties proxyProperties) {
2733 enforceChangePermission();
2734 synchronized (mGlobalProxyLock) {
2735 if (proxyProperties == mGlobalProxy) return;
2736 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2737 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2738
2739 String host = "";
2740 int port = 0;
2741 String exclList = "";
2742 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2743 mGlobalProxy = new ProxyProperties(proxyProperties);
2744 host = mGlobalProxy.getHost();
2745 port = mGlobalProxy.getPort();
2746 exclList = mGlobalProxy.getExclusionList();
2747 } else {
2748 mGlobalProxy = null;
2749 }
2750 ContentResolver res = mContext.getContentResolver();
2751 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2752 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002753 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002754 exclList);
2755 }
2756
2757 if (mGlobalProxy == null) {
2758 proxyProperties = mDefaultProxy;
2759 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002760 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002761 }
2762
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002763 private void loadGlobalProxy() {
2764 ContentResolver res = mContext.getContentResolver();
2765 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2766 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2767 String exclList = Settings.Secure.getString(res,
2768 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2769 if (!TextUtils.isEmpty(host)) {
2770 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2771 synchronized (mGlobalProxyLock) {
2772 mGlobalProxy = proxyProperties;
2773 }
2774 }
2775 }
2776
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002777 public ProxyProperties getGlobalProxy() {
2778 synchronized (mGlobalProxyLock) {
2779 return mGlobalProxy;
2780 }
2781 }
2782
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002783 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2784 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2785 proxy = null;
2786 }
2787 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002788 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2789 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002790 mDefaultProxy = proxy;
2791
2792 if (!mDefaultProxyDisabled) {
2793 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002794 }
2795 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002796 }
2797
2798 private void handleDeprecatedGlobalHttpProxy() {
2799 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2800 Settings.Secure.HTTP_PROXY);
2801 if (!TextUtils.isEmpty(proxy)) {
2802 String data[] = proxy.split(":");
2803 String proxyHost = data[0];
2804 int proxyPort = 8080;
2805 if (data.length > 1) {
2806 try {
2807 proxyPort = Integer.parseInt(data[1]);
2808 } catch (NumberFormatException e) {
2809 return;
2810 }
2811 }
2812 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2813 setGlobalProxy(p);
2814 }
2815 }
2816
2817 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002818 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002819 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002820 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002821 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2822 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002823 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002824 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002825 }
2826
2827 private static class SettingsObserver extends ContentObserver {
2828 private int mWhat;
2829 private Handler mHandler;
2830 SettingsObserver(Handler handler, int what) {
2831 super(handler);
2832 mHandler = handler;
2833 mWhat = what;
2834 }
2835
2836 void observe(Context context) {
2837 ContentResolver resolver = context.getContentResolver();
2838 resolver.registerContentObserver(Settings.Secure.getUriFor(
2839 Settings.Secure.HTTP_PROXY), false, this);
2840 }
2841
2842 @Override
2843 public void onChange(boolean selfChange) {
2844 mHandler.obtainMessage(mWhat).sendToTarget();
2845 }
2846 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002847
2848 private void log(String s) {
2849 Slog.d(TAG, s);
2850 }
2851
2852 private void loge(String s) {
2853 Slog.e(TAG, s);
2854 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002855
repo syncf5de5572011-07-29 23:55:49 -07002856 int convertFeatureToNetworkType(int networkType, String feature) {
2857 int usedNetworkType = networkType;
2858
2859 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2860 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2861 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2862 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2863 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2864 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2865 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2866 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2867 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2868 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2869 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2870 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2871 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2872 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2873 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2874 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2875 } else {
2876 Slog.e(TAG, "Can't match any mobile netTracker!");
2877 }
2878 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2879 if (TextUtils.equals(feature, "p2p")) {
2880 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2881 } else {
2882 Slog.e(TAG, "Can't match any wifi netTracker!");
2883 }
2884 } else {
2885 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002886 }
repo syncf5de5572011-07-29 23:55:49 -07002887 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002888 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002889
2890 private static <T> T checkNotNull(T value, String message) {
2891 if (value == null) {
2892 throw new NullPointerException(message);
2893 }
2894 return value;
2895 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002896
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002897 /**
2898 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002899 * VpnBuilder and not available in ConnectivityManager. Permissions
2900 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002901 * @hide
2902 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002903 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002904 public boolean protectVpn(ParcelFileDescriptor socket) {
2905 try {
2906 int type = mActiveDefaultNetwork;
2907 if (ConnectivityManager.isNetworkTypeValid(type)) {
2908 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2909 return true;
2910 }
2911 } catch (Exception e) {
2912 // ignore
2913 } finally {
2914 try {
2915 socket.close();
2916 } catch (Exception e) {
2917 // ignore
2918 }
2919 }
2920 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002921 }
2922
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002923 /**
2924 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002925 * and not available in ConnectivityManager. Permissions are checked
2926 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002927 * @hide
2928 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002929 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002930 public boolean prepareVpn(String oldPackage, String newPackage) {
2931 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002932 }
2933
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002934 /**
2935 * Configure a TUN interface and return its file descriptor. Parameters
2936 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002937 * and not available in ConnectivityManager. Permissions are checked in
2938 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002939 * @hide
2940 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002941 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002942 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002943 return mVpn.establish(config);
2944 }
2945
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002946 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002947 * Start legacy VPN and return an intent to VpnDialogs. This method is
2948 * used by VpnSettings and not available in ConnectivityManager.
2949 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002950 * @hide
2951 */
2952 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002953 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2954 mVpn.startLegacyVpn(config, racoon, mtpd);
2955 }
2956
2957 /**
2958 * Return the information of the ongoing legacy VPN. This method is used
2959 * by VpnSettings and not available in ConnectivityManager. Permissions
2960 * are checked in Vpn class.
2961 * @hide
2962 */
2963 @Override
2964 public LegacyVpnInfo getLegacyVpnInfo() {
2965 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002966 }
2967
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002968 /**
2969 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2970 * through NetworkStateTracker since it works differently. For example, it
2971 * needs to override DNS servers but never takes the default routes. It
2972 * relies on another data network, and it could keep existing connections
2973 * alive after reconnecting, switching between networks, or even resuming
2974 * from deep sleep. Calls from applications should be done synchronously
2975 * to avoid race conditions. As these are all hidden APIs, refactoring can
2976 * be done whenever a better abstraction is developed.
2977 */
2978 public class VpnCallback {
2979
2980 private VpnCallback() {
2981 }
2982
Chia-chi Yehcc844502011-07-14 18:01:57 -07002983 public void override(List<String> dnsServers, List<String> searchDomains) {
2984 if (dnsServers == null) {
2985 restore();
2986 return;
2987 }
2988
2989 // Convert DNS servers into addresses.
2990 List<InetAddress> addresses = new ArrayList<InetAddress>();
2991 for (String address : dnsServers) {
2992 // Double check the addresses and remove invalid ones.
2993 try {
2994 addresses.add(InetAddress.parseNumericAddress(address));
2995 } catch (Exception e) {
2996 // ignore
2997 }
2998 }
2999 if (addresses.isEmpty()) {
3000 restore();
3001 return;
3002 }
3003
3004 // Concatenate search domains into a string.
3005 StringBuilder buffer = new StringBuilder();
3006 if (searchDomains != null) {
3007 for (String domain : searchDomains) {
3008 buffer.append(domain).append(' ');
3009 }
3010 }
3011 String domains = buffer.toString().trim();
3012
3013 // Apply DNS changes.
3014 boolean changed = false;
3015 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07003016 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003017 mDnsOverridden = true;
3018 }
3019 if (changed) {
3020 bumpDns();
3021 }
3022
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003023 // Temporarily disable the default proxy.
3024 synchronized (mDefaultProxyLock) {
3025 mDefaultProxyDisabled = true;
3026 if (mDefaultProxy != null) {
3027 sendProxyBroadcast(null);
3028 }
3029 }
3030
3031 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003032 }
3033
Chia-chi Yehcc844502011-07-14 18:01:57 -07003034 public void restore() {
3035 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003036 if (mDnsOverridden) {
3037 mDnsOverridden = false;
3038 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003039 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003040 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003041 synchronized (mDefaultProxyLock) {
3042 mDefaultProxyDisabled = false;
3043 if (mDefaultProxy != null) {
3044 sendProxyBroadcast(mDefaultProxy);
3045 }
3046 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003047 }
3048 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003049}