blob: 6e689c55667896dea6b565534b9d8366d671b5e7 [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();
503 if (mNetTrackers[netType != null) {
504 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 Greenwalt497ff5e72011-07-15 11:16:45 -0700517 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700518 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800519
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700520 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
521 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
522
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700523 mTethering = new Tethering(mContext, nmService, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700524 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700525 mTethering.getTetherableWifiRegexs().length != 0 ||
526 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700527 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800528
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700529 mVpn = new Vpn(mContext, new VpnCallback());
530
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700531 try {
532 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700533 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700534 } catch (RemoteException e) {
535 loge("Error registering observer :" + e);
536 }
537
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700538 if (DBG) {
539 mInetLog = new ArrayList();
540 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700541
542 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
543 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800544
545 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800546 }
tk.mun093f55c2011-10-13 22:51:57 +0900547private NetworkStateTracker makeWimaxStateTracker() {
548 //Initialize Wimax
549 DexClassLoader wimaxClassLoader;
550 Class wimaxStateTrackerClass = null;
551 Class wimaxServiceClass = null;
552 Class wimaxManagerClass;
553 String wimaxJarLocation;
554 String wimaxLibLocation;
555 String wimaxManagerClassName;
556 String wimaxServiceClassName;
557 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800558
tk.mun093f55c2011-10-13 22:51:57 +0900559 NetworkStateTracker wimaxStateTracker = null;
560
561 boolean isWimaxEnabled = mContext.getResources().getBoolean(
562 com.android.internal.R.bool.config_wimaxEnabled);
563
564 if (isWimaxEnabled) {
565 try {
566 wimaxJarLocation = mContext.getResources().getString(
567 com.android.internal.R.string.config_wimaxServiceJarLocation);
568 wimaxLibLocation = mContext.getResources().getString(
569 com.android.internal.R.string.config_wimaxNativeLibLocation);
570 wimaxManagerClassName = mContext.getResources().getString(
571 com.android.internal.R.string.config_wimaxManagerClassname);
572 wimaxServiceClassName = mContext.getResources().getString(
573 com.android.internal.R.string.config_wimaxServiceClassname);
574 wimaxStateTrackerClassName = mContext.getResources().getString(
575 com.android.internal.R.string.config_wimaxStateTrackerClassname);
576
577 log("wimaxJarLocation: " + wimaxJarLocation);
578 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
579 new ContextWrapper(mContext).getCacheDir().getAbsolutePath(),
580 wimaxLibLocation, ClassLoader.getSystemClassLoader());
581
582 try {
583 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
584 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
585 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
586 } catch (ClassNotFoundException ex) {
587 loge("Exception finding Wimax classes: " + ex.toString());
588 return null;
589 }
590 } catch(Resources.NotFoundException ex) {
591 loge("Wimax Resources does not exist!!! ");
592 return null;
593 }
594
595 try {
596 log("Starting Wimax Service... ");
597
598 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
599 (new Class[] {Context.class, Handler.class});
600 wimaxStateTracker = (NetworkStateTracker)wmxStTrkrConst.newInstance(mContext,
601 mHandler);
602
603 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
604 (new Class[] {Context.class, wimaxStateTrackerClass});
605 wmxSrvConst.setAccessible(true);
606 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(mContext, wimaxStateTracker);
607 wmxSrvConst.setAccessible(false);
608
609 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
610
611 } catch(Exception ex) {
612 loge("Exception creating Wimax classes: " + ex.toString());
613 return null;
614 }
615 } else {
616 loge("Wimax is not enabled or not added to the network attributes!!! ");
617 return null;
618 }
619
620 return wimaxStateTracker;
621 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800622 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700623 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800624 * @param preference the new preference
625 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700626 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800627 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700628
629 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800630 }
631
632 public int getNetworkPreference() {
633 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700634 int preference;
635 synchronized(this) {
636 preference = mNetworkPreference;
637 }
638 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800639 }
640
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700641 private void handleSetNetworkPreference(int preference) {
642 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700643 mNetConfigs[preference] != null &&
644 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700645 if (mNetworkPreference != preference) {
646 final ContentResolver cr = mContext.getContentResolver();
647 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
648 synchronized(this) {
649 mNetworkPreference = preference;
650 }
651 enforcePreference();
652 }
653 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800654 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700655
Wink Saville4f0de1e2011-08-04 15:01:58 -0700656 private int getConnectivityChangeDelay() {
657 final ContentResolver cr = mContext.getContentResolver();
658
659 /** Check system properties for the default value then use secure settings value, if any. */
660 int defaultDelay = SystemProperties.getInt(
661 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
662 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
663 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
664 defaultDelay);
665 }
666
The Android Open Source Project28527d22009-03-03 19:31:44 -0800667 private int getPersistedNetworkPreference() {
668 final ContentResolver cr = mContext.getContentResolver();
669
670 final int networkPrefSetting = Settings.Secure
671 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
672 if (networkPrefSetting != -1) {
673 return networkPrefSetting;
674 }
675
676 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
677 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700678
The Android Open Source Project28527d22009-03-03 19:31:44 -0800679 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700680 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800681 * In this method, we only tear down a non-preferred network. Establishing
682 * a connection to the preferred network is taken care of when we handle
683 * the disconnect event from the non-preferred network
684 * (see {@link #handleDisconnect(NetworkInfo)}).
685 */
686 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700687 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800688 return;
689
Robert Greenwalt2034b912009-08-12 16:08:25 -0700690 if (!mNetTrackers[mNetworkPreference].isAvailable())
691 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800692
Robert Greenwalt2034b912009-08-12 16:08:25 -0700693 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700694 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700695 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700696 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800697 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700698 " in enforcePreference");
699 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700700 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800701 }
702 }
703 }
704
705 private boolean teardown(NetworkStateTracker netTracker) {
706 if (netTracker.teardown()) {
707 netTracker.setTeardownRequested(true);
708 return true;
709 } else {
710 return false;
711 }
712 }
713
714 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700715 * Check if UID should be blocked from using the network represented by the
716 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700717 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700718 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
719 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700720
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700721 final boolean networkCostly;
722 final int uidRules;
723 synchronized (mRulesLock) {
724 networkCostly = mMeteredIfaces.contains(iface);
725 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700726 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700727
728 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
729 return true;
730 }
731
732 // no restrictive rules; network is visible
733 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700734 }
735
736 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700737 * Return a filtered {@link NetworkInfo}, potentially marked
738 * {@link DetailedState#BLOCKED} based on
739 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700740 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700741 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
742 NetworkInfo info = tracker.getNetworkInfo();
743 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700744 // network is blocked; clone and override state
745 info = new NetworkInfo(info);
746 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700747 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700748 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700749 }
750
751 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800752 * Return NetworkInfo for the active (i.e., connected) network interface.
753 * It is assumed that at most one network is active at a time. If more
754 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700755 * @return the info for the active network, or {@code null} if none is
756 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800757 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700758 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800759 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700760 enforceAccessPermission();
761 final int uid = Binder.getCallingUid();
762 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800763 }
764
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700765 @Override
766 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
767 enforceConnectivityInternalPermission();
768 return getNetworkInfo(mActiveDefaultNetwork, uid);
769 }
770
771 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800772 public NetworkInfo getNetworkInfo(int networkType) {
773 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700774 final int uid = Binder.getCallingUid();
775 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 }
777
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700778 private NetworkInfo getNetworkInfo(int networkType, int uid) {
779 NetworkInfo info = null;
780 if (isNetworkTypeValid(networkType)) {
781 final NetworkStateTracker tracker = mNetTrackers[networkType];
782 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700783 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700784 }
785 }
786 return info;
787 }
788
789 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800790 public NetworkInfo[] getAllNetworkInfo() {
791 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700792 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700793 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700794 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700795 for (NetworkStateTracker tracker : mNetTrackers) {
796 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700797 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700798 }
799 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700801 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800802 }
803
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700804 @Override
805 public boolean isNetworkSupported(int networkType) {
806 enforceAccessPermission();
807 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
808 }
809
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700810 /**
811 * Return LinkProperties for the active (i.e., connected) default
812 * network interface. It is assumed that at most one default network
813 * is active at a time. If more than one is active, it is indeterminate
814 * which will be returned.
815 * @return the ip properties for the active network, or {@code null} if
816 * none is active
817 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700818 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700819 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700820 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700821 }
822
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700823 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700824 public LinkProperties getLinkProperties(int networkType) {
825 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700826 if (isNetworkTypeValid(networkType)) {
827 final NetworkStateTracker tracker = mNetTrackers[networkType];
828 if (tracker != null) {
829 return tracker.getLinkProperties();
830 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700831 }
832 return null;
833 }
834
Jeff Sharkey21062e72011-05-28 20:56:34 -0700835 @Override
836 public NetworkState[] getAllNetworkState() {
837 enforceAccessPermission();
838 final int uid = Binder.getCallingUid();
839 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700840 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700841 for (NetworkStateTracker tracker : mNetTrackers) {
842 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700843 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700844 result.add(new NetworkState(
845 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
846 }
847 }
848 }
849 return result.toArray(new NetworkState[result.size()]);
850 }
851
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700852 private NetworkState getNetworkStateUnchecked(int networkType) {
853 if (isNetworkTypeValid(networkType)) {
854 final NetworkStateTracker tracker = mNetTrackers[networkType];
855 if (tracker != null) {
856 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
857 tracker.getLinkCapabilities());
858 }
859 }
860 return null;
861 }
862
863 @Override
864 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
865 enforceAccessPermission();
866 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
867 if (state != null) {
868 try {
869 return mPolicyManager.getNetworkQuotaInfo(state);
870 } catch (RemoteException e) {
871 }
872 }
873 return null;
874 }
875
The Android Open Source Project28527d22009-03-03 19:31:44 -0800876 public boolean setRadios(boolean turnOn) {
877 boolean result = true;
878 enforceChangePermission();
879 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700880 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881 }
882 return result;
883 }
884
885 public boolean setRadio(int netType, boolean turnOn) {
886 enforceChangePermission();
887 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
888 return false;
889 }
890 NetworkStateTracker tracker = mNetTrackers[netType];
891 return tracker != null && tracker.setRadio(turnOn);
892 }
893
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700894 /**
895 * Used to notice when the calling process dies so we can self-expire
896 *
897 * Also used to know if the process has cleaned up after itself when
898 * our auto-expire timer goes off. The timer has a link to an object.
899 *
900 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700901 private class FeatureUser implements IBinder.DeathRecipient {
902 int mNetworkType;
903 String mFeature;
904 IBinder mBinder;
905 int mPid;
906 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800907 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700908
909 FeatureUser(int type, String feature, IBinder binder) {
910 super();
911 mNetworkType = type;
912 mFeature = feature;
913 mBinder = binder;
914 mPid = getCallingPid();
915 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800916 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700917
Robert Greenwalt2034b912009-08-12 16:08:25 -0700918 try {
919 mBinder.linkToDeath(this, 0);
920 } catch (RemoteException e) {
921 binderDied();
922 }
923 }
924
925 void unlinkDeathRecipient() {
926 mBinder.unlinkToDeath(this, 0);
927 }
928
929 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800930 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800931 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
932 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700933 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700934 }
935
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700936 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -0700937 if (VDBG) {
938 log("ConnectivityService FeatureUser expire(" +
939 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
940 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
941 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700942 stopUsingNetworkFeature(this, false);
943 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800944
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500945 public boolean isSameUser(FeatureUser u) {
946 if (u == null) return false;
947
948 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
949 }
950
951 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
952 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
953 TextUtils.equals(mFeature, feature)) {
954 return true;
955 }
956 return false;
957 }
958
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800959 public String toString() {
960 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
961 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
962 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700963 }
964
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700965 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700966 public int startUsingNetworkFeature(int networkType, String feature,
967 IBinder binder) {
Wink Savillea7d56572011-09-21 11:05:43 -0700968 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800969 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700970 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800971 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700972 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700973 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700974 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800975 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700976
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700977 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700978
repo syncf5de5572011-07-29 23:55:49 -0700979 // TODO - move this into individual networktrackers
980 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700981
982 if (mProtectedNetworks.contains(usedNetworkType)) {
983 enforceConnectivityInternalPermission();
984 }
985
Robert Greenwalt2034b912009-08-12 16:08:25 -0700986 NetworkStateTracker network = mNetTrackers[usedNetworkType];
987 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800988 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700989 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700990 NetworkInfo ni = network.getNetworkInfo();
991
992 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800993 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800994 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
995 return Phone.APN_TYPE_NOT_AVAILABLE;
996 } else {
997 // else make the attempt anyway - probably giving REQUEST_STARTED below
998 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700999 }
1000
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001001 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1002
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001003 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001004 boolean addToList = true;
1005 if (restoreTimer < 0) {
1006 // In case there is no timer is specified for the feature,
1007 // make sure we don't add duplicate entry with the same request.
1008 for (FeatureUser u : mFeatureUsers) {
1009 if (u.isSameUser(f)) {
1010 // Duplicate user is found. Do not add.
1011 addToList = false;
1012 break;
1013 }
1014 }
1015 }
1016
1017 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001018 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1019 // this gets used for per-pid dns when connected
1020 mNetRequestersPids[usedNetworkType].add(currentPid);
1021 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001022 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001023
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001024 if (restoreTimer >= 0) {
1025 mHandler.sendMessageDelayed(
1026 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1027 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001028
Robert Greenwalta52c75a2009-08-19 20:19:33 -07001029 if ((ni.isConnectedOrConnecting() == true) &&
1030 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001031 if (ni.isConnected() == true) {
1032 // add the pid-specific dns
repo sync3035f652011-08-02 13:39:06 -07001033 handleDnsConfigurationChange(usedNetworkType);
Wink Savillea7d56572011-09-21 11:05:43 -07001034 if (VDBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001035 return Phone.APN_ALREADY_ACTIVE;
1036 }
Wink Savillea7d56572011-09-21 11:05:43 -07001037 if (VDBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001038 return Phone.APN_REQUEST_STARTED;
1039 }
1040
1041 // check if the radio in play can make another contact
1042 // assume if cannot for now
1043
Wink Savillea7d56572011-09-21 11:05:43 -07001044 if (DBG) {
1045 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1046 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001047 network.reconnect();
1048 return Phone.APN_REQUEST_STARTED;
1049 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -08001050 // need to remember this unsupported request so we respond appropriately on stop
1051 synchronized(this) {
1052 mFeatureUsers.add(f);
1053 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1054 // this gets used for per-pid dns when connected
1055 mNetRequestersPids[usedNetworkType].add(currentPid);
1056 }
1057 }
Robert Greenwaltd391e892010-05-18 10:52:51 -07001058 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001059 }
1060 }
1061 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001062 }
1063
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001064 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001065 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001066 enforceChangePermission();
1067
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001068 int pid = getCallingPid();
1069 int uid = getCallingUid();
1070
1071 FeatureUser u = null;
1072 boolean found = false;
1073
1074 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001075 for (FeatureUser x : mFeatureUsers) {
1076 if (x.isSameUser(pid, uid, networkType, feature)) {
1077 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001078 found = true;
1079 break;
1080 }
1081 }
1082 }
1083 if (found && u != null) {
1084 // stop regardless of how many other time this proc had called start
1085 return stopUsingNetworkFeature(u, true);
1086 } else {
1087 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001088 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001089 return 1;
1090 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001091 }
1092
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001093 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1094 int networkType = u.mNetworkType;
1095 String feature = u.mFeature;
1096 int pid = u.mPid;
1097 int uid = u.mUid;
1098
1099 NetworkStateTracker tracker = null;
1100 boolean callTeardown = false; // used to carry our decision outside of sync block
1101
Wink Savillea7d56572011-09-21 11:05:43 -07001102 if (VDBG) {
1103 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001104 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001105
The Android Open Source Project28527d22009-03-03 19:31:44 -08001106 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001107 if (DBG) {
1108 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1109 ", net is invalid");
1110 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001111 return -1;
1112 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001113
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001114 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1115 // sync block
1116 synchronized(this) {
1117 // check if this process still has an outstanding start request
1118 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001119 if (VDBG) {
1120 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1121 ", ignoring");
1122 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001123 return 1;
1124 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001125 u.unlinkDeathRecipient();
1126 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1127 // If we care about duplicate requests, check for that here.
1128 //
1129 // This is done to support the extension of a request - the app
1130 // can request we start the network feature again and renew the
1131 // auto-shutoff delay. Normal "stop" calls from the app though
1132 // do not pay attention to duplicate requests - in effect the
1133 // API does not refcount and a single stop will counter multiple starts.
1134 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001135 for (FeatureUser x : mFeatureUsers) {
1136 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001137 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001138 return 1;
1139 }
1140 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001141 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001142
repo syncf5de5572011-07-29 23:55:49 -07001143 // TODO - move to individual network trackers
1144 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1145
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001146 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001147 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001148 if (DBG) {
1149 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1150 " no known tracker for used net type " + usedNetworkType);
1151 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001152 return -1;
1153 }
1154 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001155 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001156 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001157 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001158 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001159 if (VDBG) {
1160 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1161 " others still using it");
1162 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001163 return 1;
1164 }
1165 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001166 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001167 if (DBG) {
1168 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1169 " not a known feature - dropping");
1170 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001171 }
1172 }
Wink Savillea7d56572011-09-21 11:05:43 -07001173
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001174 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001175 if (DBG) {
1176 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1177 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001178 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001179 return 1;
1180 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001181 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001182 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001183 }
1184
1185 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001186 * @deprecated use requestRouteToHostAddress instead
1187 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001188 * Ensure that a network route exists to deliver traffic to the specified
1189 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001190 * @param networkType the type of the network over which traffic to the
1191 * specified host is to be routed
1192 * @param hostAddress the IP address of the host to which the route is
1193 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001194 * @return {@code true} on success, {@code false} on failure
1195 */
1196 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001197 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1198
1199 if (inetAddress == null) {
1200 return false;
1201 }
1202
1203 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1204 }
1205
1206 /**
1207 * Ensure that a network route exists to deliver traffic to the specified
1208 * host via the specified network interface.
1209 * @param networkType the type of the network over which traffic to the
1210 * specified host is to be routed
1211 * @param hostAddress the IP address of the host to which the route is
1212 * desired
1213 * @return {@code true} on success, {@code false} on failure
1214 */
1215 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001216 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001217 if (mProtectedNetworks.contains(networkType)) {
1218 enforceConnectivityInternalPermission();
1219 }
1220
The Android Open Source Project28527d22009-03-03 19:31:44 -08001221 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1222 return false;
1223 }
1224 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001225
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001226 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1227 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001228 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001229 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001230 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001231 }
1232 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001233 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001234 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001235 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001236 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001237 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001238 } catch (UnknownHostException e) {}
1239 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001240 }
1241
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001242 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1243 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001244 }
1245
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001246 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1247 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001248 }
1249
Robert Greenwalt98107422011-07-22 11:55:33 -07001250 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001251 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001252 }
1253
1254 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001255 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001256 }
1257
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001258 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1259 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001260 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1261 if (bestRoute == null) {
1262 bestRoute = RouteInfo.makeHostRoute(addr);
1263 } else {
1264 if (bestRoute.getGateway().equals(addr)) {
1265 // if there is no better route, add the implied hostroute for our gateway
1266 bestRoute = RouteInfo.makeHostRoute(addr);
1267 } else {
1268 // if we will connect to this through another route, add a direct route
1269 // to it's gateway
1270 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1271 }
1272 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001273 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001274 }
1275
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001276 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001277 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001278 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1279
1280 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001281 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001282 return false;
1283 }
1284
1285 if (r.isHostRoute() == false) {
1286 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1287 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001288 if (bestRoute.getGateway().equals(r.getGateway())) {
1289 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001290 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001291 } else {
1292 // if we will connect to our gateway through another route, add a direct
1293 // route to it's gateway
1294 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001295 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001296 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001297 }
1298 }
1299 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001300 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001301 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001302 if (toDefaultTable) {
1303 mAddedRoutes.add(r); // only track default table - only one apps can effect
1304 mNetd.addRoute(ifaceName, r);
1305 } else {
1306 mNetd.addSecondaryRoute(ifaceName, r);
1307 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001308 } catch (Exception e) {
1309 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001310 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001311 return false;
1312 }
1313 } else {
1314 // if we remove this one and there are no more like it, then refcount==0 and
1315 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001316 if (toDefaultTable) {
1317 mAddedRoutes.remove(r);
1318 if (mAddedRoutes.contains(r) == false) {
1319 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1320 try {
1321 mNetd.removeRoute(ifaceName, r);
1322 } catch (Exception e) {
1323 // never crash - catch them all
1324 if (VDBG) loge("Exception trying to remove a route: " + e);
1325 return false;
1326 }
1327 } else {
1328 if (VDBG) log("not removing " + r + " as it's still in use");
1329 }
1330 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001331 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001332 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001333 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001334 } catch (Exception e) {
1335 // never crash - catch them all
Robert Greenwalt78f28112011-08-02 17:18:41 -07001336 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001337 return false;
1338 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001339 }
1340 }
1341 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001342 }
1343
1344 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001345 * @see ConnectivityManager#getMobileDataEnabled()
1346 */
1347 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001348 // TODO: This detail should probably be in DataConnectionTracker's
1349 // which is where we store the value and maybe make this
1350 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001351 enforceAccessPermission();
1352 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1353 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001354 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001355 return retVal;
1356 }
1357
Robert Greenwalt34848c02011-03-25 13:09:25 -07001358 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001359 enforceConnectivityInternalPermission();
1360
Robert Greenwalt34848c02011-03-25 13:09:25 -07001361 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1362 (met ? ENABLED : DISABLED), networkType));
1363 }
1364
1365 private void handleSetDependencyMet(int networkType, boolean met) {
1366 if (mNetTrackers[networkType] != null) {
1367 if (DBG) {
1368 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1369 }
1370 mNetTrackers[networkType].setDependencyMet(met);
1371 }
1372 }
1373
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001374 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1375 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001376 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001377 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001378 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001379
1380 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001381 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001382 }
1383
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001384 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001385 // skip update when we've already applied rules
1386 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1387 if (oldRules == uidRules) return;
1388
1389 mUidRules.put(uid, uidRules);
1390 }
1391
1392 // TODO: dispatch into NMS to push rules towards kernel module
1393 // TODO: notify UID when it has requested targeted updates
1394 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001395
1396 @Override
1397 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1398 // only someone like NPMS should only be calling us
1399 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1400
1401 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001402 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001403 }
1404
1405 synchronized (mRulesLock) {
1406 mMeteredIfaces.clear();
1407 for (String iface : meteredIfaces) {
1408 mMeteredIfaces.add(iface);
1409 }
1410 }
1411 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001412 };
1413
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001414 /**
1415 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1416 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001417 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001418 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001419 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001420
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001421 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001422 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001423 }
1424
1425 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001426 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001427 if (VDBG) {
1428 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001429 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001430 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1431 }
1432 }
1433
1434 @Override
1435 public void setPolicyDataEnable(int networkType, boolean enabled) {
1436 // only someone like NPMS should only be calling us
1437 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1438
1439 mHandler.sendMessage(mHandler.obtainMessage(
1440 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1441 }
1442
1443 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1444 if (isNetworkTypeValid(networkType)) {
1445 final NetworkStateTracker tracker = mNetTrackers[networkType];
1446 if (tracker != null) {
1447 tracker.setPolicyDataEnable(enabled);
1448 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001449 }
1450 }
1451
The Android Open Source Project28527d22009-03-03 19:31:44 -08001452 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001453 mContext.enforceCallingOrSelfPermission(
1454 android.Manifest.permission.ACCESS_NETWORK_STATE,
1455 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001456 }
1457
1458 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001459 mContext.enforceCallingOrSelfPermission(
1460 android.Manifest.permission.CHANGE_NETWORK_STATE,
1461 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001462 }
1463
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001464 // TODO Make this a special check when it goes public
1465 private void enforceTetherChangePermission() {
1466 mContext.enforceCallingOrSelfPermission(
1467 android.Manifest.permission.CHANGE_NETWORK_STATE,
1468 "ConnectivityService");
1469 }
1470
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001471 private void enforceTetherAccessPermission() {
1472 mContext.enforceCallingOrSelfPermission(
1473 android.Manifest.permission.ACCESS_NETWORK_STATE,
1474 "ConnectivityService");
1475 }
1476
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001477 private void enforceConnectivityInternalPermission() {
1478 mContext.enforceCallingOrSelfPermission(
1479 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1480 "ConnectivityService");
1481 }
1482
The Android Open Source Project28527d22009-03-03 19:31:44 -08001483 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001484 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1485 * network, we ignore it. If it is for the active network, we send out a
1486 * broadcast. But first, we check whether it might be possible to connect
1487 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001488 * @param info the {@code NetworkInfo} for the network
1489 */
1490 private void handleDisconnect(NetworkInfo info) {
1491
Robert Greenwalt2034b912009-08-12 16:08:25 -07001492 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001493
Robert Greenwalt2034b912009-08-12 16:08:25 -07001494 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001495 /*
1496 * If the disconnected network is not the active one, then don't report
1497 * this as a loss of connectivity. What probably happened is that we're
1498 * getting the disconnect for a network that we explicitly disabled
1499 * in accordance with network preference policies.
1500 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001501 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001502 List pids = mNetRequestersPids[prevNetType];
1503 for (int i = 0; i<pids.size(); i++) {
1504 Integer pid = (Integer)pids.get(i);
1505 // will remove them because the net's no longer connected
1506 // need to do this now as only now do we know the pids and
1507 // can properly null things that are no longer referenced.
1508 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001510 }
1511
The Android Open Source Project28527d22009-03-03 19:31:44 -08001512 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1513 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1514 if (info.isFailover()) {
1515 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1516 info.setFailover(false);
1517 }
1518 if (info.getReason() != null) {
1519 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1520 }
1521 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001522 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1523 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001524 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001525
Robert Greenwalt34848c02011-03-25 13:09:25 -07001526 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001527 tryFailover(prevNetType);
1528 if (mActiveDefaultNetwork != -1) {
1529 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001530 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1531 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001532 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001533 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1534 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001535 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001536 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001537
1538 // Reset interface if no other connections are using the same interface
1539 boolean doReset = true;
1540 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1541 if (linkProperties != null) {
1542 String oldIface = linkProperties.getInterfaceName();
1543 if (TextUtils.isEmpty(oldIface) == false) {
1544 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1545 if (networkStateTracker == null) continue;
1546 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1547 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1548 LinkProperties l = networkStateTracker.getLinkProperties();
1549 if (l == null) continue;
1550 if (oldIface.equals(l.getInterfaceName())) {
1551 doReset = false;
1552 break;
1553 }
1554 }
1555 }
1556 }
1557 }
1558
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001559 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001560 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001561
Jeff Sharkey971cd162011-08-29 16:02:57 -07001562 final Intent immediateIntent = new Intent(intent);
1563 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1564 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001565 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001566 /*
1567 * If the failover network is already connected, then immediately send
1568 * out a followup broadcast indicating successful failover
1569 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001570 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001571 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1572 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001573 }
1574 }
1575
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001576 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001577 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001578 * If this is a default network, check if other defaults are available.
1579 * Try to reconnect on all available and let them hash it out when
1580 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001581 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001582 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001583 if (mActiveDefaultNetwork == prevNetType) {
1584 mActiveDefaultNetwork = -1;
1585 }
1586
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001587 // don't signal a reconnect for anything lower or equal priority than our
1588 // current connected default
1589 // TODO - don't filter by priority now - nice optimization but risky
1590// int currentPriority = -1;
1591// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001592// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001593// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001594 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001595 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001596 if (mNetConfigs[checkType] == null) continue;
1597 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001598
1599// Enabling the isAvailable() optimization caused mobile to not get
1600// selected if it was in the middle of error handling. Specifically
1601// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1602// would not be available and we wouldn't get connected to anything.
1603// So removing the isAvailable() optimization below for now. TODO: This
1604// optimization should work and we need to investigate why it doesn't work.
1605// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1606// complete before it is really complete.
1607// if (!mNetTrackers[checkType].isAvailable()) continue;
1608
Robert Greenwalt34848c02011-03-25 13:09:25 -07001609// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001610
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001611 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1612 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1613 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1614 checkInfo.setFailover(true);
1615 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001616 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001617 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001618 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001619 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001620 }
1621
1622 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001623 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1624 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001625 }
1626
Wink Saville4f0de1e2011-08-04 15:01:58 -07001627 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001628 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1629 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001630 }
1631
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001632 private void sendInetConditionBroadcast(NetworkInfo info) {
1633 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1634 }
1635
Wink Saville4f0de1e2011-08-04 15:01:58 -07001636 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001637 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001638 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1639 if (info.isFailover()) {
1640 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1641 info.setFailover(false);
1642 }
1643 if (info.getReason() != null) {
1644 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1645 }
1646 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001647 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1648 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001649 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001650 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001651 return intent;
1652 }
1653
1654 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1655 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1656 }
1657
1658 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1659 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001660 }
1661
1662 /**
1663 * Called when an attempt to fail over to another network has failed.
1664 * @param info the {@link NetworkInfo} for the failed network
1665 */
1666 private void handleConnectionFailure(NetworkInfo info) {
1667 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001668
Robert Greenwalt2034b912009-08-12 16:08:25 -07001669 String reason = info.getReason();
1670 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001671
Robert Greenwalte981bc52010-10-08 16:35:52 -07001672 String reasonText;
1673 if (reason == null) {
1674 reasonText = ".";
1675 } else {
1676 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001677 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001678 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001679
1680 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1681 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1682 if (getActiveNetworkInfo() == null) {
1683 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1684 }
1685 if (reason != null) {
1686 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1687 }
1688 if (extraInfo != null) {
1689 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1690 }
1691 if (info.isFailover()) {
1692 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1693 info.setFailover(false);
1694 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001695
Robert Greenwalt34848c02011-03-25 13:09:25 -07001696 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001697 tryFailover(info.getType());
1698 if (mActiveDefaultNetwork != -1) {
1699 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001700 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1701 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001702 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001703 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1704 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001705 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001706
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001707 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001708
1709 final Intent immediateIntent = new Intent(intent);
1710 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1711 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001712 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001713 /*
1714 * If the failover network is already connected, then immediately send
1715 * out a followup broadcast indicating successful failover
1716 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001717 if (mActiveDefaultNetwork != -1) {
1718 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001719 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001720 }
1721
1722 private void sendStickyBroadcast(Intent intent) {
1723 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001724 if (!mSystemReady) {
1725 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001726 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001727 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001728 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001729 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001730 }
1731
Dianne Hackborna417ff82009-12-08 19:45:14 -08001732 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001733 }
1734 }
1735
Wink Saville4f0de1e2011-08-04 15:01:58 -07001736 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1737 if (delayMs <= 0) {
1738 sendStickyBroadcast(intent);
1739 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001740 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001741 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1742 + intent.getAction());
1743 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001744 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1745 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1746 }
1747 }
1748
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001749 void systemReady() {
1750 synchronized(this) {
1751 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001752 if (mInitialBroadcast != null) {
1753 mContext.sendStickyBroadcast(mInitialBroadcast);
1754 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001755 }
1756 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001757 // load the global proxy at startup
1758 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001759 }
1760
1761 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001762 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001763
1764 // snapshot isFailover, because sendConnectedBroadcast() resets it
1765 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001766 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001767
Robert Greenwalt2034b912009-08-12 16:08:25 -07001768 // if this is a default net and other default is running
1769 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001770 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001771 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1772 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001773 mNetConfigs[mActiveDefaultNetwork].priority >
1774 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001775 mNetworkPreference == mActiveDefaultNetwork) {
1776 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001777 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001778 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001779 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001780 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001781 teardown(thisNet);
1782 return;
1783 } else {
1784 // tear down the other
1785 NetworkStateTracker otherNet =
1786 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001787 if (DBG) {
1788 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001789 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001790 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001791 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001792 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001793 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001794 return;
1795 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001796 }
1797 }
1798 synchronized (ConnectivityService.this) {
1799 // have a new default network, release the transition wakelock in a second
1800 // if it's held. The second pause is to allow apps to reconnect over the
1801 // new network
1802 if (mNetTransitionWakeLock.isHeld()) {
1803 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001804 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001805 mNetTransitionWakeLockSerialNumber, 0),
1806 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001807 }
1808 }
1809 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001810 // this will cause us to come up initially as unconnected and switching
1811 // to connected after our normal pause unless somebody reports us as reall
1812 // disconnected
1813 mDefaultInetConditionPublished = 0;
1814 mDefaultConnectionSequence++;
1815 mInetConditionChangeInFlight = false;
1816 // Don't do this - if we never sign in stay, grey
1817 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001818 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001819 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001820 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001821 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001822 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001823
1824 // notify battery stats service about this network
1825 final String iface = thisNet.getLinkProperties().getInterfaceName();
1826 if (iface != null) {
1827 try {
1828 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1829 } catch (RemoteException e) {
1830 // ignored; service lives in system_server
1831 }
1832 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001833 }
1834
The Android Open Source Project28527d22009-03-03 19:31:44 -08001835 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001836 * After a change in the connectivity state of a network. We're mainly
1837 * concerned with making sure that the list of DNS servers is set up
1838 * according to which networks are connected, and ensuring that the
1839 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001840 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001841 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001842 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1843
The Android Open Source Project28527d22009-03-03 19:31:44 -08001844 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001845 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001846 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001847 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001848 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001849
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001850 LinkProperties curLp = mCurrentLinkProperties[netType];
1851 LinkProperties newLp = null;
1852
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001853 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001854 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001855 if (VDBG) {
1856 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1857 " doReset=" + doReset + " resetMask=" + resetMask +
1858 "\n curLp=" + curLp +
1859 "\n newLp=" + newLp);
1860 }
1861
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001862 if (curLp != null) {
1863 if (curLp.isIdenticalInterfaceName(newLp)) {
1864 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1865 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1866 for (LinkAddress linkAddr : car.removed) {
1867 if (linkAddr.getAddress() instanceof Inet4Address) {
1868 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1869 }
1870 if (linkAddr.getAddress() instanceof Inet6Address) {
1871 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1872 }
Wink Saville051a6642011-07-13 13:44:13 -07001873 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001874 if (DBG) {
1875 log("handleConnectivityChange: addresses changed" +
1876 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1877 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001878 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001879 } else {
1880 if (DBG) {
1881 log("handleConnectivityChange: address are the same reset per doReset" +
1882 " linkProperty[" + netType + "]:" +
1883 " resetMask=" + resetMask);
1884 }
Wink Saville051a6642011-07-13 13:44:13 -07001885 }
1886 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001887 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001888 if (DBG) {
1889 log("handleConnectivityChange: interface not not equivalent reset both" +
1890 " linkProperty[" + netType + "]:" +
1891 " resetMask=" + resetMask);
1892 }
Wink Saville051a6642011-07-13 13:44:13 -07001893 }
Wink Saville051a6642011-07-13 13:44:13 -07001894 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001895 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07001896 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001897 }
1898 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001899 if (VDBG) {
1900 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1901 " doReset=" + doReset + " resetMask=" + resetMask +
1902 "\n curLp=" + curLp +
1903 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001904 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001905 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001906 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07001907 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001908
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001909 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001910 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1911 if (linkProperties != null) {
1912 String iface = linkProperties.getInterfaceName();
1913 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001914 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07001915 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1916 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07001917
1918 // Tell VPN the interface is down. It is a temporary
1919 // but effective fix to make VPN aware of the change.
1920 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1921 mVpn.interfaceStatusChanged(iface, false);
1922 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07001923 }
1924 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07001925 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001926 try {
1927 mNetd.flushInterfaceDnsCache(iface);
1928 } catch (Exception e) {
1929 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001930 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07001931 }
1932 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001933 }
1934 }
1935 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001936
1937 // TODO: Temporary notifying upstread change to Tethering.
1938 // @see bug/4455071
1939 /** Notify TetheringService if interface name has been changed. */
1940 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1941 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1942 if (isTetheringSupported()) {
1943 mTethering.handleTetherIfaceChange();
1944 }
1945 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001946 }
1947
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001948 /**
1949 * Add and remove routes using the old properties (null if not previously connected),
1950 * new properties (null if becoming disconnected). May even be double null, which
1951 * is a noop.
1952 * Uses isLinkDefault to determine if default routes should be set or conversely if
1953 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07001954 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001955 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07001956 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1957 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001958 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001959 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1960 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001961 if (curLp != null) {
1962 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001963 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001964 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001965 } else if (newLp != null) {
1966 routeDiff.added = newLp.getRoutes();
1967 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001968 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001969
Robert Greenwalt8d777252011-08-15 12:31:55 -07001970 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1971
Robert Greenwalt98107422011-07-22 11:55:33 -07001972 for (RouteInfo r : routeDiff.removed) {
1973 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001974 removeRoute(curLp, r, TO_DEFAULT_TABLE);
1975 }
1976 if (isLinkDefault == false) {
1977 // remove from a secondary route table
1978 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001979 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001980 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001981
Robert Greenwalt98107422011-07-22 11:55:33 -07001982 for (RouteInfo r : routeDiff.added) {
1983 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001984 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001985 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001986 // add to a secondary route table
1987 addRoute(newLp, r, TO_SECONDARY_TABLE);
1988
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001989 // many radios add a default route even when we don't want one.
1990 // remove the default route unless somebody else has asked for it
1991 String ifaceName = newLp.getInterfaceName();
1992 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07001993 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001994 try {
1995 mNetd.removeRoute(ifaceName, r);
1996 } catch (Exception e) {
1997 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07001998 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07001999 }
2000 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002001 }
2002 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002003
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002004 if (!isLinkDefault) {
2005 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002006 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002007 // routes changed - remove all old dns entries and add new
2008 if (curLp != null) {
2009 for (InetAddress oldDns : curLp.getDnses()) {
2010 removeRouteToAddress(curLp, oldDns);
2011 }
2012 }
2013 if (newLp != null) {
2014 for (InetAddress newDns : newLp.getDnses()) {
2015 addRouteToAddress(newLp, newDns);
2016 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002017 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002018 } else {
2019 // no change in routes, check for change in dns themselves
2020 for (InetAddress oldDns : dnsDiff.removed) {
2021 removeRouteToAddress(curLp, oldDns);
2022 }
2023 for (InetAddress newDns : dnsDiff.added) {
2024 addRouteToAddress(newLp, newDns);
2025 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002026 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002027 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002028 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002029 }
2030
2031
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002032 /**
2033 * Reads the network specific TCP buffer sizes from SystemProperties
2034 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2035 * wide use
2036 */
2037 public void updateNetworkSettings(NetworkStateTracker nt) {
2038 String key = nt.getTcpBufferSizesPropName();
2039 String bufferSizes = SystemProperties.get(key);
2040
2041 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002042 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002043
2044 // Setting to default values so we won't be stuck to previous values
2045 key = "net.tcp.buffersize.default";
2046 bufferSizes = SystemProperties.get(key);
2047 }
2048
2049 // Set values in kernel
2050 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002051 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002052 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002053 + "] which comes from [" + key + "]");
2054 }
2055 setBufferSize(bufferSizes);
2056 }
2057 }
2058
2059 /**
2060 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2061 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2062 *
2063 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2064 * writeMin, writeInitial, writeMax"
2065 */
2066 private void setBufferSize(String bufferSizes) {
2067 try {
2068 String[] values = bufferSizes.split(",");
2069
2070 if (values.length == 6) {
2071 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002072 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2073 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2074 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2075 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2076 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2077 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002078 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002079 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002080 }
2081 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002082 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002083 }
2084 }
2085
Robert Greenwalt2034b912009-08-12 16:08:25 -07002086 /**
2087 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2088 * on the highest priority active net which this process requested.
2089 * If there aren't any, clear it out
2090 */
2091 private void reassessPidDns(int myPid, boolean doBump)
2092 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002093 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002094 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002095 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002096 continue;
2097 }
2098 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002099 if (nt.getNetworkInfo().isConnected() &&
2100 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002101 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002102 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002103 List pids = mNetRequestersPids[i];
2104 for (int j=0; j<pids.size(); j++) {
2105 Integer pid = (Integer)pids.get(j);
2106 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002107 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002108 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002109 if (doBump) {
2110 bumpDns();
2111 }
2112 return;
2113 }
2114 }
2115 }
2116 }
2117 // nothing found - delete
2118 for (int i = 1; ; i++) {
2119 String prop = "net.dns" + i + "." + myPid;
2120 if (SystemProperties.get(prop).length() == 0) {
2121 if (doBump) {
2122 bumpDns();
2123 }
2124 return;
2125 }
2126 SystemProperties.set(prop, "");
2127 }
2128 }
2129
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002130 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002131 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002132 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002133 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002134 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002135 String dnsString = dns.getHostAddress();
2136 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2137 changed = true;
2138 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2139 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002140 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002141 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002142 }
2143
2144 private void bumpDns() {
2145 /*
2146 * Bump the property that tells the name resolver library to reread
2147 * the DNS server list from the properties.
2148 */
2149 String propVal = SystemProperties.get("net.dnschange");
2150 int n = 0;
2151 if (propVal.length() != 0) {
2152 try {
2153 n = Integer.parseInt(propVal);
2154 } catch (NumberFormatException e) {}
2155 }
2156 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002157 /*
2158 * Tell the VMs to toss their DNS caches
2159 */
2160 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2161 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002162 /*
2163 * Connectivity events can happen before boot has completed ...
2164 */
2165 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002166 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002167 }
2168
Chia-chi Yehcc844502011-07-14 18:01:57 -07002169 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002170 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002171 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002172 boolean changed = false;
2173 int last = 0;
2174 if (dnses.size() == 0 && mDefaultDns != null) {
2175 ++last;
2176 String value = mDefaultDns.getHostAddress();
2177 if (!value.equals(SystemProperties.get("net.dns1"))) {
2178 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002179 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002180 }
2181 changed = true;
2182 SystemProperties.set("net.dns1", value);
2183 }
2184 } else {
2185 for (InetAddress dns : dnses) {
2186 ++last;
2187 String key = "net.dns" + last;
2188 String value = dns.getHostAddress();
2189 if (!changed && value.equals(SystemProperties.get(key))) {
2190 continue;
2191 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002192 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002193 log("adding dns " + value + " for " + network);
2194 }
2195 changed = true;
2196 SystemProperties.set(key, value);
2197 }
2198 }
2199 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2200 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002201 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002202 changed = true;
2203 SystemProperties.set(key, "");
2204 }
2205 mNumDnsEntries = last;
2206
Robert Greenwaltfce71862011-07-25 16:06:25 -07002207 if (changed) {
2208 try {
2209 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2210 mNetd.setDefaultInterfaceForDns(iface);
2211 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002212 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002213 }
2214 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002215 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2216 SystemProperties.set("net.dns.search", domains);
2217 changed = true;
2218 }
2219 return changed;
2220 }
2221
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002222 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002223 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002224 NetworkStateTracker nt = mNetTrackers[netType];
2225 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002226 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002227 if (p == null) return;
2228 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002229 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002230 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002231 String network = nt.getNetworkInfo().getTypeName();
2232 synchronized (mDnsLock) {
2233 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002234 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002235 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002236 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002237 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002238 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002239 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002240 NetworkUtils.makeStrings(dnses));
2241 } catch (Exception e) {
Wink Savillea7d56572011-09-21 11:05:43 -07002242 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002243 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002244 // set per-pid dns for attached secondary nets
2245 List pids = mNetRequestersPids[netType];
2246 for (int y=0; y< pids.size(); y++) {
2247 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002248 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 }
2250 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002251 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002253 }
2254
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002255 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002256 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2257 NETWORK_RESTORE_DELAY_PROP_NAME);
2258 if(restoreDefaultNetworkDelayStr != null &&
2259 restoreDefaultNetworkDelayStr.length() != 0) {
2260 try {
2261 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2262 } catch (NumberFormatException e) {
2263 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002265 // if the system property isn't set, use the value for the apn type
2266 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2267
2268 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2269 (mNetConfigs[networkType] != null)) {
2270 ret = mNetConfigs[networkType].restoreTime;
2271 }
2272 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002273 }
2274
2275 @Override
2276 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002277 if (mContext.checkCallingOrSelfPermission(
2278 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002279 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002280 pw.println("Permission Denial: can't dump ConnectivityService " +
2281 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2282 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002283 return;
2284 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002285 pw.println();
2286 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002287 if (nst != null) {
2288 if (nst.getNetworkInfo().isConnected()) {
2289 pw.println("Active network: " + nst.getNetworkInfo().
2290 getTypeName());
2291 }
2292 pw.println(nst.getNetworkInfo());
2293 pw.println(nst);
2294 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002295 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002297
2298 pw.println("Network Requester Pids:");
2299 for (int net : mPriorityList) {
2300 String pidString = net + ": ";
2301 for (Object pid : mNetRequestersPids[net]) {
2302 pidString = pidString + pid.toString() + ", ";
2303 }
2304 pw.println(pidString);
2305 }
2306 pw.println();
2307
2308 pw.println("FeatureUsers:");
2309 for (Object requester : mFeatureUsers) {
2310 pw.println(requester.toString());
2311 }
2312 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002313
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002314 synchronized (this) {
2315 pw.println("NetworkTranstionWakeLock is currently " +
2316 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2317 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2318 }
2319 pw.println();
2320
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002321 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002322
2323 if (mInetLog != null) {
2324 pw.println();
2325 pw.println("Inet condition reports:");
2326 for(int i = 0; i < mInetLog.size(); i++) {
2327 pw.println(mInetLog.get(i));
2328 }
2329 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002330 }
2331
Robert Greenwalt2034b912009-08-12 16:08:25 -07002332 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002333 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002334 public MyHandler(Looper looper) {
2335 super(looper);
2336 }
2337
The Android Open Source Project28527d22009-03-03 19:31:44 -08002338 @Override
2339 public void handleMessage(Message msg) {
2340 NetworkInfo info;
2341 switch (msg.what) {
2342 case NetworkStateTracker.EVENT_STATE_CHANGED:
2343 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002344 int type = info.getType();
2345 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002346
Wink Savillea7d56572011-09-21 11:05:43 -07002347 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2348 (state == NetworkInfo.State.DISCONNECTED)) {
2349 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002350 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002351 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002352 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002353
2354 // Connectivity state changed:
2355 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002356 // [12-9] Network subtype (for mobile network, as defined
2357 // by TelephonyManager)
2358 // [8-3] Detailed state ordinal (as defined by
2359 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002360 // [2-0] Network type (as defined by ConnectivityManager)
2361 int eventLogParam = (info.getType() & 0x7) |
2362 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2363 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002364 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002365 eventLogParam);
2366
2367 if (info.getDetailedState() ==
2368 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002369 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002370 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002371 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002372 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002373 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002374 // the logic here is, handle SUSPENDED the same as
2375 // DISCONNECTED. The only difference being we are
2376 // broadcasting an intent with NetworkInfo that's
2377 // suspended. This allows the applications an
2378 // opportunity to handle DISCONNECTED and SUSPENDED
2379 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002380 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002381 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002382 handleConnect(info);
2383 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002384 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002385 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002386 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002387 // TODO: Temporary allowing network configuration
2388 // change not resetting sockets.
2389 // @see bug/4455071
2390 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002391 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002392 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002393 String causedBy = null;
2394 synchronized (ConnectivityService.this) {
2395 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2396 mNetTransitionWakeLock.isHeld()) {
2397 mNetTransitionWakeLock.release();
2398 causedBy = mNetTransitionWakeLockCausedBy;
2399 }
2400 }
2401 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002402 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002403 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002404 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002405 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002406 FeatureUser u = (FeatureUser)msg.obj;
2407 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002408 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002409 case EVENT_INET_CONDITION_CHANGE:
2410 {
2411 int netType = msg.arg1;
2412 int condition = msg.arg2;
2413 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002414 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002415 }
2416 case EVENT_INET_CONDITION_HOLD_END:
2417 {
2418 int netType = msg.arg1;
2419 int sequence = msg.arg2;
2420 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002421 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002422 }
2423 case EVENT_SET_NETWORK_PREFERENCE:
2424 {
2425 int preference = msg.arg1;
2426 handleSetNetworkPreference(preference);
2427 break;
2428 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002429 case EVENT_SET_MOBILE_DATA:
2430 {
2431 boolean enabled = (msg.arg1 == ENABLED);
2432 handleSetMobileData(enabled);
2433 break;
2434 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002435 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2436 {
2437 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002438 break;
2439 }
2440 case EVENT_SET_DEPENDENCY_MET:
2441 {
2442 boolean met = (msg.arg1 == ENABLED);
2443 handleSetDependencyMet(msg.arg2, met);
2444 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002445 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002446 case EVENT_RESTORE_DNS:
2447 {
2448 if (mActiveDefaultNetwork != -1) {
2449 handleDnsConfigurationChange(mActiveDefaultNetwork);
2450 }
2451 break;
2452 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002453 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2454 {
2455 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002456 sendStickyBroadcast(intent);
2457 break;
2458 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002459 case EVENT_SET_POLICY_DATA_ENABLE: {
2460 final int networkType = msg.arg1;
2461 final boolean enabled = msg.arg2 == ENABLED;
2462 handleSetPolicyDataEnable(networkType, enabled);
2463 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002464 }
2465 }
2466 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002467
2468 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002469 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002470 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002471
2472 if (isTetheringSupported()) {
2473 return mTethering.tether(iface);
2474 } else {
2475 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2476 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002477 }
2478
2479 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002480 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002481 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002482
2483 if (isTetheringSupported()) {
2484 return mTethering.untether(iface);
2485 } else {
2486 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2487 }
2488 }
2489
2490 // javadoc from interface
2491 public int getLastTetherError(String iface) {
2492 enforceTetherAccessPermission();
2493
2494 if (isTetheringSupported()) {
2495 return mTethering.getLastTetherError(iface);
2496 } else {
2497 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2498 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002499 }
2500
2501 // TODO - proper iface API for selection by property, inspection, etc
2502 public String[] getTetherableUsbRegexs() {
2503 enforceTetherAccessPermission();
2504 if (isTetheringSupported()) {
2505 return mTethering.getTetherableUsbRegexs();
2506 } else {
2507 return new String[0];
2508 }
2509 }
2510
2511 public String[] getTetherableWifiRegexs() {
2512 enforceTetherAccessPermission();
2513 if (isTetheringSupported()) {
2514 return mTethering.getTetherableWifiRegexs();
2515 } else {
2516 return new String[0];
2517 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002518 }
2519
Danica Chang96567052010-08-11 14:54:43 -07002520 public String[] getTetherableBluetoothRegexs() {
2521 enforceTetherAccessPermission();
2522 if (isTetheringSupported()) {
2523 return mTethering.getTetherableBluetoothRegexs();
2524 } else {
2525 return new String[0];
2526 }
2527 }
2528
Mike Lockwooded4a1742011-07-19 13:04:47 -07002529 public int setUsbTethering(boolean enable) {
2530 enforceTetherAccessPermission();
2531 if (isTetheringSupported()) {
2532 return mTethering.setUsbTethering(enable);
2533 } else {
2534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2535 }
2536 }
2537
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002538 // TODO - move iface listing, queries, etc to new module
2539 // javadoc from interface
2540 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002541 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002542 return mTethering.getTetherableIfaces();
2543 }
2544
2545 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002546 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002547 return mTethering.getTetheredIfaces();
2548 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002549
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002550 @Override
2551 public String[] getTetheredIfacePairs() {
2552 enforceTetherAccessPermission();
2553 return mTethering.getTetheredIfacePairs();
2554 }
2555
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002556 public String[] getTetheringErroredIfaces() {
2557 enforceTetherAccessPermission();
2558 return mTethering.getErroredIfaces();
2559 }
2560
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002561 // if ro.tether.denied = true we default to no tethering
2562 // gservices could set the secure setting to 1 though to enable it on a build where it
2563 // had previously been turned off.
2564 public boolean isTetheringSupported() {
2565 enforceTetherAccessPermission();
2566 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002567 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2568 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2569 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002570 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002571
2572 // An API NetworkStateTrackers can call when they lose their network.
2573 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2574 // whichever happens first. The timer is started by the first caller and not
2575 // restarted by subsequent callers.
2576 public void requestNetworkTransitionWakelock(String forWhom) {
2577 enforceConnectivityInternalPermission();
2578 synchronized (this) {
2579 if (mNetTransitionWakeLock.isHeld()) return;
2580 mNetTransitionWakeLockSerialNumber++;
2581 mNetTransitionWakeLock.acquire();
2582 mNetTransitionWakeLockCausedBy = forWhom;
2583 }
2584 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002585 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002586 mNetTransitionWakeLockSerialNumber, 0),
2587 mNetTransitionWakeLockTimeout);
2588 return;
2589 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002590
Robert Greenwalt986c7412010-09-08 15:24:47 -07002591 // 100 percent is full good, 0 is full bad.
2592 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002593 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002594 mContext.enforceCallingOrSelfPermission(
2595 android.Manifest.permission.STATUS_BAR,
2596 "ConnectivityService");
2597
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002598 if (DBG) {
2599 int pid = getCallingPid();
2600 int uid = getCallingUid();
2601 String s = pid + "(" + uid + ") reports inet is " +
2602 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2603 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2604 mInetLog.add(s);
2605 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2606 mInetLog.remove(0);
2607 }
2608 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002609 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002610 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2611 }
2612
2613 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002614 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002615 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002616 return;
2617 }
2618 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002619 if (DBG) log("handleInetConditionChange: net=" + netType +
2620 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002621 return;
2622 }
Wink Savillea7d56572011-09-21 11:05:43 -07002623 if (VDBG) {
2624 log("handleInetConditionChange: net=" +
2625 netType + ", condition=" + condition +
2626 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2627 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002628 mDefaultInetCondition = condition;
2629 int delay;
2630 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002631 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002632 // setup a new hold to debounce this
2633 if (mDefaultInetCondition > 50) {
2634 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2635 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2636 } else {
2637 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2638 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2639 }
2640 mInetConditionChangeInFlight = true;
2641 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2642 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2643 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002644 // we've set the new condition, when this hold ends that will get picked up
2645 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002646 }
2647 }
2648
2649 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002650 if (DBG) {
2651 log("handleInetConditionHoldEnd: net=" + netType +
2652 ", condition=" + mDefaultInetCondition +
2653 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002654 }
2655 mInetConditionChangeInFlight = false;
2656
2657 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002658 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002659 return;
2660 }
2661 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002662 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002663 return;
2664 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002665 // TODO: Figure out why this optimization sometimes causes a
2666 // change in mDefaultInetCondition to be missed and the
2667 // UI to not be updated.
2668 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2669 // if (DBG) log("no change in condition - aborting");
2670 // return;
2671 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002672 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2673 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002674 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002675 return;
2676 }
2677 mDefaultInetConditionPublished = mDefaultInetCondition;
2678 sendInetConditionBroadcast(networkInfo);
2679 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002680 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002681
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002682 public ProxyProperties getProxy() {
2683 synchronized (mDefaultProxyLock) {
2684 return mDefaultProxyDisabled ? null : mDefaultProxy;
2685 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002686 }
2687
2688 public void setGlobalProxy(ProxyProperties proxyProperties) {
2689 enforceChangePermission();
2690 synchronized (mGlobalProxyLock) {
2691 if (proxyProperties == mGlobalProxy) return;
2692 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2693 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2694
2695 String host = "";
2696 int port = 0;
2697 String exclList = "";
2698 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2699 mGlobalProxy = new ProxyProperties(proxyProperties);
2700 host = mGlobalProxy.getHost();
2701 port = mGlobalProxy.getPort();
2702 exclList = mGlobalProxy.getExclusionList();
2703 } else {
2704 mGlobalProxy = null;
2705 }
2706 ContentResolver res = mContext.getContentResolver();
2707 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2708 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002709 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002710 exclList);
2711 }
2712
2713 if (mGlobalProxy == null) {
2714 proxyProperties = mDefaultProxy;
2715 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002716 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002717 }
2718
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002719 private void loadGlobalProxy() {
2720 ContentResolver res = mContext.getContentResolver();
2721 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2722 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2723 String exclList = Settings.Secure.getString(res,
2724 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2725 if (!TextUtils.isEmpty(host)) {
2726 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2727 synchronized (mGlobalProxyLock) {
2728 mGlobalProxy = proxyProperties;
2729 }
2730 }
2731 }
2732
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002733 public ProxyProperties getGlobalProxy() {
2734 synchronized (mGlobalProxyLock) {
2735 return mGlobalProxy;
2736 }
2737 }
2738
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002739 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2740 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2741 proxy = null;
2742 }
2743 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002744 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2745 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002746 mDefaultProxy = proxy;
2747
2748 if (!mDefaultProxyDisabled) {
2749 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002750 }
2751 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002752 }
2753
2754 private void handleDeprecatedGlobalHttpProxy() {
2755 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2756 Settings.Secure.HTTP_PROXY);
2757 if (!TextUtils.isEmpty(proxy)) {
2758 String data[] = proxy.split(":");
2759 String proxyHost = data[0];
2760 int proxyPort = 8080;
2761 if (data.length > 1) {
2762 try {
2763 proxyPort = Integer.parseInt(data[1]);
2764 } catch (NumberFormatException e) {
2765 return;
2766 }
2767 }
2768 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2769 setGlobalProxy(p);
2770 }
2771 }
2772
2773 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002774 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002775 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002776 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002777 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2778 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002779 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002780 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002781 }
2782
2783 private static class SettingsObserver extends ContentObserver {
2784 private int mWhat;
2785 private Handler mHandler;
2786 SettingsObserver(Handler handler, int what) {
2787 super(handler);
2788 mHandler = handler;
2789 mWhat = what;
2790 }
2791
2792 void observe(Context context) {
2793 ContentResolver resolver = context.getContentResolver();
2794 resolver.registerContentObserver(Settings.Secure.getUriFor(
2795 Settings.Secure.HTTP_PROXY), false, this);
2796 }
2797
2798 @Override
2799 public void onChange(boolean selfChange) {
2800 mHandler.obtainMessage(mWhat).sendToTarget();
2801 }
2802 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002803
2804 private void log(String s) {
2805 Slog.d(TAG, s);
2806 }
2807
2808 private void loge(String s) {
2809 Slog.e(TAG, s);
2810 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002811
repo syncf5de5572011-07-29 23:55:49 -07002812 int convertFeatureToNetworkType(int networkType, String feature) {
2813 int usedNetworkType = networkType;
2814
2815 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2816 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2817 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2818 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2819 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2820 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2821 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2822 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2823 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2824 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2825 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2826 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2827 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2828 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2829 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2830 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2831 } else {
2832 Slog.e(TAG, "Can't match any mobile netTracker!");
2833 }
2834 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2835 if (TextUtils.equals(feature, "p2p")) {
2836 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2837 } else {
2838 Slog.e(TAG, "Can't match any wifi netTracker!");
2839 }
2840 } else {
2841 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002842 }
repo syncf5de5572011-07-29 23:55:49 -07002843 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002844 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002845
2846 private static <T> T checkNotNull(T value, String message) {
2847 if (value == null) {
2848 throw new NullPointerException(message);
2849 }
2850 return value;
2851 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002852
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002853 /**
2854 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002855 * VpnBuilder and not available in ConnectivityManager. Permissions
2856 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002857 * @hide
2858 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002859 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002860 public boolean protectVpn(ParcelFileDescriptor socket) {
2861 try {
2862 int type = mActiveDefaultNetwork;
2863 if (ConnectivityManager.isNetworkTypeValid(type)) {
2864 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2865 return true;
2866 }
2867 } catch (Exception e) {
2868 // ignore
2869 } finally {
2870 try {
2871 socket.close();
2872 } catch (Exception e) {
2873 // ignore
2874 }
2875 }
2876 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002877 }
2878
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002879 /**
2880 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002881 * and not available in ConnectivityManager. Permissions are checked
2882 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002883 * @hide
2884 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002885 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002886 public boolean prepareVpn(String oldPackage, String newPackage) {
2887 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002888 }
2889
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002890 /**
2891 * Configure a TUN interface and return its file descriptor. Parameters
2892 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002893 * and not available in ConnectivityManager. Permissions are checked in
2894 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002895 * @hide
2896 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002897 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002898 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002899 return mVpn.establish(config);
2900 }
2901
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002902 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002903 * Start legacy VPN and return an intent to VpnDialogs. This method is
2904 * used by VpnSettings and not available in ConnectivityManager.
2905 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002906 * @hide
2907 */
2908 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002909 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2910 mVpn.startLegacyVpn(config, racoon, mtpd);
2911 }
2912
2913 /**
2914 * Return the information of the ongoing legacy VPN. This method is used
2915 * by VpnSettings and not available in ConnectivityManager. Permissions
2916 * are checked in Vpn class.
2917 * @hide
2918 */
2919 @Override
2920 public LegacyVpnInfo getLegacyVpnInfo() {
2921 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002922 }
2923
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002924 /**
2925 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2926 * through NetworkStateTracker since it works differently. For example, it
2927 * needs to override DNS servers but never takes the default routes. It
2928 * relies on another data network, and it could keep existing connections
2929 * alive after reconnecting, switching between networks, or even resuming
2930 * from deep sleep. Calls from applications should be done synchronously
2931 * to avoid race conditions. As these are all hidden APIs, refactoring can
2932 * be done whenever a better abstraction is developed.
2933 */
2934 public class VpnCallback {
2935
2936 private VpnCallback() {
2937 }
2938
Chia-chi Yehcc844502011-07-14 18:01:57 -07002939 public void override(List<String> dnsServers, List<String> searchDomains) {
2940 if (dnsServers == null) {
2941 restore();
2942 return;
2943 }
2944
2945 // Convert DNS servers into addresses.
2946 List<InetAddress> addresses = new ArrayList<InetAddress>();
2947 for (String address : dnsServers) {
2948 // Double check the addresses and remove invalid ones.
2949 try {
2950 addresses.add(InetAddress.parseNumericAddress(address));
2951 } catch (Exception e) {
2952 // ignore
2953 }
2954 }
2955 if (addresses.isEmpty()) {
2956 restore();
2957 return;
2958 }
2959
2960 // Concatenate search domains into a string.
2961 StringBuilder buffer = new StringBuilder();
2962 if (searchDomains != null) {
2963 for (String domain : searchDomains) {
2964 buffer.append(domain).append(' ');
2965 }
2966 }
2967 String domains = buffer.toString().trim();
2968
2969 // Apply DNS changes.
2970 boolean changed = false;
2971 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002972 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002973 mDnsOverridden = true;
2974 }
2975 if (changed) {
2976 bumpDns();
2977 }
2978
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002979 // Temporarily disable the default proxy.
2980 synchronized (mDefaultProxyLock) {
2981 mDefaultProxyDisabled = true;
2982 if (mDefaultProxy != null) {
2983 sendProxyBroadcast(null);
2984 }
2985 }
2986
2987 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002988 }
2989
Chia-chi Yehcc844502011-07-14 18:01:57 -07002990 public void restore() {
2991 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002992 if (mDnsOverridden) {
2993 mDnsOverridden = false;
2994 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002995 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002996 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002997 synchronized (mDefaultProxyLock) {
2998 mDefaultProxyDisabled = false;
2999 if (mDefaultProxy != null) {
3000 sendProxyBroadcast(mDefaultProxy);
3001 }
3002 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003003 }
3004 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003005}