blob: 6e4aca77882811f41675236d4e71a052c9178df5 [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) {
1034 // add the pid-specific dns
repo sync3035f652011-08-02 13:39:06 -07001035 handleDnsConfigurationChange(usedNetworkType);
Wink Savillea7d56572011-09-21 11:05:43 -07001036 if (VDBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001037 return Phone.APN_ALREADY_ACTIVE;
1038 }
Wink Savillea7d56572011-09-21 11:05:43 -07001039 if (VDBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001040 return Phone.APN_REQUEST_STARTED;
1041 }
1042
1043 // check if the radio in play can make another contact
1044 // assume if cannot for now
1045
Wink Savillea7d56572011-09-21 11:05:43 -07001046 if (DBG) {
1047 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1048 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001049 network.reconnect();
1050 return Phone.APN_REQUEST_STARTED;
1051 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -08001052 // need to remember this unsupported request so we respond appropriately on stop
1053 synchronized(this) {
1054 mFeatureUsers.add(f);
1055 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1056 // this gets used for per-pid dns when connected
1057 mNetRequestersPids[usedNetworkType].add(currentPid);
1058 }
1059 }
Robert Greenwaltd391e892010-05-18 10:52:51 -07001060 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001061 }
1062 }
1063 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001064 }
1065
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001066 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001067 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001068 enforceChangePermission();
1069
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001070 int pid = getCallingPid();
1071 int uid = getCallingUid();
1072
1073 FeatureUser u = null;
1074 boolean found = false;
1075
1076 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001077 for (FeatureUser x : mFeatureUsers) {
1078 if (x.isSameUser(pid, uid, networkType, feature)) {
1079 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001080 found = true;
1081 break;
1082 }
1083 }
1084 }
1085 if (found && u != null) {
1086 // stop regardless of how many other time this proc had called start
1087 return stopUsingNetworkFeature(u, true);
1088 } else {
1089 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001090 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001091 return 1;
1092 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001093 }
1094
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001095 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1096 int networkType = u.mNetworkType;
1097 String feature = u.mFeature;
1098 int pid = u.mPid;
1099 int uid = u.mUid;
1100
1101 NetworkStateTracker tracker = null;
1102 boolean callTeardown = false; // used to carry our decision outside of sync block
1103
Wink Savillea7d56572011-09-21 11:05:43 -07001104 if (VDBG) {
1105 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001106 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001107
The Android Open Source Project28527d22009-03-03 19:31:44 -08001108 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001109 if (DBG) {
1110 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1111 ", net is invalid");
1112 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001113 return -1;
1114 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001115
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001116 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1117 // sync block
1118 synchronized(this) {
1119 // check if this process still has an outstanding start request
1120 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001121 if (VDBG) {
1122 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1123 ", ignoring");
1124 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001125 return 1;
1126 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001127 u.unlinkDeathRecipient();
1128 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1129 // If we care about duplicate requests, check for that here.
1130 //
1131 // This is done to support the extension of a request - the app
1132 // can request we start the network feature again and renew the
1133 // auto-shutoff delay. Normal "stop" calls from the app though
1134 // do not pay attention to duplicate requests - in effect the
1135 // API does not refcount and a single stop will counter multiple starts.
1136 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001137 for (FeatureUser x : mFeatureUsers) {
1138 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001139 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001140 return 1;
1141 }
1142 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001143 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001144
repo syncf5de5572011-07-29 23:55:49 -07001145 // TODO - move to individual network trackers
1146 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1147
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001148 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001149 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001150 if (DBG) {
1151 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1152 " no known tracker for used net type " + usedNetworkType);
1153 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001154 return -1;
1155 }
1156 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001157 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001158 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001159 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001160 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001161 if (VDBG) {
1162 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1163 " others still using it");
1164 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001165 return 1;
1166 }
1167 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001168 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001169 if (DBG) {
1170 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1171 " not a known feature - dropping");
1172 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001173 }
1174 }
Wink Savillea7d56572011-09-21 11:05:43 -07001175
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001176 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001177 if (DBG) {
1178 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1179 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001180 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001181 return 1;
1182 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001183 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001184 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001185 }
1186
1187 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001188 * @deprecated use requestRouteToHostAddress instead
1189 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001190 * Ensure that a network route exists to deliver traffic to the specified
1191 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001192 * @param networkType the type of the network over which traffic to the
1193 * specified host is to be routed
1194 * @param hostAddress the IP address of the host to which the route is
1195 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001196 * @return {@code true} on success, {@code false} on failure
1197 */
1198 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001199 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1200
1201 if (inetAddress == null) {
1202 return false;
1203 }
1204
1205 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1206 }
1207
1208 /**
1209 * Ensure that a network route exists to deliver traffic to the specified
1210 * host via the specified network interface.
1211 * @param networkType the type of the network over which traffic to the
1212 * specified host is to be routed
1213 * @param hostAddress the IP address of the host to which the route is
1214 * desired
1215 * @return {@code true} on success, {@code false} on failure
1216 */
1217 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001218 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001219 if (mProtectedNetworks.contains(networkType)) {
1220 enforceConnectivityInternalPermission();
1221 }
1222
The Android Open Source Project28527d22009-03-03 19:31:44 -08001223 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1224 return false;
1225 }
1226 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001227
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001228 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1229 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001230 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001231 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001232 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001233 }
1234 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001235 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001236 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001237 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001238 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001239 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001240 } catch (UnknownHostException e) {}
1241 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001242 }
1243
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001244 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1245 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001246 }
1247
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001248 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1249 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001250 }
1251
Robert Greenwalt98107422011-07-22 11:55:33 -07001252 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001253 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001254 }
1255
1256 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001257 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001258 }
1259
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001260 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1261 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001262 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1263 if (bestRoute == null) {
1264 bestRoute = RouteInfo.makeHostRoute(addr);
1265 } else {
1266 if (bestRoute.getGateway().equals(addr)) {
1267 // if there is no better route, add the implied hostroute for our gateway
1268 bestRoute = RouteInfo.makeHostRoute(addr);
1269 } else {
1270 // if we will connect to this through another route, add a direct route
1271 // to it's gateway
1272 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1273 }
1274 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001275 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001276 }
1277
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001278 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001279 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001280 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1281
1282 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001283 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001284 return false;
1285 }
1286
1287 if (r.isHostRoute() == false) {
1288 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1289 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001290 if (bestRoute.getGateway().equals(r.getGateway())) {
1291 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001292 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001293 } else {
1294 // if we will connect to our gateway through another route, add a direct
1295 // route to it's gateway
1296 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001297 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001298 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001299 }
1300 }
1301 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001302 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001303 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001304 if (toDefaultTable) {
1305 mAddedRoutes.add(r); // only track default table - only one apps can effect
1306 mNetd.addRoute(ifaceName, r);
1307 } else {
1308 mNetd.addSecondaryRoute(ifaceName, r);
1309 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001310 } catch (Exception e) {
1311 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001312 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001313 return false;
1314 }
1315 } else {
1316 // if we remove this one and there are no more like it, then refcount==0 and
1317 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001318 if (toDefaultTable) {
1319 mAddedRoutes.remove(r);
1320 if (mAddedRoutes.contains(r) == false) {
1321 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1322 try {
1323 mNetd.removeRoute(ifaceName, r);
1324 } catch (Exception e) {
1325 // never crash - catch them all
1326 if (VDBG) loge("Exception trying to remove a route: " + e);
1327 return false;
1328 }
1329 } else {
1330 if (VDBG) log("not removing " + r + " as it's still in use");
1331 }
1332 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001333 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001334 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001335 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001336 } catch (Exception e) {
1337 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001338 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001339 return false;
1340 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001341 }
1342 }
1343 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001344 }
1345
1346 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001347 * @see ConnectivityManager#getMobileDataEnabled()
1348 */
1349 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001350 // TODO: This detail should probably be in DataConnectionTracker's
1351 // which is where we store the value and maybe make this
1352 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001353 enforceAccessPermission();
1354 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1355 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001356 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001357 return retVal;
1358 }
1359
Robert Greenwalt34848c02011-03-25 13:09:25 -07001360 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001361 enforceConnectivityInternalPermission();
1362
Robert Greenwalt34848c02011-03-25 13:09:25 -07001363 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1364 (met ? ENABLED : DISABLED), networkType));
1365 }
1366
1367 private void handleSetDependencyMet(int networkType, boolean met) {
1368 if (mNetTrackers[networkType] != null) {
1369 if (DBG) {
1370 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1371 }
1372 mNetTrackers[networkType].setDependencyMet(met);
1373 }
1374 }
1375
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001376 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1377 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001378 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001379 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001380 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001381
1382 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001383 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001384 }
1385
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001386 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001387 // skip update when we've already applied rules
1388 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1389 if (oldRules == uidRules) return;
1390
1391 mUidRules.put(uid, uidRules);
1392 }
1393
1394 // TODO: dispatch into NMS to push rules towards kernel module
1395 // TODO: notify UID when it has requested targeted updates
1396 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001397
1398 @Override
1399 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1400 // only someone like NPMS should only be calling us
1401 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1402
1403 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001404 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001405 }
1406
1407 synchronized (mRulesLock) {
1408 mMeteredIfaces.clear();
1409 for (String iface : meteredIfaces) {
1410 mMeteredIfaces.add(iface);
1411 }
1412 }
1413 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001414 };
1415
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001416 /**
1417 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1418 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001419 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001420 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001421 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001422
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001423 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001424 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001425 }
1426
1427 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001428 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001429 if (VDBG) {
1430 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001431 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001432 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1433 }
1434 }
1435
1436 @Override
1437 public void setPolicyDataEnable(int networkType, boolean enabled) {
1438 // only someone like NPMS should only be calling us
1439 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1440
1441 mHandler.sendMessage(mHandler.obtainMessage(
1442 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1443 }
1444
1445 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1446 if (isNetworkTypeValid(networkType)) {
1447 final NetworkStateTracker tracker = mNetTrackers[networkType];
1448 if (tracker != null) {
1449 tracker.setPolicyDataEnable(enabled);
1450 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001451 }
1452 }
1453
The Android Open Source Project28527d22009-03-03 19:31:44 -08001454 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001455 mContext.enforceCallingOrSelfPermission(
1456 android.Manifest.permission.ACCESS_NETWORK_STATE,
1457 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001458 }
1459
1460 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001461 mContext.enforceCallingOrSelfPermission(
1462 android.Manifest.permission.CHANGE_NETWORK_STATE,
1463 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001464 }
1465
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001466 // TODO Make this a special check when it goes public
1467 private void enforceTetherChangePermission() {
1468 mContext.enforceCallingOrSelfPermission(
1469 android.Manifest.permission.CHANGE_NETWORK_STATE,
1470 "ConnectivityService");
1471 }
1472
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001473 private void enforceTetherAccessPermission() {
1474 mContext.enforceCallingOrSelfPermission(
1475 android.Manifest.permission.ACCESS_NETWORK_STATE,
1476 "ConnectivityService");
1477 }
1478
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001479 private void enforceConnectivityInternalPermission() {
1480 mContext.enforceCallingOrSelfPermission(
1481 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1482 "ConnectivityService");
1483 }
1484
The Android Open Source Project28527d22009-03-03 19:31:44 -08001485 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001486 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1487 * network, we ignore it. If it is for the active network, we send out a
1488 * broadcast. But first, we check whether it might be possible to connect
1489 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001490 * @param info the {@code NetworkInfo} for the network
1491 */
1492 private void handleDisconnect(NetworkInfo info) {
1493
Robert Greenwalt2034b912009-08-12 16:08:25 -07001494 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001495
Robert Greenwalt2034b912009-08-12 16:08:25 -07001496 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001497 /*
1498 * If the disconnected network is not the active one, then don't report
1499 * this as a loss of connectivity. What probably happened is that we're
1500 * getting the disconnect for a network that we explicitly disabled
1501 * in accordance with network preference policies.
1502 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001503 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001504 List pids = mNetRequestersPids[prevNetType];
1505 for (int i = 0; i<pids.size(); i++) {
1506 Integer pid = (Integer)pids.get(i);
1507 // will remove them because the net's no longer connected
1508 // need to do this now as only now do we know the pids and
1509 // can properly null things that are no longer referenced.
1510 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001511 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001512 }
1513
The Android Open Source Project28527d22009-03-03 19:31:44 -08001514 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1515 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1516 if (info.isFailover()) {
1517 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1518 info.setFailover(false);
1519 }
1520 if (info.getReason() != null) {
1521 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1522 }
1523 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001524 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1525 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001526 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001527
Robert Greenwalt34848c02011-03-25 13:09:25 -07001528 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001529 tryFailover(prevNetType);
1530 if (mActiveDefaultNetwork != -1) {
1531 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001532 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1533 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001534 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001535 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1536 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001537 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001538 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001539
1540 // Reset interface if no other connections are using the same interface
1541 boolean doReset = true;
1542 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1543 if (linkProperties != null) {
1544 String oldIface = linkProperties.getInterfaceName();
1545 if (TextUtils.isEmpty(oldIface) == false) {
1546 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1547 if (networkStateTracker == null) continue;
1548 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1549 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1550 LinkProperties l = networkStateTracker.getLinkProperties();
1551 if (l == null) continue;
1552 if (oldIface.equals(l.getInterfaceName())) {
1553 doReset = false;
1554 break;
1555 }
1556 }
1557 }
1558 }
1559 }
1560
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001561 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001562 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001563
Jeff Sharkey971cd162011-08-29 16:02:57 -07001564 final Intent immediateIntent = new Intent(intent);
1565 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1566 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001567 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001568 /*
1569 * If the failover network is already connected, then immediately send
1570 * out a followup broadcast indicating successful failover
1571 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001572 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001573 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1574 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001575 }
1576 }
1577
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001578 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001579 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001580 * If this is a default network, check if other defaults are available.
1581 * Try to reconnect on all available and let them hash it out when
1582 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001583 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001584 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001585 if (mActiveDefaultNetwork == prevNetType) {
1586 mActiveDefaultNetwork = -1;
1587 }
1588
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001589 // don't signal a reconnect for anything lower or equal priority than our
1590 // current connected default
1591 // TODO - don't filter by priority now - nice optimization but risky
1592// int currentPriority = -1;
1593// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001594// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001595// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001596 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001597 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001598 if (mNetConfigs[checkType] == null) continue;
1599 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001600 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001601
1602// Enabling the isAvailable() optimization caused mobile to not get
1603// selected if it was in the middle of error handling. Specifically
1604// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1605// would not be available and we wouldn't get connected to anything.
1606// So removing the isAvailable() optimization below for now. TODO: This
1607// optimization should work and we need to investigate why it doesn't work.
1608// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1609// complete before it is really complete.
1610// if (!mNetTrackers[checkType].isAvailable()) continue;
1611
Robert Greenwalt34848c02011-03-25 13:09:25 -07001612// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001613
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001614 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1615 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1616 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1617 checkInfo.setFailover(true);
1618 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001619 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001620 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001621 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001622 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001623 }
1624
1625 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001626 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1627 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001628 }
1629
Wink Saville4f0de1e2011-08-04 15:01:58 -07001630 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001631 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1632 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001633 }
1634
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001635 private void sendInetConditionBroadcast(NetworkInfo info) {
1636 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1637 }
1638
Wink Saville4f0de1e2011-08-04 15:01:58 -07001639 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001640 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001641 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1642 if (info.isFailover()) {
1643 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1644 info.setFailover(false);
1645 }
1646 if (info.getReason() != null) {
1647 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1648 }
1649 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001650 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1651 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001652 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001653 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001654 return intent;
1655 }
1656
1657 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1658 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1659 }
1660
1661 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1662 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001663 }
1664
1665 /**
1666 * Called when an attempt to fail over to another network has failed.
1667 * @param info the {@link NetworkInfo} for the failed network
1668 */
1669 private void handleConnectionFailure(NetworkInfo info) {
1670 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001671
Robert Greenwalt2034b912009-08-12 16:08:25 -07001672 String reason = info.getReason();
1673 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001674
Robert Greenwalte981bc52010-10-08 16:35:52 -07001675 String reasonText;
1676 if (reason == null) {
1677 reasonText = ".";
1678 } else {
1679 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001680 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001681 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001682
1683 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1684 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1685 if (getActiveNetworkInfo() == null) {
1686 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1687 }
1688 if (reason != null) {
1689 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1690 }
1691 if (extraInfo != null) {
1692 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1693 }
1694 if (info.isFailover()) {
1695 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1696 info.setFailover(false);
1697 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001698
Robert Greenwalt34848c02011-03-25 13:09:25 -07001699 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001700 tryFailover(info.getType());
1701 if (mActiveDefaultNetwork != -1) {
1702 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001703 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1704 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001705 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001706 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1707 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001708 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001709
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001710 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001711
1712 final Intent immediateIntent = new Intent(intent);
1713 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1714 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001715 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001716 /*
1717 * If the failover network is already connected, then immediately send
1718 * out a followup broadcast indicating successful failover
1719 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001720 if (mActiveDefaultNetwork != -1) {
1721 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001722 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001723 }
1724
1725 private void sendStickyBroadcast(Intent intent) {
1726 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001727 if (!mSystemReady) {
1728 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001729 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001730 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001731 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001732 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001733 }
1734
Dianne Hackborna417ff82009-12-08 19:45:14 -08001735 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001736 }
1737 }
1738
Wink Saville4f0de1e2011-08-04 15:01:58 -07001739 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1740 if (delayMs <= 0) {
1741 sendStickyBroadcast(intent);
1742 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001743 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001744 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1745 + intent.getAction());
1746 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001747 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1748 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1749 }
1750 }
1751
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001752 void systemReady() {
1753 synchronized(this) {
1754 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001755 if (mInitialBroadcast != null) {
1756 mContext.sendStickyBroadcast(mInitialBroadcast);
1757 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001758 }
1759 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001760 // load the global proxy at startup
1761 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001762 }
1763
1764 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001765 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001766
1767 // snapshot isFailover, because sendConnectedBroadcast() resets it
1768 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001769 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001770
Robert Greenwalt2034b912009-08-12 16:08:25 -07001771 // if this is a default net and other default is running
1772 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001773 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001774 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1775 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001776 mNetConfigs[mActiveDefaultNetwork].priority >
1777 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001778 mNetworkPreference == mActiveDefaultNetwork) {
1779 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001780 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001781 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001782 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001783 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001784 teardown(thisNet);
1785 return;
1786 } else {
1787 // tear down the other
1788 NetworkStateTracker otherNet =
1789 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001790 if (DBG) {
1791 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001792 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001793 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001794 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001795 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001796 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001797 return;
1798 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001799 }
1800 }
1801 synchronized (ConnectivityService.this) {
1802 // have a new default network, release the transition wakelock in a second
1803 // if it's held. The second pause is to allow apps to reconnect over the
1804 // new network
1805 if (mNetTransitionWakeLock.isHeld()) {
1806 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001807 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001808 mNetTransitionWakeLockSerialNumber, 0),
1809 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001810 }
1811 }
1812 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001813 // this will cause us to come up initially as unconnected and switching
1814 // to connected after our normal pause unless somebody reports us as reall
1815 // disconnected
1816 mDefaultInetConditionPublished = 0;
1817 mDefaultConnectionSequence++;
1818 mInetConditionChangeInFlight = false;
1819 // Don't do this - if we never sign in stay, grey
1820 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001821 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001822 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001823 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001824 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001825 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001826
1827 // notify battery stats service about this network
1828 final String iface = thisNet.getLinkProperties().getInterfaceName();
1829 if (iface != null) {
1830 try {
1831 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1832 } catch (RemoteException e) {
1833 // ignored; service lives in system_server
1834 }
1835 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001836 }
1837
The Android Open Source Project28527d22009-03-03 19:31:44 -08001838 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001839 * After a change in the connectivity state of a network. We're mainly
1840 * concerned with making sure that the list of DNS servers is set up
1841 * according to which networks are connected, and ensuring that the
1842 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001843 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001844 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001845 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1846
The Android Open Source Project28527d22009-03-03 19:31:44 -08001847 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001848 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001849 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001850 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001851 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001852
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001853 LinkProperties curLp = mCurrentLinkProperties[netType];
1854 LinkProperties newLp = null;
1855
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001856 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001857 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001858 if (VDBG) {
1859 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1860 " doReset=" + doReset + " resetMask=" + resetMask +
1861 "\n curLp=" + curLp +
1862 "\n newLp=" + newLp);
1863 }
1864
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001865 if (curLp != null) {
1866 if (curLp.isIdenticalInterfaceName(newLp)) {
1867 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1868 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1869 for (LinkAddress linkAddr : car.removed) {
1870 if (linkAddr.getAddress() instanceof Inet4Address) {
1871 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1872 }
1873 if (linkAddr.getAddress() instanceof Inet6Address) {
1874 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1875 }
Wink Saville051a6642011-07-13 13:44:13 -07001876 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001877 if (DBG) {
1878 log("handleConnectivityChange: addresses changed" +
1879 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1880 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001881 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001882 } else {
1883 if (DBG) {
1884 log("handleConnectivityChange: address are the same reset per doReset" +
1885 " linkProperty[" + netType + "]:" +
1886 " resetMask=" + resetMask);
1887 }
Wink Saville051a6642011-07-13 13:44:13 -07001888 }
1889 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001890 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001891 if (DBG) {
1892 log("handleConnectivityChange: interface not not equivalent reset both" +
1893 " linkProperty[" + netType + "]:" +
1894 " resetMask=" + resetMask);
1895 }
Wink Saville051a6642011-07-13 13:44:13 -07001896 }
Wink Saville051a6642011-07-13 13:44:13 -07001897 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001898 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07001899 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001900 }
1901 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001902 if (VDBG) {
1903 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1904 " doReset=" + doReset + " resetMask=" + resetMask +
1905 "\n curLp=" + curLp +
1906 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001907 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001909 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001910 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001911
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001912 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001913 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1914 if (linkProperties != null) {
1915 String iface = linkProperties.getInterfaceName();
1916 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001917 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001918 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1919 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001920
1921 // Tell VPN the interface is down. It is a temporary
1922 // but effective fix to make VPN aware of the change.
1923 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1924 mVpn.interfaceStatusChanged(iface, false);
1925 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001926 }
1927 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07001928 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001929 try {
1930 mNetd.flushInterfaceDnsCache(iface);
1931 } catch (Exception e) {
1932 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001933 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001934 }
1935 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001936 }
1937 }
1938 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001939
1940 // TODO: Temporary notifying upstread change to Tethering.
1941 // @see bug/4455071
1942 /** Notify TetheringService if interface name has been changed. */
1943 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1944 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1945 if (isTetheringSupported()) {
1946 mTethering.handleTetherIfaceChange();
1947 }
1948 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001949 }
1950
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001951 /**
1952 * Add and remove routes using the old properties (null if not previously connected),
1953 * new properties (null if becoming disconnected). May even be double null, which
1954 * is a noop.
1955 * Uses isLinkDefault to determine if default routes should be set or conversely if
1956 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001957 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001958 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07001959 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1960 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001961 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001962 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1963 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001964 if (curLp != null) {
1965 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001966 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001967 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001968 } else if (newLp != null) {
1969 routeDiff.added = newLp.getRoutes();
1970 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001971 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001972
Robert Greenwalt8d777252011-08-15 12:31:55 -07001973 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1974
Robert Greenwalt98107422011-07-22 11:55:33 -07001975 for (RouteInfo r : routeDiff.removed) {
1976 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001977 removeRoute(curLp, r, TO_DEFAULT_TABLE);
1978 }
1979 if (isLinkDefault == false) {
1980 // remove from a secondary route table
1981 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001982 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001983 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001984
Robert Greenwalt98107422011-07-22 11:55:33 -07001985 for (RouteInfo r : routeDiff.added) {
1986 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001987 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001988 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001989 // add to a secondary route table
1990 addRoute(newLp, r, TO_SECONDARY_TABLE);
1991
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001992 // many radios add a default route even when we don't want one.
1993 // remove the default route unless somebody else has asked for it
1994 String ifaceName = newLp.getInterfaceName();
1995 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07001996 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001997 try {
1998 mNetd.removeRoute(ifaceName, r);
1999 } catch (Exception e) {
2000 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07002001 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002002 }
2003 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002004 }
2005 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002006
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002007 if (!isLinkDefault) {
2008 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002009 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002010 // routes changed - remove all old dns entries and add new
2011 if (curLp != null) {
2012 for (InetAddress oldDns : curLp.getDnses()) {
2013 removeRouteToAddress(curLp, oldDns);
2014 }
2015 }
2016 if (newLp != null) {
2017 for (InetAddress newDns : newLp.getDnses()) {
2018 addRouteToAddress(newLp, newDns);
2019 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002020 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002021 } else {
2022 // no change in routes, check for change in dns themselves
2023 for (InetAddress oldDns : dnsDiff.removed) {
2024 removeRouteToAddress(curLp, oldDns);
2025 }
2026 for (InetAddress newDns : dnsDiff.added) {
2027 addRouteToAddress(newLp, newDns);
2028 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002029 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002030 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002031 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002032 }
2033
2034
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002035 /**
2036 * Reads the network specific TCP buffer sizes from SystemProperties
2037 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2038 * wide use
2039 */
2040 public void updateNetworkSettings(NetworkStateTracker nt) {
2041 String key = nt.getTcpBufferSizesPropName();
2042 String bufferSizes = SystemProperties.get(key);
2043
2044 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002045 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002046
2047 // Setting to default values so we won't be stuck to previous values
2048 key = "net.tcp.buffersize.default";
2049 bufferSizes = SystemProperties.get(key);
2050 }
2051
2052 // Set values in kernel
2053 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002054 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002055 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002056 + "] which comes from [" + key + "]");
2057 }
2058 setBufferSize(bufferSizes);
2059 }
2060 }
2061
2062 /**
2063 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2064 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2065 *
2066 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2067 * writeMin, writeInitial, writeMax"
2068 */
2069 private void setBufferSize(String bufferSizes) {
2070 try {
2071 String[] values = bufferSizes.split(",");
2072
2073 if (values.length == 6) {
2074 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002075 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2076 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2077 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2078 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2079 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2080 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002081 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002082 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002083 }
2084 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002085 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002086 }
2087 }
2088
Robert Greenwalt2034b912009-08-12 16:08:25 -07002089 /**
2090 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2091 * on the highest priority active net which this process requested.
2092 * If there aren't any, clear it out
2093 */
2094 private void reassessPidDns(int myPid, boolean doBump)
2095 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002096 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002097 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002098 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002099 continue;
2100 }
2101 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002102 if (nt.getNetworkInfo().isConnected() &&
2103 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002104 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002105 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002106 List pids = mNetRequestersPids[i];
2107 for (int j=0; j<pids.size(); j++) {
2108 Integer pid = (Integer)pids.get(j);
2109 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002110 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002111 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002112 if (doBump) {
2113 bumpDns();
2114 }
2115 return;
2116 }
2117 }
2118 }
2119 }
2120 // nothing found - delete
2121 for (int i = 1; ; i++) {
2122 String prop = "net.dns" + i + "." + myPid;
2123 if (SystemProperties.get(prop).length() == 0) {
2124 if (doBump) {
2125 bumpDns();
2126 }
2127 return;
2128 }
2129 SystemProperties.set(prop, "");
2130 }
2131 }
2132
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002133 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002134 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002135 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002136 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002137 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002138 String dnsString = dns.getHostAddress();
2139 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2140 changed = true;
2141 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2142 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002143 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002144 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002145 }
2146
2147 private void bumpDns() {
2148 /*
2149 * Bump the property that tells the name resolver library to reread
2150 * the DNS server list from the properties.
2151 */
2152 String propVal = SystemProperties.get("net.dnschange");
2153 int n = 0;
2154 if (propVal.length() != 0) {
2155 try {
2156 n = Integer.parseInt(propVal);
2157 } catch (NumberFormatException e) {}
2158 }
2159 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002160 /*
2161 * Tell the VMs to toss their DNS caches
2162 */
2163 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2164 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002165 /*
2166 * Connectivity events can happen before boot has completed ...
2167 */
2168 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002169 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002170 }
2171
Chia-chi Yehcc844502011-07-14 18:01:57 -07002172 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002173 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002174 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002175 boolean changed = false;
2176 int last = 0;
2177 if (dnses.size() == 0 && mDefaultDns != null) {
2178 ++last;
2179 String value = mDefaultDns.getHostAddress();
2180 if (!value.equals(SystemProperties.get("net.dns1"))) {
2181 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002182 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002183 }
2184 changed = true;
2185 SystemProperties.set("net.dns1", value);
2186 }
2187 } else {
2188 for (InetAddress dns : dnses) {
2189 ++last;
2190 String key = "net.dns" + last;
2191 String value = dns.getHostAddress();
2192 if (!changed && value.equals(SystemProperties.get(key))) {
2193 continue;
2194 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002195 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002196 log("adding dns " + value + " for " + network);
2197 }
2198 changed = true;
2199 SystemProperties.set(key, value);
2200 }
2201 }
2202 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2203 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002204 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002205 changed = true;
2206 SystemProperties.set(key, "");
2207 }
2208 mNumDnsEntries = last;
2209
Robert Greenwaltfce71862011-07-25 16:06:25 -07002210 if (changed) {
2211 try {
2212 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2213 mNetd.setDefaultInterfaceForDns(iface);
2214 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002215 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002216 }
2217 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002218 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2219 SystemProperties.set("net.dns.search", domains);
2220 changed = true;
2221 }
2222 return changed;
2223 }
2224
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002225 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002226 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002227 NetworkStateTracker nt = mNetTrackers[netType];
2228 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002229 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002230 if (p == null) return;
2231 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002232 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002233 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002234 String network = nt.getNetworkInfo().getTypeName();
2235 synchronized (mDnsLock) {
2236 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002237 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002238 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002239 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002240 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002241 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002242 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002243 NetworkUtils.makeStrings(dnses));
2244 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002245 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002246 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002247 // set per-pid dns for attached secondary nets
2248 List pids = mNetRequestersPids[netType];
2249 for (int y=0; y< pids.size(); y++) {
2250 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002251 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 }
2253 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002254 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002256 }
2257
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002258 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002259 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2260 NETWORK_RESTORE_DELAY_PROP_NAME);
2261 if(restoreDefaultNetworkDelayStr != null &&
2262 restoreDefaultNetworkDelayStr.length() != 0) {
2263 try {
2264 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2265 } catch (NumberFormatException e) {
2266 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002267 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002268 // if the system property isn't set, use the value for the apn type
2269 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2270
2271 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2272 (mNetConfigs[networkType] != null)) {
2273 ret = mNetConfigs[networkType].restoreTime;
2274 }
2275 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002276 }
2277
2278 @Override
2279 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002280 if (mContext.checkCallingOrSelfPermission(
2281 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002282 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002283 pw.println("Permission Denial: can't dump ConnectivityService " +
2284 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2285 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002286 return;
2287 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002288 pw.println();
2289 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002290 if (nst != null) {
2291 if (nst.getNetworkInfo().isConnected()) {
2292 pw.println("Active network: " + nst.getNetworkInfo().
2293 getTypeName());
2294 }
2295 pw.println(nst.getNetworkInfo());
2296 pw.println(nst);
2297 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002298 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002300
2301 pw.println("Network Requester Pids:");
2302 for (int net : mPriorityList) {
2303 String pidString = net + ": ";
2304 for (Object pid : mNetRequestersPids[net]) {
2305 pidString = pidString + pid.toString() + ", ";
2306 }
2307 pw.println(pidString);
2308 }
2309 pw.println();
2310
2311 pw.println("FeatureUsers:");
2312 for (Object requester : mFeatureUsers) {
2313 pw.println(requester.toString());
2314 }
2315 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002316
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002317 synchronized (this) {
2318 pw.println("NetworkTranstionWakeLock is currently " +
2319 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2320 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2321 }
2322 pw.println();
2323
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002324 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002325
2326 if (mInetLog != null) {
2327 pw.println();
2328 pw.println("Inet condition reports:");
2329 for(int i = 0; i < mInetLog.size(); i++) {
2330 pw.println(mInetLog.get(i));
2331 }
2332 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002333 }
2334
Robert Greenwalt2034b912009-08-12 16:08:25 -07002335 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002336 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002337 public MyHandler(Looper looper) {
2338 super(looper);
2339 }
2340
The Android Open Source Project28527d22009-03-03 19:31:44 -08002341 @Override
2342 public void handleMessage(Message msg) {
2343 NetworkInfo info;
2344 switch (msg.what) {
2345 case NetworkStateTracker.EVENT_STATE_CHANGED:
2346 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002347 int type = info.getType();
2348 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002349
Wink Savillea7d56572011-09-21 11:05:43 -07002350 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2351 (state == NetworkInfo.State.DISCONNECTED)) {
2352 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002353 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002354 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002355 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002356
2357 // Connectivity state changed:
2358 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002359 // [12-9] Network subtype (for mobile network, as defined
2360 // by TelephonyManager)
2361 // [8-3] Detailed state ordinal (as defined by
2362 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002363 // [2-0] Network type (as defined by ConnectivityManager)
2364 int eventLogParam = (info.getType() & 0x7) |
2365 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2366 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002367 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002368 eventLogParam);
2369
2370 if (info.getDetailedState() ==
2371 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002372 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002373 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002374 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002375 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002376 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002377 // the logic here is, handle SUSPENDED the same as
2378 // DISCONNECTED. The only difference being we are
2379 // broadcasting an intent with NetworkInfo that's
2380 // suspended. This allows the applications an
2381 // opportunity to handle DISCONNECTED and SUSPENDED
2382 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002383 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002384 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002385 handleConnect(info);
2386 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002387 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002388 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002389 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002390 // TODO: Temporary allowing network configuration
2391 // change not resetting sockets.
2392 // @see bug/4455071
2393 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002394 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002395 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002396 String causedBy = null;
2397 synchronized (ConnectivityService.this) {
2398 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2399 mNetTransitionWakeLock.isHeld()) {
2400 mNetTransitionWakeLock.release();
2401 causedBy = mNetTransitionWakeLockCausedBy;
2402 }
2403 }
2404 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002405 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002406 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002407 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002408 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002409 FeatureUser u = (FeatureUser)msg.obj;
2410 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002411 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002412 case EVENT_INET_CONDITION_CHANGE:
2413 {
2414 int netType = msg.arg1;
2415 int condition = msg.arg2;
2416 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002417 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002418 }
2419 case EVENT_INET_CONDITION_HOLD_END:
2420 {
2421 int netType = msg.arg1;
2422 int sequence = msg.arg2;
2423 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002424 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002425 }
2426 case EVENT_SET_NETWORK_PREFERENCE:
2427 {
2428 int preference = msg.arg1;
2429 handleSetNetworkPreference(preference);
2430 break;
2431 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002432 case EVENT_SET_MOBILE_DATA:
2433 {
2434 boolean enabled = (msg.arg1 == ENABLED);
2435 handleSetMobileData(enabled);
2436 break;
2437 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002438 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2439 {
2440 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002441 break;
2442 }
2443 case EVENT_SET_DEPENDENCY_MET:
2444 {
2445 boolean met = (msg.arg1 == ENABLED);
2446 handleSetDependencyMet(msg.arg2, met);
2447 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002448 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002449 case EVENT_RESTORE_DNS:
2450 {
2451 if (mActiveDefaultNetwork != -1) {
2452 handleDnsConfigurationChange(mActiveDefaultNetwork);
2453 }
2454 break;
2455 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002456 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2457 {
2458 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002459 sendStickyBroadcast(intent);
2460 break;
2461 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002462 case EVENT_SET_POLICY_DATA_ENABLE: {
2463 final int networkType = msg.arg1;
2464 final boolean enabled = msg.arg2 == ENABLED;
2465 handleSetPolicyDataEnable(networkType, enabled);
2466 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002467 }
2468 }
2469 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002470
2471 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002472 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002473 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002474
2475 if (isTetheringSupported()) {
2476 return mTethering.tether(iface);
2477 } else {
2478 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2479 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002480 }
2481
2482 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002483 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002484 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002485
2486 if (isTetheringSupported()) {
2487 return mTethering.untether(iface);
2488 } else {
2489 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2490 }
2491 }
2492
2493 // javadoc from interface
2494 public int getLastTetherError(String iface) {
2495 enforceTetherAccessPermission();
2496
2497 if (isTetheringSupported()) {
2498 return mTethering.getLastTetherError(iface);
2499 } else {
2500 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2501 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002502 }
2503
2504 // TODO - proper iface API for selection by property, inspection, etc
2505 public String[] getTetherableUsbRegexs() {
2506 enforceTetherAccessPermission();
2507 if (isTetheringSupported()) {
2508 return mTethering.getTetherableUsbRegexs();
2509 } else {
2510 return new String[0];
2511 }
2512 }
2513
2514 public String[] getTetherableWifiRegexs() {
2515 enforceTetherAccessPermission();
2516 if (isTetheringSupported()) {
2517 return mTethering.getTetherableWifiRegexs();
2518 } else {
2519 return new String[0];
2520 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002521 }
2522
Danica Chang96567052010-08-11 14:54:43 -07002523 public String[] getTetherableBluetoothRegexs() {
2524 enforceTetherAccessPermission();
2525 if (isTetheringSupported()) {
2526 return mTethering.getTetherableBluetoothRegexs();
2527 } else {
2528 return new String[0];
2529 }
2530 }
2531
Mike Lockwooded4a1742011-07-19 13:04:47 -07002532 public int setUsbTethering(boolean enable) {
2533 enforceTetherAccessPermission();
2534 if (isTetheringSupported()) {
2535 return mTethering.setUsbTethering(enable);
2536 } else {
2537 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2538 }
2539 }
2540
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002541 // TODO - move iface listing, queries, etc to new module
2542 // javadoc from interface
2543 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002544 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002545 return mTethering.getTetherableIfaces();
2546 }
2547
2548 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002549 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002550 return mTethering.getTetheredIfaces();
2551 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002552
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002553 @Override
2554 public String[] getTetheredIfacePairs() {
2555 enforceTetherAccessPermission();
2556 return mTethering.getTetheredIfacePairs();
2557 }
2558
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002559 public String[] getTetheringErroredIfaces() {
2560 enforceTetherAccessPermission();
2561 return mTethering.getErroredIfaces();
2562 }
2563
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002564 // if ro.tether.denied = true we default to no tethering
2565 // gservices could set the secure setting to 1 though to enable it on a build where it
2566 // had previously been turned off.
2567 public boolean isTetheringSupported() {
2568 enforceTetherAccessPermission();
2569 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002570 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2571 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2572 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002573 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002574
2575 // An API NetworkStateTrackers can call when they lose their network.
2576 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2577 // whichever happens first. The timer is started by the first caller and not
2578 // restarted by subsequent callers.
2579 public void requestNetworkTransitionWakelock(String forWhom) {
2580 enforceConnectivityInternalPermission();
2581 synchronized (this) {
2582 if (mNetTransitionWakeLock.isHeld()) return;
2583 mNetTransitionWakeLockSerialNumber++;
2584 mNetTransitionWakeLock.acquire();
2585 mNetTransitionWakeLockCausedBy = forWhom;
2586 }
2587 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002588 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002589 mNetTransitionWakeLockSerialNumber, 0),
2590 mNetTransitionWakeLockTimeout);
2591 return;
2592 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002593
Robert Greenwalt986c7412010-09-08 15:24:47 -07002594 // 100 percent is full good, 0 is full bad.
2595 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002596 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002597 mContext.enforceCallingOrSelfPermission(
2598 android.Manifest.permission.STATUS_BAR,
2599 "ConnectivityService");
2600
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002601 if (DBG) {
2602 int pid = getCallingPid();
2603 int uid = getCallingUid();
2604 String s = pid + "(" + uid + ") reports inet is " +
2605 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2606 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2607 mInetLog.add(s);
2608 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2609 mInetLog.remove(0);
2610 }
2611 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002612 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002613 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2614 }
2615
2616 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002617 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002618 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002619 return;
2620 }
2621 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002622 if (DBG) log("handleInetConditionChange: net=" + netType +
2623 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002624 return;
2625 }
Wink Savillea7d56572011-09-21 11:05:43 -07002626 if (VDBG) {
2627 log("handleInetConditionChange: net=" +
2628 netType + ", condition=" + condition +
2629 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2630 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002631 mDefaultInetCondition = condition;
2632 int delay;
2633 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002634 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002635 // setup a new hold to debounce this
2636 if (mDefaultInetCondition > 50) {
2637 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2638 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2639 } else {
2640 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2641 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2642 }
2643 mInetConditionChangeInFlight = true;
2644 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2645 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2646 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002647 // we've set the new condition, when this hold ends that will get picked up
2648 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002649 }
2650 }
2651
2652 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002653 if (DBG) {
2654 log("handleInetConditionHoldEnd: net=" + netType +
2655 ", condition=" + mDefaultInetCondition +
2656 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002657 }
2658 mInetConditionChangeInFlight = false;
2659
2660 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002661 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002662 return;
2663 }
2664 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002665 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002666 return;
2667 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002668 // TODO: Figure out why this optimization sometimes causes a
2669 // change in mDefaultInetCondition to be missed and the
2670 // UI to not be updated.
2671 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2672 // if (DBG) log("no change in condition - aborting");
2673 // return;
2674 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002675 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2676 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002677 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002678 return;
2679 }
2680 mDefaultInetConditionPublished = mDefaultInetCondition;
2681 sendInetConditionBroadcast(networkInfo);
2682 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002683 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002684
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002685 public ProxyProperties getProxy() {
2686 synchronized (mDefaultProxyLock) {
2687 return mDefaultProxyDisabled ? null : mDefaultProxy;
2688 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002689 }
2690
2691 public void setGlobalProxy(ProxyProperties proxyProperties) {
2692 enforceChangePermission();
2693 synchronized (mGlobalProxyLock) {
2694 if (proxyProperties == mGlobalProxy) return;
2695 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2696 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2697
2698 String host = "";
2699 int port = 0;
2700 String exclList = "";
2701 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2702 mGlobalProxy = new ProxyProperties(proxyProperties);
2703 host = mGlobalProxy.getHost();
2704 port = mGlobalProxy.getPort();
2705 exclList = mGlobalProxy.getExclusionList();
2706 } else {
2707 mGlobalProxy = null;
2708 }
2709 ContentResolver res = mContext.getContentResolver();
2710 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2711 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002712 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002713 exclList);
2714 }
2715
2716 if (mGlobalProxy == null) {
2717 proxyProperties = mDefaultProxy;
2718 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002719 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002720 }
2721
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002722 private void loadGlobalProxy() {
2723 ContentResolver res = mContext.getContentResolver();
2724 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2725 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2726 String exclList = Settings.Secure.getString(res,
2727 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2728 if (!TextUtils.isEmpty(host)) {
2729 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2730 synchronized (mGlobalProxyLock) {
2731 mGlobalProxy = proxyProperties;
2732 }
2733 }
2734 }
2735
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002736 public ProxyProperties getGlobalProxy() {
2737 synchronized (mGlobalProxyLock) {
2738 return mGlobalProxy;
2739 }
2740 }
2741
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002742 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2743 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2744 proxy = null;
2745 }
2746 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002747 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2748 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002749 mDefaultProxy = proxy;
2750
2751 if (!mDefaultProxyDisabled) {
2752 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002753 }
2754 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002755 }
2756
2757 private void handleDeprecatedGlobalHttpProxy() {
2758 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2759 Settings.Secure.HTTP_PROXY);
2760 if (!TextUtils.isEmpty(proxy)) {
2761 String data[] = proxy.split(":");
2762 String proxyHost = data[0];
2763 int proxyPort = 8080;
2764 if (data.length > 1) {
2765 try {
2766 proxyPort = Integer.parseInt(data[1]);
2767 } catch (NumberFormatException e) {
2768 return;
2769 }
2770 }
2771 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2772 setGlobalProxy(p);
2773 }
2774 }
2775
2776 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002777 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002778 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002779 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002780 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2781 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002782 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002783 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002784 }
2785
2786 private static class SettingsObserver extends ContentObserver {
2787 private int mWhat;
2788 private Handler mHandler;
2789 SettingsObserver(Handler handler, int what) {
2790 super(handler);
2791 mHandler = handler;
2792 mWhat = what;
2793 }
2794
2795 void observe(Context context) {
2796 ContentResolver resolver = context.getContentResolver();
2797 resolver.registerContentObserver(Settings.Secure.getUriFor(
2798 Settings.Secure.HTTP_PROXY), false, this);
2799 }
2800
2801 @Override
2802 public void onChange(boolean selfChange) {
2803 mHandler.obtainMessage(mWhat).sendToTarget();
2804 }
2805 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002806
2807 private void log(String s) {
2808 Slog.d(TAG, s);
2809 }
2810
2811 private void loge(String s) {
2812 Slog.e(TAG, s);
2813 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002814
repo syncf5de5572011-07-29 23:55:49 -07002815 int convertFeatureToNetworkType(int networkType, String feature) {
2816 int usedNetworkType = networkType;
2817
2818 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2819 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2820 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2821 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2822 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2823 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2824 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2825 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2826 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2827 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2828 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2829 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2830 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2831 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2832 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2833 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2834 } else {
2835 Slog.e(TAG, "Can't match any mobile netTracker!");
2836 }
2837 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2838 if (TextUtils.equals(feature, "p2p")) {
2839 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2840 } else {
2841 Slog.e(TAG, "Can't match any wifi netTracker!");
2842 }
2843 } else {
2844 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002845 }
repo syncf5de5572011-07-29 23:55:49 -07002846 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002847 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002848
2849 private static <T> T checkNotNull(T value, String message) {
2850 if (value == null) {
2851 throw new NullPointerException(message);
2852 }
2853 return value;
2854 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002855
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002856 /**
2857 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002858 * VpnBuilder and not available in ConnectivityManager. Permissions
2859 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002860 * @hide
2861 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002862 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002863 public boolean protectVpn(ParcelFileDescriptor socket) {
2864 try {
2865 int type = mActiveDefaultNetwork;
2866 if (ConnectivityManager.isNetworkTypeValid(type)) {
2867 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2868 return true;
2869 }
2870 } catch (Exception e) {
2871 // ignore
2872 } finally {
2873 try {
2874 socket.close();
2875 } catch (Exception e) {
2876 // ignore
2877 }
2878 }
2879 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002880 }
2881
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002882 /**
2883 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002884 * and not available in ConnectivityManager. Permissions are checked
2885 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002886 * @hide
2887 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002888 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002889 public boolean prepareVpn(String oldPackage, String newPackage) {
2890 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002891 }
2892
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002893 /**
2894 * Configure a TUN interface and return its file descriptor. Parameters
2895 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002896 * and not available in ConnectivityManager. Permissions are checked in
2897 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002898 * @hide
2899 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002900 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002901 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002902 return mVpn.establish(config);
2903 }
2904
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002905 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002906 * Start legacy VPN and return an intent to VpnDialogs. This method is
2907 * used by VpnSettings and not available in ConnectivityManager.
2908 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002909 * @hide
2910 */
2911 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002912 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2913 mVpn.startLegacyVpn(config, racoon, mtpd);
2914 }
2915
2916 /**
2917 * Return the information of the ongoing legacy VPN. This method is used
2918 * by VpnSettings and not available in ConnectivityManager. Permissions
2919 * are checked in Vpn class.
2920 * @hide
2921 */
2922 @Override
2923 public LegacyVpnInfo getLegacyVpnInfo() {
2924 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002925 }
2926
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002927 /**
2928 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2929 * through NetworkStateTracker since it works differently. For example, it
2930 * needs to override DNS servers but never takes the default routes. It
2931 * relies on another data network, and it could keep existing connections
2932 * alive after reconnecting, switching between networks, or even resuming
2933 * from deep sleep. Calls from applications should be done synchronously
2934 * to avoid race conditions. As these are all hidden APIs, refactoring can
2935 * be done whenever a better abstraction is developed.
2936 */
2937 public class VpnCallback {
2938
2939 private VpnCallback() {
2940 }
2941
Chia-chi Yehcc844502011-07-14 18:01:57 -07002942 public void override(List<String> dnsServers, List<String> searchDomains) {
2943 if (dnsServers == null) {
2944 restore();
2945 return;
2946 }
2947
2948 // Convert DNS servers into addresses.
2949 List<InetAddress> addresses = new ArrayList<InetAddress>();
2950 for (String address : dnsServers) {
2951 // Double check the addresses and remove invalid ones.
2952 try {
2953 addresses.add(InetAddress.parseNumericAddress(address));
2954 } catch (Exception e) {
2955 // ignore
2956 }
2957 }
2958 if (addresses.isEmpty()) {
2959 restore();
2960 return;
2961 }
2962
2963 // Concatenate search domains into a string.
2964 StringBuilder buffer = new StringBuilder();
2965 if (searchDomains != null) {
2966 for (String domain : searchDomains) {
2967 buffer.append(domain).append(' ');
2968 }
2969 }
2970 String domains = buffer.toString().trim();
2971
2972 // Apply DNS changes.
2973 boolean changed = false;
2974 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002975 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002976 mDnsOverridden = true;
2977 }
2978 if (changed) {
2979 bumpDns();
2980 }
2981
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002982 // Temporarily disable the default proxy.
2983 synchronized (mDefaultProxyLock) {
2984 mDefaultProxyDisabled = true;
2985 if (mDefaultProxy != null) {
2986 sendProxyBroadcast(null);
2987 }
2988 }
2989
2990 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002991 }
2992
Chia-chi Yehcc844502011-07-14 18:01:57 -07002993 public void restore() {
2994 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002995 if (mDnsOverridden) {
2996 mDnsOverridden = false;
2997 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002998 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002999 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003000 synchronized (mDefaultProxyLock) {
3001 mDefaultProxyDisabled = false;
3002 if (mDefaultProxy != null) {
3003 sendProxyBroadcast(mDefaultProxy);
3004 }
3005 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003006 }
3007 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003008}