blob: 4b5c4a1beee1982109968ab67b52d327c096dd2f [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) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800995 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800996 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
997 return Phone.APN_TYPE_NOT_AVAILABLE;
998 } else {
999 // else make the attempt anyway - probably giving REQUEST_STARTED below
1000 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001001 }
1002
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001003 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1004
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001005 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001006 boolean addToList = true;
1007 if (restoreTimer < 0) {
1008 // In case there is no timer is specified for the feature,
1009 // make sure we don't add duplicate entry with the same request.
1010 for (FeatureUser u : mFeatureUsers) {
1011 if (u.isSameUser(f)) {
1012 // Duplicate user is found. Do not add.
1013 addToList = false;
1014 break;
1015 }
1016 }
1017 }
1018
1019 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001020 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1021 // this gets used for per-pid dns when connected
1022 mNetRequestersPids[usedNetworkType].add(currentPid);
1023 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001024 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001025
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001026 if (restoreTimer >= 0) {
1027 mHandler.sendMessageDelayed(
1028 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1029 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001030
Robert Greenwalta52c75a2009-08-19 20:19:33 -07001031 if ((ni.isConnectedOrConnecting() == true) &&
1032 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001033 if (ni.isConnected() == true) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001034 final long token = Binder.clearCallingIdentity();
1035 try {
1036 // add the pid-specific dns
1037 handleDnsConfigurationChange(usedNetworkType);
1038 if (VDBG) log("special network already active");
1039 } finally {
1040 Binder.restoreCallingIdentity(token);
1041 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001042 return Phone.APN_ALREADY_ACTIVE;
1043 }
Wink Savillea7d56572011-09-21 11:05:43 -07001044 if (VDBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001045 return Phone.APN_REQUEST_STARTED;
1046 }
1047
1048 // check if the radio in play can make another contact
1049 // assume if cannot for now
1050
Wink Savillea7d56572011-09-21 11:05:43 -07001051 if (DBG) {
1052 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1053 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001054 network.reconnect();
1055 return Phone.APN_REQUEST_STARTED;
1056 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -08001057 // need to remember this unsupported request so we respond appropriately on stop
1058 synchronized(this) {
1059 mFeatureUsers.add(f);
1060 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1061 // this gets used for per-pid dns when connected
1062 mNetRequestersPids[usedNetworkType].add(currentPid);
1063 }
1064 }
Robert Greenwaltd391e892010-05-18 10:52:51 -07001065 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001066 }
1067 }
1068 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001069 }
1070
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001071 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001072 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001073 enforceChangePermission();
1074
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001075 int pid = getCallingPid();
1076 int uid = getCallingUid();
1077
1078 FeatureUser u = null;
1079 boolean found = false;
1080
1081 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001082 for (FeatureUser x : mFeatureUsers) {
1083 if (x.isSameUser(pid, uid, networkType, feature)) {
1084 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001085 found = true;
1086 break;
1087 }
1088 }
1089 }
1090 if (found && u != null) {
1091 // stop regardless of how many other time this proc had called start
1092 return stopUsingNetworkFeature(u, true);
1093 } else {
1094 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001095 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001096 return 1;
1097 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001098 }
1099
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001100 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1101 int networkType = u.mNetworkType;
1102 String feature = u.mFeature;
1103 int pid = u.mPid;
1104 int uid = u.mUid;
1105
1106 NetworkStateTracker tracker = null;
1107 boolean callTeardown = false; // used to carry our decision outside of sync block
1108
Wink Savillea7d56572011-09-21 11:05:43 -07001109 if (VDBG) {
1110 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001111 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001112
The Android Open Source Project28527d22009-03-03 19:31:44 -08001113 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001114 if (DBG) {
1115 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1116 ", net is invalid");
1117 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001118 return -1;
1119 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001120
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001121 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1122 // sync block
1123 synchronized(this) {
1124 // check if this process still has an outstanding start request
1125 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001126 if (VDBG) {
1127 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1128 ", ignoring");
1129 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001130 return 1;
1131 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001132 u.unlinkDeathRecipient();
1133 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1134 // If we care about duplicate requests, check for that here.
1135 //
1136 // This is done to support the extension of a request - the app
1137 // can request we start the network feature again and renew the
1138 // auto-shutoff delay. Normal "stop" calls from the app though
1139 // do not pay attention to duplicate requests - in effect the
1140 // API does not refcount and a single stop will counter multiple starts.
1141 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001142 for (FeatureUser x : mFeatureUsers) {
1143 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001144 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001145 return 1;
1146 }
1147 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001148 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001149
repo syncf5de5572011-07-29 23:55:49 -07001150 // TODO - move to individual network trackers
1151 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1152
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001153 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001154 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001155 if (DBG) {
1156 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1157 " no known tracker for used net type " + usedNetworkType);
1158 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001159 return -1;
1160 }
1161 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001162 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001163 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001164 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001165 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001166 if (VDBG) {
1167 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1168 " others still using it");
1169 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001170 return 1;
1171 }
1172 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001173 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001174 if (DBG) {
1175 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1176 " not a known feature - dropping");
1177 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001178 }
1179 }
Wink Savillea7d56572011-09-21 11:05:43 -07001180
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001181 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001182 if (DBG) {
1183 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1184 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001185 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001186 return 1;
1187 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001188 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001189 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001190 }
1191
1192 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001193 * @deprecated use requestRouteToHostAddress instead
1194 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001195 * Ensure that a network route exists to deliver traffic to the specified
1196 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001197 * @param networkType the type of the network over which traffic to the
1198 * specified host is to be routed
1199 * @param hostAddress the IP address of the host to which the route is
1200 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001201 * @return {@code true} on success, {@code false} on failure
1202 */
1203 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001204 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1205
1206 if (inetAddress == null) {
1207 return false;
1208 }
1209
1210 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1211 }
1212
1213 /**
1214 * Ensure that a network route exists to deliver traffic to the specified
1215 * host via the specified network interface.
1216 * @param networkType the type of the network over which traffic to the
1217 * specified host is to be routed
1218 * @param hostAddress the IP address of the host to which the route is
1219 * desired
1220 * @return {@code true} on success, {@code false} on failure
1221 */
1222 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001223 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001224 if (mProtectedNetworks.contains(networkType)) {
1225 enforceConnectivityInternalPermission();
1226 }
1227
The Android Open Source Project28527d22009-03-03 19:31:44 -08001228 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001229 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001230 return false;
1231 }
1232 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001233
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001234 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1235 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001236 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001237 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001238 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001239 }
1240 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001241 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001242 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001243 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001244 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001245 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001246 return addRouteToAddress(lp, addr);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001247 } catch (UnknownHostException e) {
1248 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1249 } finally {
1250 Binder.restoreCallingIdentity(token);
1251 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001252 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001253 }
1254
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001255 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1256 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001257 }
1258
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001259 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1260 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001261 }
1262
Robert Greenwalt98107422011-07-22 11:55:33 -07001263 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001264 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001265 }
1266
1267 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001268 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001269 }
1270
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001271 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1272 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001273 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1274 if (bestRoute == null) {
1275 bestRoute = RouteInfo.makeHostRoute(addr);
1276 } else {
1277 if (bestRoute.getGateway().equals(addr)) {
1278 // if there is no better route, add the implied hostroute for our gateway
1279 bestRoute = RouteInfo.makeHostRoute(addr);
1280 } else {
1281 // if we will connect to this through another route, add a direct route
1282 // to it's gateway
1283 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1284 }
1285 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001286 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001287 }
1288
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001289 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001290 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001291 if ((ifaceName == null) || (lp == null) || (r == null)) {
1292 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1293 return false;
1294 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001295
1296 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001297 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001298 return false;
1299 }
1300
1301 if (r.isHostRoute() == false) {
1302 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1303 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001304 if (bestRoute.getGateway().equals(r.getGateway())) {
1305 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001306 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001307 } else {
1308 // if we will connect to our gateway through another route, add a direct
1309 // route to it's gateway
1310 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001311 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001312 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001313 }
1314 }
1315 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001316 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001317 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001318 if (toDefaultTable) {
1319 mAddedRoutes.add(r); // only track default table - only one apps can effect
1320 mNetd.addRoute(ifaceName, r);
1321 } else {
1322 mNetd.addSecondaryRoute(ifaceName, r);
1323 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001324 } catch (Exception e) {
1325 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001326 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001327 return false;
1328 }
1329 } else {
1330 // if we remove this one and there are no more like it, then refcount==0 and
1331 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001332 if (toDefaultTable) {
1333 mAddedRoutes.remove(r);
1334 if (mAddedRoutes.contains(r) == false) {
1335 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1336 try {
1337 mNetd.removeRoute(ifaceName, r);
1338 } catch (Exception e) {
1339 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001340 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001341 return false;
1342 }
1343 } else {
1344 if (VDBG) log("not removing " + r + " as it's still in use");
1345 }
1346 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001347 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001348 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001349 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001350 } catch (Exception e) {
1351 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001352 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001353 return false;
1354 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001355 }
1356 }
1357 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001358 }
1359
1360 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001361 * @see ConnectivityManager#getMobileDataEnabled()
1362 */
1363 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001364 // TODO: This detail should probably be in DataConnectionTracker's
1365 // which is where we store the value and maybe make this
1366 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001367 enforceAccessPermission();
1368 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1369 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001370 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001371 return retVal;
1372 }
1373
Robert Greenwalt34848c02011-03-25 13:09:25 -07001374 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001375 enforceConnectivityInternalPermission();
1376
Robert Greenwalt34848c02011-03-25 13:09:25 -07001377 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1378 (met ? ENABLED : DISABLED), networkType));
1379 }
1380
1381 private void handleSetDependencyMet(int networkType, boolean met) {
1382 if (mNetTrackers[networkType] != null) {
1383 if (DBG) {
1384 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1385 }
1386 mNetTrackers[networkType].setDependencyMet(met);
1387 }
1388 }
1389
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001390 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1391 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001392 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001393 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001394 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001395
1396 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001397 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001398 }
1399
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001400 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001401 // skip update when we've already applied rules
1402 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1403 if (oldRules == uidRules) return;
1404
1405 mUidRules.put(uid, uidRules);
1406 }
1407
1408 // TODO: dispatch into NMS to push rules towards kernel module
1409 // TODO: notify UID when it has requested targeted updates
1410 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001411
1412 @Override
1413 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1414 // only someone like NPMS should only be calling us
1415 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1416
1417 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 Sharkey921ebf22011-05-19 17:12:49 -07001428 };
1429
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001430 /**
1431 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1432 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001433 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001434 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001435 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001436
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001437 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001438 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001439 }
1440
1441 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001442 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001443 if (VDBG) {
1444 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001445 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001446 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1447 }
1448 }
1449
1450 @Override
1451 public void setPolicyDataEnable(int networkType, boolean enabled) {
1452 // only someone like NPMS should only be calling us
1453 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1454
1455 mHandler.sendMessage(mHandler.obtainMessage(
1456 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1457 }
1458
1459 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1460 if (isNetworkTypeValid(networkType)) {
1461 final NetworkStateTracker tracker = mNetTrackers[networkType];
1462 if (tracker != null) {
1463 tracker.setPolicyDataEnable(enabled);
1464 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001465 }
1466 }
1467
The Android Open Source Project28527d22009-03-03 19:31:44 -08001468 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001469 mContext.enforceCallingOrSelfPermission(
1470 android.Manifest.permission.ACCESS_NETWORK_STATE,
1471 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001472 }
1473
1474 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001475 mContext.enforceCallingOrSelfPermission(
1476 android.Manifest.permission.CHANGE_NETWORK_STATE,
1477 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001478 }
1479
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001480 // TODO Make this a special check when it goes public
1481 private void enforceTetherChangePermission() {
1482 mContext.enforceCallingOrSelfPermission(
1483 android.Manifest.permission.CHANGE_NETWORK_STATE,
1484 "ConnectivityService");
1485 }
1486
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001487 private void enforceTetherAccessPermission() {
1488 mContext.enforceCallingOrSelfPermission(
1489 android.Manifest.permission.ACCESS_NETWORK_STATE,
1490 "ConnectivityService");
1491 }
1492
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001493 private void enforceConnectivityInternalPermission() {
1494 mContext.enforceCallingOrSelfPermission(
1495 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1496 "ConnectivityService");
1497 }
1498
The Android Open Source Project28527d22009-03-03 19:31:44 -08001499 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001500 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1501 * network, we ignore it. If it is for the active network, we send out a
1502 * broadcast. But first, we check whether it might be possible to connect
1503 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001504 * @param info the {@code NetworkInfo} for the network
1505 */
1506 private void handleDisconnect(NetworkInfo info) {
1507
Robert Greenwalt2034b912009-08-12 16:08:25 -07001508 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509
Robert Greenwalt2034b912009-08-12 16:08:25 -07001510 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 /*
1512 * If the disconnected network is not the active one, then don't report
1513 * this as a loss of connectivity. What probably happened is that we're
1514 * getting the disconnect for a network that we explicitly disabled
1515 * in accordance with network preference policies.
1516 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001517 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001518 List pids = mNetRequestersPids[prevNetType];
1519 for (int i = 0; i<pids.size(); i++) {
1520 Integer pid = (Integer)pids.get(i);
1521 // will remove them because the net's no longer connected
1522 // need to do this now as only now do we know the pids and
1523 // can properly null things that are no longer referenced.
1524 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001525 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001526 }
1527
The Android Open Source Project28527d22009-03-03 19:31:44 -08001528 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1529 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1530 if (info.isFailover()) {
1531 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1532 info.setFailover(false);
1533 }
1534 if (info.getReason() != null) {
1535 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1536 }
1537 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001538 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1539 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001540 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001541
Robert Greenwalt34848c02011-03-25 13:09:25 -07001542 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001543 tryFailover(prevNetType);
1544 if (mActiveDefaultNetwork != -1) {
1545 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001546 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1547 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001548 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001549 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1550 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001551 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001552 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001553
1554 // Reset interface if no other connections are using the same interface
1555 boolean doReset = true;
1556 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1557 if (linkProperties != null) {
1558 String oldIface = linkProperties.getInterfaceName();
1559 if (TextUtils.isEmpty(oldIface) == false) {
1560 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1561 if (networkStateTracker == null) continue;
1562 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1563 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1564 LinkProperties l = networkStateTracker.getLinkProperties();
1565 if (l == null) continue;
1566 if (oldIface.equals(l.getInterfaceName())) {
1567 doReset = false;
1568 break;
1569 }
1570 }
1571 }
1572 }
1573 }
1574
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001575 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001576 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001577
Jeff Sharkey971cd162011-08-29 16:02:57 -07001578 final Intent immediateIntent = new Intent(intent);
1579 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1580 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001581 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001582 /*
1583 * If the failover network is already connected, then immediately send
1584 * out a followup broadcast indicating successful failover
1585 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001586 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001587 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1588 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001589 }
1590 }
1591
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001592 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001593 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001594 * If this is a default network, check if other defaults are available.
1595 * Try to reconnect on all available and let them hash it out when
1596 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001597 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001598 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001599 if (mActiveDefaultNetwork == prevNetType) {
1600 mActiveDefaultNetwork = -1;
1601 }
1602
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001603 // don't signal a reconnect for anything lower or equal priority than our
1604 // current connected default
1605 // TODO - don't filter by priority now - nice optimization but risky
1606// int currentPriority = -1;
1607// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001608// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001609// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001610 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001611 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001612 if (mNetConfigs[checkType] == null) continue;
1613 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001614 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001615
1616// Enabling the isAvailable() optimization caused mobile to not get
1617// selected if it was in the middle of error handling. Specifically
1618// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1619// would not be available and we wouldn't get connected to anything.
1620// So removing the isAvailable() optimization below for now. TODO: This
1621// optimization should work and we need to investigate why it doesn't work.
1622// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1623// complete before it is really complete.
1624// if (!mNetTrackers[checkType].isAvailable()) continue;
1625
Robert Greenwalt34848c02011-03-25 13:09:25 -07001626// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001627
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001628 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1629 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1630 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1631 checkInfo.setFailover(true);
1632 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001633 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001634 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001635 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001636 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001637 }
1638
1639 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001640 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1641 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001642 }
1643
Wink Saville4f0de1e2011-08-04 15:01:58 -07001644 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001645 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1646 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001647 }
1648
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001649 private void sendInetConditionBroadcast(NetworkInfo info) {
1650 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1651 }
1652
Wink Saville4f0de1e2011-08-04 15:01:58 -07001653 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001654 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001655 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1656 if (info.isFailover()) {
1657 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1658 info.setFailover(false);
1659 }
1660 if (info.getReason() != null) {
1661 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1662 }
1663 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001664 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1665 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001666 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001667 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001668 return intent;
1669 }
1670
1671 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1672 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1673 }
1674
1675 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1676 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001677 }
1678
1679 /**
1680 * Called when an attempt to fail over to another network has failed.
1681 * @param info the {@link NetworkInfo} for the failed network
1682 */
1683 private void handleConnectionFailure(NetworkInfo info) {
1684 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001685
Robert Greenwalt2034b912009-08-12 16:08:25 -07001686 String reason = info.getReason();
1687 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001688
Robert Greenwalte981bc52010-10-08 16:35:52 -07001689 String reasonText;
1690 if (reason == null) {
1691 reasonText = ".";
1692 } else {
1693 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001694 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001695 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001696
1697 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1698 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1699 if (getActiveNetworkInfo() == null) {
1700 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1701 }
1702 if (reason != null) {
1703 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1704 }
1705 if (extraInfo != null) {
1706 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1707 }
1708 if (info.isFailover()) {
1709 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1710 info.setFailover(false);
1711 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001712
Robert Greenwalt34848c02011-03-25 13:09:25 -07001713 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001714 tryFailover(info.getType());
1715 if (mActiveDefaultNetwork != -1) {
1716 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001717 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1718 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001719 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001720 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1721 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001722 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001723
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001724 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001725
1726 final Intent immediateIntent = new Intent(intent);
1727 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1728 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001729 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001730 /*
1731 * If the failover network is already connected, then immediately send
1732 * out a followup broadcast indicating successful failover
1733 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001734 if (mActiveDefaultNetwork != -1) {
1735 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001736 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001737 }
1738
1739 private void sendStickyBroadcast(Intent intent) {
1740 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001741 if (!mSystemReady) {
1742 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001743 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001744 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001745 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001746 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001747 }
1748
Dianne Hackborna417ff82009-12-08 19:45:14 -08001749 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001750 }
1751 }
1752
Wink Saville4f0de1e2011-08-04 15:01:58 -07001753 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1754 if (delayMs <= 0) {
1755 sendStickyBroadcast(intent);
1756 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001757 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001758 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1759 + intent.getAction());
1760 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001761 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1762 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1763 }
1764 }
1765
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001766 void systemReady() {
1767 synchronized(this) {
1768 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001769 if (mInitialBroadcast != null) {
1770 mContext.sendStickyBroadcast(mInitialBroadcast);
1771 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001772 }
1773 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001774 // load the global proxy at startup
1775 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001776 }
1777
1778 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001779 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001780
1781 // snapshot isFailover, because sendConnectedBroadcast() resets it
1782 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001783 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001784
Robert Greenwalt2034b912009-08-12 16:08:25 -07001785 // if this is a default net and other default is running
1786 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001787 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001788 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1789 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001790 mNetConfigs[mActiveDefaultNetwork].priority >
1791 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001792 mNetworkPreference == mActiveDefaultNetwork) {
1793 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001794 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001795 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001796 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001797 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001798 teardown(thisNet);
1799 return;
1800 } else {
1801 // tear down the other
1802 NetworkStateTracker otherNet =
1803 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001804 if (DBG) {
1805 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001806 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001807 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001808 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001809 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001810 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001811 return;
1812 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001813 }
1814 }
1815 synchronized (ConnectivityService.this) {
1816 // have a new default network, release the transition wakelock in a second
1817 // if it's held. The second pause is to allow apps to reconnect over the
1818 // new network
1819 if (mNetTransitionWakeLock.isHeld()) {
1820 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001821 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001822 mNetTransitionWakeLockSerialNumber, 0),
1823 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001824 }
1825 }
1826 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001827 // this will cause us to come up initially as unconnected and switching
1828 // to connected after our normal pause unless somebody reports us as reall
1829 // disconnected
1830 mDefaultInetConditionPublished = 0;
1831 mDefaultConnectionSequence++;
1832 mInetConditionChangeInFlight = false;
1833 // Don't do this - if we never sign in stay, grey
1834 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001835 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001836 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001837 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001838 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001839 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001840
1841 // notify battery stats service about this network
1842 final String iface = thisNet.getLinkProperties().getInterfaceName();
1843 if (iface != null) {
1844 try {
1845 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1846 } catch (RemoteException e) {
1847 // ignored; service lives in system_server
1848 }
1849 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001850 }
1851
The Android Open Source Project28527d22009-03-03 19:31:44 -08001852 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001853 * After a change in the connectivity state of a network. We're mainly
1854 * concerned with making sure that the list of DNS servers is set up
1855 * according to which networks are connected, and ensuring that the
1856 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001857 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001858 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001859 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1860
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001862 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001863 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001864 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001865 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001866
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001867 LinkProperties curLp = mCurrentLinkProperties[netType];
1868 LinkProperties newLp = null;
1869
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001870 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001871 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001872 if (VDBG) {
1873 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1874 " doReset=" + doReset + " resetMask=" + resetMask +
1875 "\n curLp=" + curLp +
1876 "\n newLp=" + newLp);
1877 }
1878
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001879 if (curLp != null) {
1880 if (curLp.isIdenticalInterfaceName(newLp)) {
1881 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1882 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1883 for (LinkAddress linkAddr : car.removed) {
1884 if (linkAddr.getAddress() instanceof Inet4Address) {
1885 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1886 }
1887 if (linkAddr.getAddress() instanceof Inet6Address) {
1888 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1889 }
Wink Saville051a6642011-07-13 13:44:13 -07001890 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001891 if (DBG) {
1892 log("handleConnectivityChange: addresses changed" +
1893 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1894 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001895 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001896 } else {
1897 if (DBG) {
1898 log("handleConnectivityChange: address are the same reset per doReset" +
1899 " linkProperty[" + netType + "]:" +
1900 " resetMask=" + resetMask);
1901 }
Wink Saville051a6642011-07-13 13:44:13 -07001902 }
1903 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001904 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001905 if (DBG) {
1906 log("handleConnectivityChange: interface not not equivalent reset both" +
1907 " linkProperty[" + netType + "]:" +
1908 " resetMask=" + resetMask);
1909 }
Wink Saville051a6642011-07-13 13:44:13 -07001910 }
Wink Saville051a6642011-07-13 13:44:13 -07001911 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001912 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07001913 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001914 }
1915 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001916 if (VDBG) {
1917 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1918 " doReset=" + doReset + " resetMask=" + resetMask +
1919 "\n curLp=" + curLp +
1920 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001921 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001923 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001924 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001925
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001926 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001927 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1928 if (linkProperties != null) {
1929 String iface = linkProperties.getInterfaceName();
1930 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001931 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001932 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1933 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001934
1935 // Tell VPN the interface is down. It is a temporary
1936 // but effective fix to make VPN aware of the change.
1937 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1938 mVpn.interfaceStatusChanged(iface, false);
1939 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001940 }
1941 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07001942 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001943 try {
1944 mNetd.flushInterfaceDnsCache(iface);
1945 } catch (Exception e) {
1946 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001947 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001948 }
1949 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001950 }
1951 }
1952 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001953
1954 // TODO: Temporary notifying upstread change to Tethering.
1955 // @see bug/4455071
1956 /** Notify TetheringService if interface name has been changed. */
1957 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1958 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1959 if (isTetheringSupported()) {
1960 mTethering.handleTetherIfaceChange();
1961 }
1962 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001963 }
1964
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001965 /**
1966 * Add and remove routes using the old properties (null if not previously connected),
1967 * new properties (null if becoming disconnected). May even be double null, which
1968 * is a noop.
1969 * Uses isLinkDefault to determine if default routes should be set or conversely if
1970 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001971 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001972 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07001973 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1974 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001975 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001976 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1977 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001978 if (curLp != null) {
1979 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001980 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001981 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001982 } else if (newLp != null) {
1983 routeDiff.added = newLp.getRoutes();
1984 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001985 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001986
Robert Greenwalt8d777252011-08-15 12:31:55 -07001987 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1988
Robert Greenwalt98107422011-07-22 11:55:33 -07001989 for (RouteInfo r : routeDiff.removed) {
1990 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001991 removeRoute(curLp, r, TO_DEFAULT_TABLE);
1992 }
1993 if (isLinkDefault == false) {
1994 // remove from a secondary route table
1995 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001996 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001997 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001998
Robert Greenwalt98107422011-07-22 11:55:33 -07001999 for (RouteInfo r : routeDiff.added) {
2000 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002001 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002002 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002003 // add to a secondary route table
2004 addRoute(newLp, r, TO_SECONDARY_TABLE);
2005
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002006 // many radios add a default route even when we don't want one.
2007 // remove the default route unless somebody else has asked for it
2008 String ifaceName = newLp.getInterfaceName();
2009 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002010 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002011 try {
2012 mNetd.removeRoute(ifaceName, r);
2013 } catch (Exception e) {
2014 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002015 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002016 }
2017 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002018 }
2019 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002020
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002021 if (!isLinkDefault) {
2022 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002023 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002024 // routes changed - remove all old dns entries and add new
2025 if (curLp != null) {
2026 for (InetAddress oldDns : curLp.getDnses()) {
2027 removeRouteToAddress(curLp, oldDns);
2028 }
2029 }
2030 if (newLp != null) {
2031 for (InetAddress newDns : newLp.getDnses()) {
2032 addRouteToAddress(newLp, newDns);
2033 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002034 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002035 } else {
2036 // no change in routes, check for change in dns themselves
2037 for (InetAddress oldDns : dnsDiff.removed) {
2038 removeRouteToAddress(curLp, oldDns);
2039 }
2040 for (InetAddress newDns : dnsDiff.added) {
2041 addRouteToAddress(newLp, newDns);
2042 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002043 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002044 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002045 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002046 }
2047
2048
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002049 /**
2050 * Reads the network specific TCP buffer sizes from SystemProperties
2051 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2052 * wide use
2053 */
2054 public void updateNetworkSettings(NetworkStateTracker nt) {
2055 String key = nt.getTcpBufferSizesPropName();
2056 String bufferSizes = SystemProperties.get(key);
2057
2058 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002059 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002060
2061 // Setting to default values so we won't be stuck to previous values
2062 key = "net.tcp.buffersize.default";
2063 bufferSizes = SystemProperties.get(key);
2064 }
2065
2066 // Set values in kernel
2067 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002068 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002069 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002070 + "] which comes from [" + key + "]");
2071 }
2072 setBufferSize(bufferSizes);
2073 }
2074 }
2075
2076 /**
2077 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2078 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2079 *
2080 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2081 * writeMin, writeInitial, writeMax"
2082 */
2083 private void setBufferSize(String bufferSizes) {
2084 try {
2085 String[] values = bufferSizes.split(",");
2086
2087 if (values.length == 6) {
2088 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002089 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2090 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2091 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2092 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2093 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2094 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002095 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002096 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002097 }
2098 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002099 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002100 }
2101 }
2102
Robert Greenwalt2034b912009-08-12 16:08:25 -07002103 /**
2104 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2105 * on the highest priority active net which this process requested.
2106 * If there aren't any, clear it out
2107 */
2108 private void reassessPidDns(int myPid, boolean doBump)
2109 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002110 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002111 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002112 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002113 continue;
2114 }
2115 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002116 if (nt.getNetworkInfo().isConnected() &&
2117 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002118 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002119 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002120 List pids = mNetRequestersPids[i];
2121 for (int j=0; j<pids.size(); j++) {
2122 Integer pid = (Integer)pids.get(j);
2123 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002124 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002125 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002126 if (doBump) {
2127 bumpDns();
2128 }
2129 return;
2130 }
2131 }
2132 }
2133 }
2134 // nothing found - delete
2135 for (int i = 1; ; i++) {
2136 String prop = "net.dns" + i + "." + myPid;
2137 if (SystemProperties.get(prop).length() == 0) {
2138 if (doBump) {
2139 bumpDns();
2140 }
2141 return;
2142 }
2143 SystemProperties.set(prop, "");
2144 }
2145 }
2146
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002147 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002148 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002149 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002150 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002151 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002152 String dnsString = dns.getHostAddress();
2153 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2154 changed = true;
2155 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2156 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002157 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002158 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002159 }
2160
2161 private void bumpDns() {
2162 /*
2163 * Bump the property that tells the name resolver library to reread
2164 * the DNS server list from the properties.
2165 */
2166 String propVal = SystemProperties.get("net.dnschange");
2167 int n = 0;
2168 if (propVal.length() != 0) {
2169 try {
2170 n = Integer.parseInt(propVal);
2171 } catch (NumberFormatException e) {}
2172 }
2173 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002174 /*
2175 * Tell the VMs to toss their DNS caches
2176 */
2177 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2178 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002179 /*
2180 * Connectivity events can happen before boot has completed ...
2181 */
2182 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002183 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002184 }
2185
Chia-chi Yehcc844502011-07-14 18:01:57 -07002186 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002187 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002188 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002189 boolean changed = false;
2190 int last = 0;
2191 if (dnses.size() == 0 && mDefaultDns != null) {
2192 ++last;
2193 String value = mDefaultDns.getHostAddress();
2194 if (!value.equals(SystemProperties.get("net.dns1"))) {
2195 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002196 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002197 }
2198 changed = true;
2199 SystemProperties.set("net.dns1", value);
2200 }
2201 } else {
2202 for (InetAddress dns : dnses) {
2203 ++last;
2204 String key = "net.dns" + last;
2205 String value = dns.getHostAddress();
2206 if (!changed && value.equals(SystemProperties.get(key))) {
2207 continue;
2208 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002209 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002210 log("adding dns " + value + " for " + network);
2211 }
2212 changed = true;
2213 SystemProperties.set(key, value);
2214 }
2215 }
2216 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2217 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002218 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002219 changed = true;
2220 SystemProperties.set(key, "");
2221 }
2222 mNumDnsEntries = last;
2223
Robert Greenwaltfce71862011-07-25 16:06:25 -07002224 if (changed) {
2225 try {
2226 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2227 mNetd.setDefaultInterfaceForDns(iface);
2228 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002229 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002230 }
2231 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002232 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2233 SystemProperties.set("net.dns.search", domains);
2234 changed = true;
2235 }
2236 return changed;
2237 }
2238
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002239 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002240 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002241 NetworkStateTracker nt = mNetTrackers[netType];
2242 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002243 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002244 if (p == null) return;
2245 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002246 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002247 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002248 String network = nt.getNetworkInfo().getTypeName();
2249 synchronized (mDnsLock) {
2250 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002251 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002252 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002253 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002254 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002255 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002256 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002257 NetworkUtils.makeStrings(dnses));
2258 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002259 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002260 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002261 // set per-pid dns for attached secondary nets
2262 List pids = mNetRequestersPids[netType];
2263 for (int y=0; y< pids.size(); y++) {
2264 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002265 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002266 }
2267 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002268 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002269 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002270 }
2271
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002272 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002273 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2274 NETWORK_RESTORE_DELAY_PROP_NAME);
2275 if(restoreDefaultNetworkDelayStr != null &&
2276 restoreDefaultNetworkDelayStr.length() != 0) {
2277 try {
2278 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2279 } catch (NumberFormatException e) {
2280 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002281 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002282 // if the system property isn't set, use the value for the apn type
2283 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2284
2285 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2286 (mNetConfigs[networkType] != null)) {
2287 ret = mNetConfigs[networkType].restoreTime;
2288 }
2289 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 }
2291
2292 @Override
2293 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002294 if (mContext.checkCallingOrSelfPermission(
2295 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002297 pw.println("Permission Denial: can't dump ConnectivityService " +
2298 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2299 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 return;
2301 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002302 pw.println();
2303 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002304 if (nst != null) {
2305 if (nst.getNetworkInfo().isConnected()) {
2306 pw.println("Active network: " + nst.getNetworkInfo().
2307 getTypeName());
2308 }
2309 pw.println(nst.getNetworkInfo());
2310 pw.println(nst);
2311 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002314
2315 pw.println("Network Requester Pids:");
2316 for (int net : mPriorityList) {
2317 String pidString = net + ": ";
2318 for (Object pid : mNetRequestersPids[net]) {
2319 pidString = pidString + pid.toString() + ", ";
2320 }
2321 pw.println(pidString);
2322 }
2323 pw.println();
2324
2325 pw.println("FeatureUsers:");
2326 for (Object requester : mFeatureUsers) {
2327 pw.println(requester.toString());
2328 }
2329 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002330
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002331 synchronized (this) {
2332 pw.println("NetworkTranstionWakeLock is currently " +
2333 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2334 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2335 }
2336 pw.println();
2337
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002338 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002339
2340 if (mInetLog != null) {
2341 pw.println();
2342 pw.println("Inet condition reports:");
2343 for(int i = 0; i < mInetLog.size(); i++) {
2344 pw.println(mInetLog.get(i));
2345 }
2346 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002347 }
2348
Robert Greenwalt2034b912009-08-12 16:08:25 -07002349 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002350 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002351 public MyHandler(Looper looper) {
2352 super(looper);
2353 }
2354
The Android Open Source Project28527d22009-03-03 19:31:44 -08002355 @Override
2356 public void handleMessage(Message msg) {
2357 NetworkInfo info;
2358 switch (msg.what) {
2359 case NetworkStateTracker.EVENT_STATE_CHANGED:
2360 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002361 int type = info.getType();
2362 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002363
Wink Savillea7d56572011-09-21 11:05:43 -07002364 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2365 (state == NetworkInfo.State.DISCONNECTED)) {
2366 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002367 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002368 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002369 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002370
2371 // Connectivity state changed:
2372 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002373 // [12-9] Network subtype (for mobile network, as defined
2374 // by TelephonyManager)
2375 // [8-3] Detailed state ordinal (as defined by
2376 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002377 // [2-0] Network type (as defined by ConnectivityManager)
2378 int eventLogParam = (info.getType() & 0x7) |
2379 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2380 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002381 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002382 eventLogParam);
2383
2384 if (info.getDetailedState() ==
2385 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002386 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002387 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002388 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002389 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002390 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002391 // the logic here is, handle SUSPENDED the same as
2392 // DISCONNECTED. The only difference being we are
2393 // broadcasting an intent with NetworkInfo that's
2394 // suspended. This allows the applications an
2395 // opportunity to handle DISCONNECTED and SUSPENDED
2396 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002397 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002398 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002399 handleConnect(info);
2400 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002401 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002402 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002403 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002404 // TODO: Temporary allowing network configuration
2405 // change not resetting sockets.
2406 // @see bug/4455071
2407 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002408 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002409 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002410 String causedBy = null;
2411 synchronized (ConnectivityService.this) {
2412 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2413 mNetTransitionWakeLock.isHeld()) {
2414 mNetTransitionWakeLock.release();
2415 causedBy = mNetTransitionWakeLockCausedBy;
2416 }
2417 }
2418 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002419 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002420 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002421 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002422 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002423 FeatureUser u = (FeatureUser)msg.obj;
2424 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002425 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002426 case EVENT_INET_CONDITION_CHANGE:
2427 {
2428 int netType = msg.arg1;
2429 int condition = msg.arg2;
2430 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002431 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002432 }
2433 case EVENT_INET_CONDITION_HOLD_END:
2434 {
2435 int netType = msg.arg1;
2436 int sequence = msg.arg2;
2437 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002438 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002439 }
2440 case EVENT_SET_NETWORK_PREFERENCE:
2441 {
2442 int preference = msg.arg1;
2443 handleSetNetworkPreference(preference);
2444 break;
2445 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002446 case EVENT_SET_MOBILE_DATA:
2447 {
2448 boolean enabled = (msg.arg1 == ENABLED);
2449 handleSetMobileData(enabled);
2450 break;
2451 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002452 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2453 {
2454 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002455 break;
2456 }
2457 case EVENT_SET_DEPENDENCY_MET:
2458 {
2459 boolean met = (msg.arg1 == ENABLED);
2460 handleSetDependencyMet(msg.arg2, met);
2461 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002462 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002463 case EVENT_RESTORE_DNS:
2464 {
2465 if (mActiveDefaultNetwork != -1) {
2466 handleDnsConfigurationChange(mActiveDefaultNetwork);
2467 }
2468 break;
2469 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002470 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2471 {
2472 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002473 sendStickyBroadcast(intent);
2474 break;
2475 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002476 case EVENT_SET_POLICY_DATA_ENABLE: {
2477 final int networkType = msg.arg1;
2478 final boolean enabled = msg.arg2 == ENABLED;
2479 handleSetPolicyDataEnable(networkType, enabled);
2480 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002481 }
2482 }
2483 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002484
2485 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002486 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002487 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002488
2489 if (isTetheringSupported()) {
2490 return mTethering.tether(iface);
2491 } else {
2492 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2493 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002494 }
2495
2496 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002497 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002498 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002499
2500 if (isTetheringSupported()) {
2501 return mTethering.untether(iface);
2502 } else {
2503 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2504 }
2505 }
2506
2507 // javadoc from interface
2508 public int getLastTetherError(String iface) {
2509 enforceTetherAccessPermission();
2510
2511 if (isTetheringSupported()) {
2512 return mTethering.getLastTetherError(iface);
2513 } else {
2514 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2515 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002516 }
2517
2518 // TODO - proper iface API for selection by property, inspection, etc
2519 public String[] getTetherableUsbRegexs() {
2520 enforceTetherAccessPermission();
2521 if (isTetheringSupported()) {
2522 return mTethering.getTetherableUsbRegexs();
2523 } else {
2524 return new String[0];
2525 }
2526 }
2527
2528 public String[] getTetherableWifiRegexs() {
2529 enforceTetherAccessPermission();
2530 if (isTetheringSupported()) {
2531 return mTethering.getTetherableWifiRegexs();
2532 } else {
2533 return new String[0];
2534 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002535 }
2536
Danica Chang96567052010-08-11 14:54:43 -07002537 public String[] getTetherableBluetoothRegexs() {
2538 enforceTetherAccessPermission();
2539 if (isTetheringSupported()) {
2540 return mTethering.getTetherableBluetoothRegexs();
2541 } else {
2542 return new String[0];
2543 }
2544 }
2545
Mike Lockwooded4a1742011-07-19 13:04:47 -07002546 public int setUsbTethering(boolean enable) {
2547 enforceTetherAccessPermission();
2548 if (isTetheringSupported()) {
2549 return mTethering.setUsbTethering(enable);
2550 } else {
2551 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2552 }
2553 }
2554
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002555 // TODO - move iface listing, queries, etc to new module
2556 // javadoc from interface
2557 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002558 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002559 return mTethering.getTetherableIfaces();
2560 }
2561
2562 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002563 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002564 return mTethering.getTetheredIfaces();
2565 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002566
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002567 @Override
2568 public String[] getTetheredIfacePairs() {
2569 enforceTetherAccessPermission();
2570 return mTethering.getTetheredIfacePairs();
2571 }
2572
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002573 public String[] getTetheringErroredIfaces() {
2574 enforceTetherAccessPermission();
2575 return mTethering.getErroredIfaces();
2576 }
2577
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002578 // if ro.tether.denied = true we default to no tethering
2579 // gservices could set the secure setting to 1 though to enable it on a build where it
2580 // had previously been turned off.
2581 public boolean isTetheringSupported() {
2582 enforceTetherAccessPermission();
2583 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002584 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2585 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2586 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002587 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002588
2589 // An API NetworkStateTrackers can call when they lose their network.
2590 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2591 // whichever happens first. The timer is started by the first caller and not
2592 // restarted by subsequent callers.
2593 public void requestNetworkTransitionWakelock(String forWhom) {
2594 enforceConnectivityInternalPermission();
2595 synchronized (this) {
2596 if (mNetTransitionWakeLock.isHeld()) return;
2597 mNetTransitionWakeLockSerialNumber++;
2598 mNetTransitionWakeLock.acquire();
2599 mNetTransitionWakeLockCausedBy = forWhom;
2600 }
2601 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002602 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002603 mNetTransitionWakeLockSerialNumber, 0),
2604 mNetTransitionWakeLockTimeout);
2605 return;
2606 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002607
Robert Greenwalt986c7412010-09-08 15:24:47 -07002608 // 100 percent is full good, 0 is full bad.
2609 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002610 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002611 mContext.enforceCallingOrSelfPermission(
2612 android.Manifest.permission.STATUS_BAR,
2613 "ConnectivityService");
2614
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002615 if (DBG) {
2616 int pid = getCallingPid();
2617 int uid = getCallingUid();
2618 String s = pid + "(" + uid + ") reports inet is " +
2619 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2620 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2621 mInetLog.add(s);
2622 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2623 mInetLog.remove(0);
2624 }
2625 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002626 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002627 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2628 }
2629
2630 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002631 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002632 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002633 return;
2634 }
2635 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002636 if (DBG) log("handleInetConditionChange: net=" + netType +
2637 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002638 return;
2639 }
Wink Savillea7d56572011-09-21 11:05:43 -07002640 if (VDBG) {
2641 log("handleInetConditionChange: net=" +
2642 netType + ", condition=" + condition +
2643 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2644 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002645 mDefaultInetCondition = condition;
2646 int delay;
2647 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002648 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002649 // setup a new hold to debounce this
2650 if (mDefaultInetCondition > 50) {
2651 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2652 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2653 } else {
2654 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2655 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2656 }
2657 mInetConditionChangeInFlight = true;
2658 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2659 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2660 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002661 // we've set the new condition, when this hold ends that will get picked up
2662 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002663 }
2664 }
2665
2666 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002667 if (DBG) {
2668 log("handleInetConditionHoldEnd: net=" + netType +
2669 ", condition=" + mDefaultInetCondition +
2670 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002671 }
2672 mInetConditionChangeInFlight = false;
2673
2674 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002675 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002676 return;
2677 }
2678 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002679 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002680 return;
2681 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002682 // TODO: Figure out why this optimization sometimes causes a
2683 // change in mDefaultInetCondition to be missed and the
2684 // UI to not be updated.
2685 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2686 // if (DBG) log("no change in condition - aborting");
2687 // return;
2688 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002689 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2690 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002691 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002692 return;
2693 }
2694 mDefaultInetConditionPublished = mDefaultInetCondition;
2695 sendInetConditionBroadcast(networkInfo);
2696 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002697 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002698
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002699 public ProxyProperties getProxy() {
2700 synchronized (mDefaultProxyLock) {
2701 return mDefaultProxyDisabled ? null : mDefaultProxy;
2702 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002703 }
2704
2705 public void setGlobalProxy(ProxyProperties proxyProperties) {
2706 enforceChangePermission();
2707 synchronized (mGlobalProxyLock) {
2708 if (proxyProperties == mGlobalProxy) return;
2709 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2710 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2711
2712 String host = "";
2713 int port = 0;
2714 String exclList = "";
2715 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2716 mGlobalProxy = new ProxyProperties(proxyProperties);
2717 host = mGlobalProxy.getHost();
2718 port = mGlobalProxy.getPort();
2719 exclList = mGlobalProxy.getExclusionList();
2720 } else {
2721 mGlobalProxy = null;
2722 }
2723 ContentResolver res = mContext.getContentResolver();
2724 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2725 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002726 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002727 exclList);
2728 }
2729
2730 if (mGlobalProxy == null) {
2731 proxyProperties = mDefaultProxy;
2732 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002733 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002734 }
2735
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002736 private void loadGlobalProxy() {
2737 ContentResolver res = mContext.getContentResolver();
2738 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2739 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2740 String exclList = Settings.Secure.getString(res,
2741 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2742 if (!TextUtils.isEmpty(host)) {
2743 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2744 synchronized (mGlobalProxyLock) {
2745 mGlobalProxy = proxyProperties;
2746 }
2747 }
2748 }
2749
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002750 public ProxyProperties getGlobalProxy() {
2751 synchronized (mGlobalProxyLock) {
2752 return mGlobalProxy;
2753 }
2754 }
2755
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002756 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2757 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2758 proxy = null;
2759 }
2760 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002761 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2762 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002763 mDefaultProxy = proxy;
2764
2765 if (!mDefaultProxyDisabled) {
2766 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002767 }
2768 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002769 }
2770
2771 private void handleDeprecatedGlobalHttpProxy() {
2772 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2773 Settings.Secure.HTTP_PROXY);
2774 if (!TextUtils.isEmpty(proxy)) {
2775 String data[] = proxy.split(":");
2776 String proxyHost = data[0];
2777 int proxyPort = 8080;
2778 if (data.length > 1) {
2779 try {
2780 proxyPort = Integer.parseInt(data[1]);
2781 } catch (NumberFormatException e) {
2782 return;
2783 }
2784 }
2785 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2786 setGlobalProxy(p);
2787 }
2788 }
2789
2790 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002791 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002792 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002793 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002794 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2795 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002796 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002797 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002798 }
2799
2800 private static class SettingsObserver extends ContentObserver {
2801 private int mWhat;
2802 private Handler mHandler;
2803 SettingsObserver(Handler handler, int what) {
2804 super(handler);
2805 mHandler = handler;
2806 mWhat = what;
2807 }
2808
2809 void observe(Context context) {
2810 ContentResolver resolver = context.getContentResolver();
2811 resolver.registerContentObserver(Settings.Secure.getUriFor(
2812 Settings.Secure.HTTP_PROXY), false, this);
2813 }
2814
2815 @Override
2816 public void onChange(boolean selfChange) {
2817 mHandler.obtainMessage(mWhat).sendToTarget();
2818 }
2819 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002820
2821 private void log(String s) {
2822 Slog.d(TAG, s);
2823 }
2824
2825 private void loge(String s) {
2826 Slog.e(TAG, s);
2827 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002828
repo syncf5de5572011-07-29 23:55:49 -07002829 int convertFeatureToNetworkType(int networkType, String feature) {
2830 int usedNetworkType = networkType;
2831
2832 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2833 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2834 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2835 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2836 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2837 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2838 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2839 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2840 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2841 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2842 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2843 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2844 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2845 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2846 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2847 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2848 } else {
2849 Slog.e(TAG, "Can't match any mobile netTracker!");
2850 }
2851 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2852 if (TextUtils.equals(feature, "p2p")) {
2853 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2854 } else {
2855 Slog.e(TAG, "Can't match any wifi netTracker!");
2856 }
2857 } else {
2858 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002859 }
repo syncf5de5572011-07-29 23:55:49 -07002860 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002861 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002862
2863 private static <T> T checkNotNull(T value, String message) {
2864 if (value == null) {
2865 throw new NullPointerException(message);
2866 }
2867 return value;
2868 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002869
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002870 /**
2871 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002872 * VpnBuilder and not available in ConnectivityManager. Permissions
2873 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002874 * @hide
2875 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002876 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002877 public boolean protectVpn(ParcelFileDescriptor socket) {
2878 try {
2879 int type = mActiveDefaultNetwork;
2880 if (ConnectivityManager.isNetworkTypeValid(type)) {
2881 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2882 return true;
2883 }
2884 } catch (Exception e) {
2885 // ignore
2886 } finally {
2887 try {
2888 socket.close();
2889 } catch (Exception e) {
2890 // ignore
2891 }
2892 }
2893 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002894 }
2895
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002896 /**
2897 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002898 * and not available in ConnectivityManager. Permissions are checked
2899 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002900 * @hide
2901 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002902 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002903 public boolean prepareVpn(String oldPackage, String newPackage) {
2904 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002905 }
2906
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002907 /**
2908 * Configure a TUN interface and return its file descriptor. Parameters
2909 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002910 * and not available in ConnectivityManager. Permissions are checked in
2911 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002912 * @hide
2913 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002914 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002915 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002916 return mVpn.establish(config);
2917 }
2918
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002919 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002920 * Start legacy VPN and return an intent to VpnDialogs. This method is
2921 * used by VpnSettings and not available in ConnectivityManager.
2922 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002923 * @hide
2924 */
2925 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002926 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2927 mVpn.startLegacyVpn(config, racoon, mtpd);
2928 }
2929
2930 /**
2931 * Return the information of the ongoing legacy VPN. This method is used
2932 * by VpnSettings and not available in ConnectivityManager. Permissions
2933 * are checked in Vpn class.
2934 * @hide
2935 */
2936 @Override
2937 public LegacyVpnInfo getLegacyVpnInfo() {
2938 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002939 }
2940
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002941 /**
2942 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2943 * through NetworkStateTracker since it works differently. For example, it
2944 * needs to override DNS servers but never takes the default routes. It
2945 * relies on another data network, and it could keep existing connections
2946 * alive after reconnecting, switching between networks, or even resuming
2947 * from deep sleep. Calls from applications should be done synchronously
2948 * to avoid race conditions. As these are all hidden APIs, refactoring can
2949 * be done whenever a better abstraction is developed.
2950 */
2951 public class VpnCallback {
2952
2953 private VpnCallback() {
2954 }
2955
Chia-chi Yehcc844502011-07-14 18:01:57 -07002956 public void override(List<String> dnsServers, List<String> searchDomains) {
2957 if (dnsServers == null) {
2958 restore();
2959 return;
2960 }
2961
2962 // Convert DNS servers into addresses.
2963 List<InetAddress> addresses = new ArrayList<InetAddress>();
2964 for (String address : dnsServers) {
2965 // Double check the addresses and remove invalid ones.
2966 try {
2967 addresses.add(InetAddress.parseNumericAddress(address));
2968 } catch (Exception e) {
2969 // ignore
2970 }
2971 }
2972 if (addresses.isEmpty()) {
2973 restore();
2974 return;
2975 }
2976
2977 // Concatenate search domains into a string.
2978 StringBuilder buffer = new StringBuilder();
2979 if (searchDomains != null) {
2980 for (String domain : searchDomains) {
2981 buffer.append(domain).append(' ');
2982 }
2983 }
2984 String domains = buffer.toString().trim();
2985
2986 // Apply DNS changes.
2987 boolean changed = false;
2988 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002989 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002990 mDnsOverridden = true;
2991 }
2992 if (changed) {
2993 bumpDns();
2994 }
2995
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002996 // Temporarily disable the default proxy.
2997 synchronized (mDefaultProxyLock) {
2998 mDefaultProxyDisabled = true;
2999 if (mDefaultProxy != null) {
3000 sendProxyBroadcast(null);
3001 }
3002 }
3003
3004 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003005 }
3006
Chia-chi Yehcc844502011-07-14 18:01:57 -07003007 public void restore() {
3008 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003009 if (mDnsOverridden) {
3010 mDnsOverridden = false;
3011 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003012 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003013 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003014 synchronized (mDefaultProxyLock) {
3015 mDefaultProxyDisabled = false;
3016 if (mDefaultProxy != null) {
3017 sendProxyBroadcast(mDefaultProxy);
3018 }
3019 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003020 }
3021 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003022}