blob: dd650bf229d3816a41586c8b403549ec50b45cdc [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070022import static android.net.ConnectivityManager.isNetworkTypeValid;
23import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070024import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080026import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.ContentResolver;
28import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090029import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.Intent;
31import android.content.pm.PackageManager;
tk.mun148c7d02011-10-13 22:51:57 +090032import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080035import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080036import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070038import android.net.INetworkPolicyListener;
39import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070040import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070041import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080042import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070043import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070045import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070047import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070048import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070049import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070051import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.net.Proxy;
53import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070054import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090056import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040058import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070060import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070061import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070062import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.Looper;
64import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070065import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070066import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070067import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.ServiceManager;
69import android.os.SystemProperties;
70import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070071import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080073import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070074import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
Chia-chi Yeh2e467642011-07-04 03:23:12 -070076import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070077import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070078import com.android.internal.telephony.Phone;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070079import com.android.server.am.BatteryStatsService;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080080import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070081import com.android.server.connectivity.Vpn;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070082import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070083import com.google.android.collect.Sets;
tk.mun148c7d02011-10-13 22:51:57 +090084import dalvik.system.DexClassLoader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070086import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import java.io.PrintWriter;
tk.mun148c7d02011-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 Savillec9822c52011-07-14 12:23:28 -070092import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070093import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070094import java.net.InetAddress;
95import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070097import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070098import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070099import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700100import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700101import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
103/**
104 * @hide
105 */
106public class ConnectivityService extends IConnectivityManager.Stub {
107
Robert Greenwaltba175a52010-10-05 19:12:26 -0700108 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700109 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 private static final String TAG = "ConnectivityService";
111
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700112 private static final boolean LOGD_RULES = false;
113
Robert Greenwalt42acef32009-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 Greenwaltf43396c2011-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 Greenwaltd0e18ff2010-01-26 11:40:34 -0800124 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800125 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800126
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127 private Vpn mVpn;
128
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700129 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
130 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700131 /** Currently active network rules by UID. */
132 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700133 /** Set of ifaces that are costly. */
134 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135
The Android Open Source Project9066cfe2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700142
143 /**
Wink Savillee8222252011-07-13 13:44:13 -0700144 * The link properties that define the current links
145 */
146 private LinkProperties mCurrentLinkProperties[];
147
148 /**
Robert Greenwalt42acef32009-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 Greenwalt42acef32009-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 Project9066cfe2009-03-03 19:31:44 -0800159 private Context mContext;
160 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700161 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-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 Project9066cfe2009-03-03 19:31:44 -0800167
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700168 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700170 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700173 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700175 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700176 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700177
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700178 private static final int ENABLED = 1;
179 private static final int DISABLED = 0;
180
Robert Greenwalt3b28e9a2011-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 Greenwalt8dcc28b2010-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 Greenwalt8dcc28b2010-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 Greenwaltf3331232010-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 Greenwalt434203a2010-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 Greenwaltd55a6b42011-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 Yeh44bb2512011-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 Saville2b30afd2011-08-05 11:40:22 -0700263 /**
Wink Saville628b0852011-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 Saville2b30afd2011-08-05 11:40:22 -0700267 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville628b0852011-08-04 15:01:58 -0700268
Jeff Sharkey8e28b7d2011-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 Greenwalt42acef32009-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 Ondo3bed4c92011-07-19 11:23:37 -0500279 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700280
Mike Lockwood0f79b542009-08-14 14:18:49 -0400281 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800282 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400283
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700284 private PowerManager.WakeLock mNetTransitionWakeLock;
285 private String mNetTransitionWakeLockCausedBy = "";
286 private int mNetTransitionWakeLockSerialNumber;
287 private int mNetTransitionWakeLockTimeout;
288
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700289 private InetAddress mDefaultDns;
290
Robert Greenwalt0a46db52011-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 Greenwalt4e8dfef2010-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 Greenwalt434203a2010-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 Yeh4c12a472011-10-03 15:34:04 -0700301 private Object mDefaultProxyLock = new Object();
302 private boolean mDefaultProxyDisabled = false;
303
Robert Greenwalt434203a2010-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700310 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700311 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700312
Robert Greenwalt511288a2009-12-07 11:33:18 -0800313 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700314 public int mSimultaneity;
315 public int mType;
316 public RadioAttributes(String init) {
317 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700318 mType = Integer.parseInt(fragments[0]);
319 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700320 }
321 }
322 RadioAttributes[] mRadioAttributes;
323
Robert Greenwalt50393202011-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 Sharkey367d15a2011-09-22 14:59:51 -0700327 public ConnectivityService(Context context, INetworkManagementService netd,
328 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800329 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800330
Wink Savillebb08caf2010-09-02 19:23:52 -0700331 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
332 handlerThread.start();
333 mHandler = new MyHandler(handlerThread.getLooper());
334
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800335 // setup our unique device name
Robert Greenwalt733c6292010-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 Sheriffa10a3ad2011-09-20 15:17:07 -0700340 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800341 SystemProperties.set("net.hostname", name);
342 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800343 }
344
Robert Greenwalte90aa5e2010-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 Greenwalte5903732011-02-22 16:00:42 -0800353 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
354 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800355 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700356 }
357
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700358 mContext = checkNotNull(context, "missing Context");
359 mNetd = checkNotNull(netd, "missing INetworkManagementService");
360 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700361
Jeff Sharkeyc006f1a2011-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 Greenwalt58d4c592011-08-02 17:18:41 -0700366 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700367 }
368
369 final PowerManager powerManager = (PowerManager) context.getSystemService(
370 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-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 Greenwalt42acef32009-08-12 16:08:25 -0700375 mNetTrackers = new NetworkStateTracker[
376 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700377 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700380
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700381 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700382 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700383
Robert Greenwalt42acef32009-08-12 16:08:25 -0700384 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700385 String[] raStrings = context.getResources().getStringArray(
386 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-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 Savilleed9c02b2010-12-03 12:01:38 -0800390 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700391 continue;
392 }
393 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800394 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700395 r.mType);
396 continue;
397 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398 mRadioAttributes[r.mType] = r;
399 }
400
Robert Greenwalt5154ae762009-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700405 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700406 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800407 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700408 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700409 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700410 }
Wink Saville975c8482011-04-07 14:23:45 -0700411 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800412 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700413 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700414 continue;
415 }
Wink Saville975c8482011-04-07 14:23:45 -0700416 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800417 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700418 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700419 continue;
420 }
Wink Saville975c8482011-04-07 14:23:45 -0700421 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700422 mNetworksDefined++;
423 } catch(Exception e) {
424 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700425 }
426 }
427
Robert Greenwalt50393202011-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 Greenwalt5154ae762009-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700446 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700447 if (na == null) continue;
Wink Saville975c8482011-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 Greenwalt5154ae762009-10-30 14:17:42 -0700452 }
453 continue;
454 }
Wink Saville975c8482011-04-07 14:23:45 -0700455 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-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 Greenwalt42acef32009-08-12 16:08:25 -0700464 mNetRequestersPids[i] = new ArrayList();
465 }
466
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500467 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700468
Robert Greenwalt5154ae762009-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 Project9066cfe2009-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 Greenwalt5154ae762009-10-30 14:17:42 -0700480 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700481 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700482 case ConnectivityManager.TYPE_WIFI:
repo syncaea743a2011-07-29 23:55:49 -0700483 mNetTrackers[netType] = new WifiStateTracker(netType,
484 mNetConfigs[netType].name);
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700487 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700488 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700489 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700490 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700491 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800492 case ConnectivityManager.TYPE_DUMMY:
493 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700494 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800495 mNetTrackers[netType].startMonitoring(context, mHandler);
496 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800497 case ConnectivityManager.TYPE_BLUETOOTH:
498 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
499 mNetTrackers[netType].startMonitoring(context, mHandler);
500 break;
tk.mun148c7d02011-10-13 22:51:57 +0900501 case ConnectivityManager.TYPE_WIMAX:
502 mNetTrackers[netType] = makeWimaxStateTracker();
Robert Greenwalt8588e472011-11-08 10:12:25 -0800503 if (mNetTrackers[netType]!= null) {
tk.mun148c7d02011-10-13 22:51:57 +0900504 mNetTrackers[netType].startMonitoring(context, mHandler);
505 }
506 break;
Benoit Goby19970692010-12-22 14:29:40 -0800507 case ConnectivityManager.TYPE_ETHERNET:
508 mNetTrackers[netType] = EthernetDataTracker.getInstance();
509 mNetTrackers[netType].startMonitoring(context, mHandler);
510 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700511 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800512 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700513 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700514 continue;
515 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700516 mCurrentLinkProperties[netType] = null;
Robert Greenwalt6537b022011-11-10 16:55:20 -0800517 if (mNetTrackers[netType] != null && mNetConfigs[netType].isDefault()) {
518 mNetTrackers[netType].reconnect();
519 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700520 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800521
Chia-chi Yehc9338302011-05-11 16:35:13 -0700522 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
523 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
524
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700525 mTethering = new Tethering(mContext, nmService, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700526 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700527 mTethering.getTetherableWifiRegexs().length != 0 ||
528 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700529 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800530
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700531 mVpn = new Vpn(mContext, new VpnCallback());
532
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700533 try {
534 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700535 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700536 } catch (RemoteException e) {
537 loge("Error registering observer :" + e);
538 }
539
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700540 if (DBG) {
541 mInetLog = new ArrayList();
542 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700543
544 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
545 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800546
547 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 }
tk.mun148c7d02011-10-13 22:51:57 +0900549private NetworkStateTracker makeWimaxStateTracker() {
550 //Initialize Wimax
551 DexClassLoader wimaxClassLoader;
552 Class wimaxStateTrackerClass = null;
553 Class wimaxServiceClass = null;
554 Class wimaxManagerClass;
555 String wimaxJarLocation;
556 String wimaxLibLocation;
557 String wimaxManagerClassName;
558 String wimaxServiceClassName;
559 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560
tk.mun148c7d02011-10-13 22:51:57 +0900561 NetworkStateTracker wimaxStateTracker = null;
562
563 boolean isWimaxEnabled = mContext.getResources().getBoolean(
564 com.android.internal.R.bool.config_wimaxEnabled);
565
566 if (isWimaxEnabled) {
567 try {
568 wimaxJarLocation = mContext.getResources().getString(
569 com.android.internal.R.string.config_wimaxServiceJarLocation);
570 wimaxLibLocation = mContext.getResources().getString(
571 com.android.internal.R.string.config_wimaxNativeLibLocation);
572 wimaxManagerClassName = mContext.getResources().getString(
573 com.android.internal.R.string.config_wimaxManagerClassname);
574 wimaxServiceClassName = mContext.getResources().getString(
575 com.android.internal.R.string.config_wimaxServiceClassname);
576 wimaxStateTrackerClassName = mContext.getResources().getString(
577 com.android.internal.R.string.config_wimaxStateTrackerClassname);
578
579 log("wimaxJarLocation: " + wimaxJarLocation);
580 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
581 new ContextWrapper(mContext).getCacheDir().getAbsolutePath(),
582 wimaxLibLocation, ClassLoader.getSystemClassLoader());
583
584 try {
585 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
586 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
587 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
588 } catch (ClassNotFoundException ex) {
589 loge("Exception finding Wimax classes: " + ex.toString());
590 return null;
591 }
592 } catch(Resources.NotFoundException ex) {
593 loge("Wimax Resources does not exist!!! ");
594 return null;
595 }
596
597 try {
598 log("Starting Wimax Service... ");
599
600 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
601 (new Class[] {Context.class, Handler.class});
602 wimaxStateTracker = (NetworkStateTracker)wmxStTrkrConst.newInstance(mContext,
603 mHandler);
604
605 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
606 (new Class[] {Context.class, wimaxStateTrackerClass});
607 wmxSrvConst.setAccessible(true);
608 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(mContext, wimaxStateTracker);
609 wmxSrvConst.setAccessible(false);
610
611 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
612
613 } catch(Exception ex) {
614 loge("Exception creating Wimax classes: " + ex.toString());
615 return null;
616 }
617 } else {
618 loge("Wimax is not enabled or not added to the network attributes!!! ");
619 return null;
620 }
621
622 return wimaxStateTracker;
623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700625 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 * @param preference the new preference
627 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700628 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700630
631 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633
634 public int getNetworkPreference() {
635 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700636 int preference;
637 synchronized(this) {
638 preference = mNetworkPreference;
639 }
640 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
642
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700643 private void handleSetNetworkPreference(int preference) {
644 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700645 mNetConfigs[preference] != null &&
646 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700647 if (mNetworkPreference != preference) {
648 final ContentResolver cr = mContext.getContentResolver();
649 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
650 synchronized(this) {
651 mNetworkPreference = preference;
652 }
653 enforcePreference();
654 }
655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700657
Wink Saville628b0852011-08-04 15:01:58 -0700658 private int getConnectivityChangeDelay() {
659 final ContentResolver cr = mContext.getContentResolver();
660
661 /** Check system properties for the default value then use secure settings value, if any. */
662 int defaultDelay = SystemProperties.getInt(
663 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
664 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
665 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
666 defaultDelay);
667 }
668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 private int getPersistedNetworkPreference() {
670 final ContentResolver cr = mContext.getContentResolver();
671
672 final int networkPrefSetting = Settings.Secure
673 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
674 if (networkPrefSetting != -1) {
675 return networkPrefSetting;
676 }
677
678 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
679 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700682 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 * In this method, we only tear down a non-preferred network. Establishing
684 * a connection to the preferred network is taken care of when we handle
685 * the disconnect event from the non-preferred network
686 * (see {@link #handleDisconnect(NetworkInfo)}).
687 */
688 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700689 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 return;
691
Robert Greenwalt42acef32009-08-12 16:08:25 -0700692 if (!mNetTrackers[mNetworkPreference].isAvailable())
693 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694
Robert Greenwalt42acef32009-08-12 16:08:25 -0700695 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700697 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700698 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800699 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700700 " in enforcePreference");
701 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700702 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704 }
705 }
706
707 private boolean teardown(NetworkStateTracker netTracker) {
708 if (netTracker.teardown()) {
709 netTracker.setTeardownRequested(true);
710 return true;
711 } else {
712 return false;
713 }
714 }
715
716 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700717 * Check if UID should be blocked from using the network represented by the
718 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700719 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700720 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
721 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700722
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700723 final boolean networkCostly;
724 final int uidRules;
725 synchronized (mRulesLock) {
726 networkCostly = mMeteredIfaces.contains(iface);
727 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700729
730 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
731 return true;
732 }
733
734 // no restrictive rules; network is visible
735 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700736 }
737
738 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700739 * Return a filtered {@link NetworkInfo}, potentially marked
740 * {@link DetailedState#BLOCKED} based on
741 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700742 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700743 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
744 NetworkInfo info = tracker.getNetworkInfo();
745 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700746 // network is blocked; clone and override state
747 info = new NetworkInfo(info);
748 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700749 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700750 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700751 }
752
753 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 * Return NetworkInfo for the active (i.e., connected) network interface.
755 * It is assumed that at most one network is active at a time. If more
756 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700757 * @return the info for the active network, or {@code null} if none is
758 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700760 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700762 enforceAccessPermission();
763 final int uid = Binder.getCallingUid();
764 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
766
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700767 @Override
768 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
769 enforceConnectivityInternalPermission();
770 return getNetworkInfo(mActiveDefaultNetwork, uid);
771 }
772
773 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 public NetworkInfo getNetworkInfo(int networkType) {
775 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700776 final int uid = Binder.getCallingUid();
777 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 }
779
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700780 private NetworkInfo getNetworkInfo(int networkType, int uid) {
781 NetworkInfo info = null;
782 if (isNetworkTypeValid(networkType)) {
783 final NetworkStateTracker tracker = mNetTrackers[networkType];
784 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700785 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700786 }
787 }
788 return info;
789 }
790
791 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 public NetworkInfo[] getAllNetworkInfo() {
793 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700794 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700795 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700796 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700797 for (NetworkStateTracker tracker : mNetTrackers) {
798 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700799 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700800 }
801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700803 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 }
805
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700806 @Override
807 public boolean isNetworkSupported(int networkType) {
808 enforceAccessPermission();
809 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
810 }
811
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700812 /**
813 * Return LinkProperties for the active (i.e., connected) default
814 * network interface. It is assumed that at most one default network
815 * is active at a time. If more than one is active, it is indeterminate
816 * which will be returned.
817 * @return the ip properties for the active network, or {@code null} if
818 * none is active
819 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700820 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700821 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700822 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700823 }
824
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700825 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700826 public LinkProperties getLinkProperties(int networkType) {
827 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700828 if (isNetworkTypeValid(networkType)) {
829 final NetworkStateTracker tracker = mNetTrackers[networkType];
830 if (tracker != null) {
831 return tracker.getLinkProperties();
832 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700833 }
834 return null;
835 }
836
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700837 @Override
838 public NetworkState[] getAllNetworkState() {
839 enforceAccessPermission();
840 final int uid = Binder.getCallingUid();
841 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700842 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700843 for (NetworkStateTracker tracker : mNetTrackers) {
844 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700845 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700846 result.add(new NetworkState(
847 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
848 }
849 }
850 }
851 return result.toArray(new NetworkState[result.size()]);
852 }
853
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700854 private NetworkState getNetworkStateUnchecked(int networkType) {
855 if (isNetworkTypeValid(networkType)) {
856 final NetworkStateTracker tracker = mNetTrackers[networkType];
857 if (tracker != null) {
858 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
859 tracker.getLinkCapabilities());
860 }
861 }
862 return null;
863 }
864
865 @Override
866 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
867 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700868
869 final long token = Binder.clearCallingIdentity();
870 try {
871 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
872 if (state != null) {
873 try {
874 return mPolicyManager.getNetworkQuotaInfo(state);
875 } catch (RemoteException e) {
876 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700877 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700878 return null;
879 } finally {
880 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700881 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700882 }
883
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700884 @Override
885 public boolean isActiveNetworkMetered() {
886 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700887
888 final long token = Binder.clearCallingIdentity();
889 try {
890 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
891 if (state != null) {
892 try {
893 return mPolicyManager.isNetworkMetered(state);
894 } catch (RemoteException e) {
895 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700896 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700897 return false;
898 } finally {
899 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700900 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700901 }
902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 public boolean setRadios(boolean turnOn) {
904 boolean result = true;
905 enforceChangePermission();
906 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700907 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909 return result;
910 }
911
912 public boolean setRadio(int netType, boolean turnOn) {
913 enforceChangePermission();
914 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
915 return false;
916 }
917 NetworkStateTracker tracker = mNetTrackers[netType];
918 return tracker != null && tracker.setRadio(turnOn);
919 }
920
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700921 /**
922 * Used to notice when the calling process dies so we can self-expire
923 *
924 * Also used to know if the process has cleaned up after itself when
925 * our auto-expire timer goes off. The timer has a link to an object.
926 *
927 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700928 private class FeatureUser implements IBinder.DeathRecipient {
929 int mNetworkType;
930 String mFeature;
931 IBinder mBinder;
932 int mPid;
933 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800934 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700935
936 FeatureUser(int type, String feature, IBinder binder) {
937 super();
938 mNetworkType = type;
939 mFeature = feature;
940 mBinder = binder;
941 mPid = getCallingPid();
942 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800943 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700944
Robert Greenwalt42acef32009-08-12 16:08:25 -0700945 try {
946 mBinder.linkToDeath(this, 0);
947 } catch (RemoteException e) {
948 binderDied();
949 }
950 }
951
952 void unlinkDeathRecipient() {
953 mBinder.unlinkToDeath(this, 0);
954 }
955
956 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800957 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800958 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
959 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700960 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700961 }
962
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700963 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700964 if (VDBG) {
965 log("ConnectivityService FeatureUser expire(" +
966 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
967 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
968 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700969 stopUsingNetworkFeature(this, false);
970 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800971
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500972 public boolean isSameUser(FeatureUser u) {
973 if (u == null) return false;
974
975 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
976 }
977
978 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
979 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
980 TextUtils.equals(mFeature, feature)) {
981 return true;
982 }
983 return false;
984 }
985
Robert Greenwaltb9285352009-12-21 18:24:07 -0800986 public String toString() {
987 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
988 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
989 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700990 }
991
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700992 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700993 public int startUsingNetworkFeature(int networkType, String feature,
994 IBinder binder) {
Wink Savillec9acde92011-09-21 11:05:43 -0700995 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800996 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700999 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001000 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001001 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001003
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001004 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001005
repo syncaea743a2011-07-29 23:55:49 -07001006 // TODO - move this into individual networktrackers
1007 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001008
1009 if (mProtectedNetworks.contains(usedNetworkType)) {
1010 enforceConnectivityInternalPermission();
1011 }
1012
Robert Greenwalt42acef32009-08-12 16:08:25 -07001013 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1014 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001015 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001016 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001017 NetworkInfo ni = network.getNetworkInfo();
1018
1019 if (ni.isAvailable() == false) {
Robert Greenwalte32e8122010-12-29 14:35:21 -08001020 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
Wink Savillec7d7eaf2012-01-25 13:47:54 -08001021 if (DBG) log("special network not available ni=" + ni.getTypeName());
Robert Greenwalte32e8122010-12-29 14:35:21 -08001022 return Phone.APN_TYPE_NOT_AVAILABLE;
1023 } else {
1024 // else make the attempt anyway - probably giving REQUEST_STARTED below
Wink Savillec7d7eaf2012-01-25 13:47:54 -08001025 if (DBG) {
1026 log("special network not available, but try anyway ni=" +
1027 ni.getTypeName());
1028 }
Robert Greenwalte32e8122010-12-29 14:35:21 -08001029 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001030 }
1031
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001032 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1033
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001034 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001035 boolean addToList = true;
1036 if (restoreTimer < 0) {
1037 // In case there is no timer is specified for the feature,
1038 // make sure we don't add duplicate entry with the same request.
1039 for (FeatureUser u : mFeatureUsers) {
1040 if (u.isSameUser(f)) {
1041 // Duplicate user is found. Do not add.
1042 addToList = false;
1043 break;
1044 }
1045 }
1046 }
1047
1048 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001049 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1050 // this gets used for per-pid dns when connected
1051 mNetRequestersPids[usedNetworkType].add(currentPid);
1052 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001053 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001054
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001055 if (restoreTimer >= 0) {
1056 mHandler.sendMessageDelayed(
1057 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1058 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001059
Robert Greenwalta64bf832009-08-19 20:19:33 -07001060 if ((ni.isConnectedOrConnecting() == true) &&
1061 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001062 if (ni.isConnected() == true) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001063 final long token = Binder.clearCallingIdentity();
1064 try {
1065 // add the pid-specific dns
1066 handleDnsConfigurationChange(usedNetworkType);
1067 if (VDBG) log("special network already active");
1068 } finally {
1069 Binder.restoreCallingIdentity(token);
1070 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001071 return Phone.APN_ALREADY_ACTIVE;
1072 }
Wink Savillec9acde92011-09-21 11:05:43 -07001073 if (VDBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001074 return Phone.APN_REQUEST_STARTED;
1075 }
1076
1077 // check if the radio in play can make another contact
1078 // assume if cannot for now
1079
Wink Savillec9acde92011-09-21 11:05:43 -07001080 if (DBG) {
1081 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1082 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001083 network.reconnect();
1084 return Phone.APN_REQUEST_STARTED;
1085 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001086 // need to remember this unsupported request so we respond appropriately on stop
1087 synchronized(this) {
1088 mFeatureUsers.add(f);
1089 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1090 // this gets used for per-pid dns when connected
1091 mNetRequestersPids[usedNetworkType].add(currentPid);
1092 }
1093 }
Robert Greenwalt02648a42010-05-18 10:52:51 -07001094 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001095 }
1096 }
1097 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
1099
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001100 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001102 enforceChangePermission();
1103
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001104 int pid = getCallingPid();
1105 int uid = getCallingUid();
1106
1107 FeatureUser u = null;
1108 boolean found = false;
1109
1110 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001111 for (FeatureUser x : mFeatureUsers) {
1112 if (x.isSameUser(pid, uid, networkType, feature)) {
1113 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001114 found = true;
1115 break;
1116 }
1117 }
1118 }
1119 if (found && u != null) {
1120 // stop regardless of how many other time this proc had called start
1121 return stopUsingNetworkFeature(u, true);
1122 } else {
1123 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001124 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001125 return 1;
1126 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001127 }
1128
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001129 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1130 int networkType = u.mNetworkType;
1131 String feature = u.mFeature;
1132 int pid = u.mPid;
1133 int uid = u.mUid;
1134
1135 NetworkStateTracker tracker = null;
1136 boolean callTeardown = false; // used to carry our decision outside of sync block
1137
Wink Savillec9acde92011-09-21 11:05:43 -07001138 if (VDBG) {
1139 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001140 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001143 if (DBG) {
1144 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1145 ", net is invalid");
1146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 return -1;
1148 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001149
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001150 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1151 // sync block
1152 synchronized(this) {
1153 // check if this process still has an outstanding start request
1154 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001155 if (VDBG) {
1156 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1157 ", ignoring");
1158 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001159 return 1;
1160 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001161 u.unlinkDeathRecipient();
1162 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1163 // If we care about duplicate requests, check for that here.
1164 //
1165 // This is done to support the extension of a request - the app
1166 // can request we start the network feature again and renew the
1167 // auto-shutoff delay. Normal "stop" calls from the app though
1168 // do not pay attention to duplicate requests - in effect the
1169 // API does not refcount and a single stop will counter multiple starts.
1170 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001171 for (FeatureUser x : mFeatureUsers) {
1172 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001173 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001174 return 1;
1175 }
1176 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001177 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001178
repo syncaea743a2011-07-29 23:55:49 -07001179 // TODO - move to individual network trackers
1180 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1181
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001182 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001183 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001184 if (DBG) {
1185 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1186 " no known tracker for used net type " + usedNetworkType);
1187 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001188 return -1;
1189 }
1190 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001191 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001192 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001193 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001194 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001195 if (VDBG) {
1196 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1197 " others still using it");
1198 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001199 return 1;
1200 }
1201 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001202 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001203 if (DBG) {
1204 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1205 " not a known feature - dropping");
1206 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001207 }
1208 }
Wink Savillec9acde92011-09-21 11:05:43 -07001209
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001210 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001211 if (DBG) {
1212 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1213 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001214 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001215 return 1;
1216 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001217 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
1220
1221 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001222 * @deprecated use requestRouteToHostAddress instead
1223 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 * Ensure that a network route exists to deliver traffic to the specified
1225 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001226 * @param networkType the type of the network over which traffic to the
1227 * specified host is to be routed
1228 * @param hostAddress the IP address of the host to which the route is
1229 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 * @return {@code true} on success, {@code false} on failure
1231 */
1232 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001233 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1234
1235 if (inetAddress == null) {
1236 return false;
1237 }
1238
1239 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1240 }
1241
1242 /**
1243 * Ensure that a network route exists to deliver traffic to the specified
1244 * host via the specified network interface.
1245 * @param networkType the type of the network over which traffic to the
1246 * specified host is to be routed
1247 * @param hostAddress the IP address of the host to which the route is
1248 * desired
1249 * @return {@code true} on success, {@code false} on failure
1250 */
1251 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001253 if (mProtectedNetworks.contains(networkType)) {
1254 enforceConnectivityInternalPermission();
1255 }
1256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001258 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 return false;
1260 }
1261 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001262
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001263 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1264 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001265 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001266 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001267 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001268 }
1269 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001271 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001272 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001273 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001274 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001275 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001276 } catch (UnknownHostException e) {
1277 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1278 } finally {
1279 Binder.restoreCallingIdentity(token);
1280 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001281 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001282 }
1283
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001284 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1285 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001286 }
1287
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001288 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1289 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001290 }
1291
Robert Greenwaltad55d352011-07-22 11:55:33 -07001292 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001293 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001294 }
1295
1296 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001297 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001298 }
1299
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001300 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1301 boolean toDefaultTable) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001302 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1303 if (bestRoute == null) {
1304 bestRoute = RouteInfo.makeHostRoute(addr);
1305 } else {
1306 if (bestRoute.getGateway().equals(addr)) {
1307 // if there is no better route, add the implied hostroute for our gateway
1308 bestRoute = RouteInfo.makeHostRoute(addr);
1309 } else {
1310 // if we will connect to this through another route, add a direct route
1311 // to it's gateway
1312 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1313 }
1314 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001315 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001316 }
1317
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001318 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001319 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001320 if ((ifaceName == null) || (lp == null) || (r == null)) {
1321 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1322 return false;
1323 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001324
1325 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001326 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001327 return false;
1328 }
1329
1330 if (r.isHostRoute() == false) {
1331 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1332 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001333 if (bestRoute.getGateway().equals(r.getGateway())) {
1334 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001335 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001336 } else {
1337 // if we will connect to our gateway through another route, add a direct
1338 // route to it's gateway
1339 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001340 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001341 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001342 }
1343 }
1344 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001345 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001346 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001347 if (toDefaultTable) {
1348 mAddedRoutes.add(r); // only track default table - only one apps can effect
1349 mNetd.addRoute(ifaceName, r);
1350 } else {
1351 mNetd.addSecondaryRoute(ifaceName, r);
1352 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001353 } catch (Exception e) {
1354 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001355 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001356 return false;
1357 }
1358 } else {
1359 // if we remove this one and there are no more like it, then refcount==0 and
1360 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001361 if (toDefaultTable) {
1362 mAddedRoutes.remove(r);
1363 if (mAddedRoutes.contains(r) == false) {
1364 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1365 try {
1366 mNetd.removeRoute(ifaceName, r);
1367 } catch (Exception e) {
1368 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001369 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001370 return false;
1371 }
1372 } else {
1373 if (VDBG) log("not removing " + r + " as it's still in use");
1374 }
1375 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001376 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001377 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001378 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001379 } catch (Exception e) {
1380 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001381 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001382 return false;
1383 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001384 }
1385 }
1386 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
1388
1389 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001390 * @see ConnectivityManager#getMobileDataEnabled()
1391 */
1392 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001393 // TODO: This detail should probably be in DataConnectionTracker's
1394 // which is where we store the value and maybe make this
1395 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001396 enforceAccessPermission();
1397 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1398 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001399 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001400 return retVal;
1401 }
1402
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001403 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001404 enforceConnectivityInternalPermission();
1405
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1407 (met ? ENABLED : DISABLED), networkType));
1408 }
1409
1410 private void handleSetDependencyMet(int networkType, boolean met) {
1411 if (mNetTrackers[networkType] != null) {
1412 if (DBG) {
1413 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1414 }
1415 mNetTrackers[networkType].setDependencyMet(met);
1416 }
1417 }
1418
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001419 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1420 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001421 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001422 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001423 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001424 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001425 }
1426
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001427 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001428 // skip update when we've already applied rules
1429 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1430 if (oldRules == uidRules) return;
1431
1432 mUidRules.put(uid, uidRules);
1433 }
1434
1435 // TODO: dispatch into NMS to push rules towards kernel module
1436 // TODO: notify UID when it has requested targeted updates
1437 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001438
1439 @Override
1440 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001441 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001442 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001443 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001444 }
1445
1446 synchronized (mRulesLock) {
1447 mMeteredIfaces.clear();
1448 for (String iface : meteredIfaces) {
1449 mMeteredIfaces.add(iface);
1450 }
1451 }
1452 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001453
1454 @Override
1455 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1456 // caller is NPMS, since we only register with them
1457 if (LOGD_RULES) {
1458 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1459 }
1460
1461 // kick off connectivity change broadcast for active network, since
1462 // global background policy change is radical.
1463 final int networkType = mActiveDefaultNetwork;
1464 if (isNetworkTypeValid(networkType)) {
1465 final NetworkStateTracker tracker = mNetTrackers[networkType];
1466 if (tracker != null) {
1467 final NetworkInfo info = tracker.getNetworkInfo();
1468 if (info != null && info.isConnected()) {
1469 sendConnectedBroadcast(info);
1470 }
1471 }
1472 }
1473 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001474 };
1475
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001476 /**
1477 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1478 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001479 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001480 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001481 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001482
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001483 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001484 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001485 }
1486
1487 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001488 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001489 if (VDBG) {
1490 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001491 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001492 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1493 }
tk.munb97d34c2012-01-06 10:43:52 +09001494 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1495 if (VDBG) {
1496 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1497 }
1498 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1499 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001500 }
1501
1502 @Override
1503 public void setPolicyDataEnable(int networkType, boolean enabled) {
1504 // only someone like NPMS should only be calling us
1505 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1506
1507 mHandler.sendMessage(mHandler.obtainMessage(
1508 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1509 }
1510
1511 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1512 if (isNetworkTypeValid(networkType)) {
1513 final NetworkStateTracker tracker = mNetTrackers[networkType];
1514 if (tracker != null) {
1515 tracker.setPolicyDataEnable(enabled);
1516 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001517 }
1518 }
1519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.ACCESS_NETWORK_STATE,
1523 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
1525
1526 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CHANGE_NETWORK_STATE,
1529 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001532 // TODO Make this a special check when it goes public
1533 private void enforceTetherChangePermission() {
1534 mContext.enforceCallingOrSelfPermission(
1535 android.Manifest.permission.CHANGE_NETWORK_STATE,
1536 "ConnectivityService");
1537 }
1538
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001539 private void enforceTetherAccessPermission() {
1540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.ACCESS_NETWORK_STATE,
1542 "ConnectivityService");
1543 }
1544
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001545 private void enforceConnectivityInternalPermission() {
1546 mContext.enforceCallingOrSelfPermission(
1547 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1548 "ConnectivityService");
1549 }
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001552 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1553 * network, we ignore it. If it is for the active network, we send out a
1554 * broadcast. But first, we check whether it might be possible to connect
1555 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 * @param info the {@code NetworkInfo} for the network
1557 */
1558 private void handleDisconnect(NetworkInfo info) {
1559
Robert Greenwalt42acef32009-08-12 16:08:25 -07001560 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561
Robert Greenwalt42acef32009-08-12 16:08:25 -07001562 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 /*
1564 * If the disconnected network is not the active one, then don't report
1565 * this as a loss of connectivity. What probably happened is that we're
1566 * getting the disconnect for a network that we explicitly disabled
1567 * in accordance with network preference policies.
1568 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001569 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001570 List pids = mNetRequestersPids[prevNetType];
1571 for (int i = 0; i<pids.size(); i++) {
1572 Integer pid = (Integer)pids.get(i);
1573 // will remove them because the net's no longer connected
1574 // need to do this now as only now do we know the pids and
1575 // can properly null things that are no longer referenced.
1576 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1581 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1582 if (info.isFailover()) {
1583 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1584 info.setFailover(false);
1585 }
1586 if (info.getReason() != null) {
1587 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1588 }
1589 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001590 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1591 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001593
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001594 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001595 tryFailover(prevNetType);
1596 if (mActiveDefaultNetwork != -1) {
1597 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001598 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1599 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001600 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001601 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1602 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001603 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001604 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001605
1606 // Reset interface if no other connections are using the same interface
1607 boolean doReset = true;
1608 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1609 if (linkProperties != null) {
1610 String oldIface = linkProperties.getInterfaceName();
1611 if (TextUtils.isEmpty(oldIface) == false) {
1612 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1613 if (networkStateTracker == null) continue;
1614 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1615 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1616 LinkProperties l = networkStateTracker.getLinkProperties();
1617 if (l == null) continue;
1618 if (oldIface.equals(l.getInterfaceName())) {
1619 doReset = false;
1620 break;
1621 }
1622 }
1623 }
1624 }
1625 }
1626
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001627 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001628 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001629
Jeff Sharkey961e3042011-08-29 16:02:57 -07001630 final Intent immediateIntent = new Intent(intent);
1631 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1632 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001633 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001634 /*
1635 * If the failover network is already connected, then immediately send
1636 * out a followup broadcast indicating successful failover
1637 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001638 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001639 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1640 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001641 }
1642 }
1643
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001644 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001645 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001646 * If this is a default network, check if other defaults are available.
1647 * Try to reconnect on all available and let them hash it out when
1648 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001649 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001650 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001651 if (mActiveDefaultNetwork == prevNetType) {
1652 mActiveDefaultNetwork = -1;
1653 }
1654
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001655 // don't signal a reconnect for anything lower or equal priority than our
1656 // current connected default
1657 // TODO - don't filter by priority now - nice optimization but risky
1658// int currentPriority = -1;
1659// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001660// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001661// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001662 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001663 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001664 if (mNetConfigs[checkType] == null) continue;
1665 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001666 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001667
1668// Enabling the isAvailable() optimization caused mobile to not get
1669// selected if it was in the middle of error handling. Specifically
1670// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1671// would not be available and we wouldn't get connected to anything.
1672// So removing the isAvailable() optimization below for now. TODO: This
1673// optimization should work and we need to investigate why it doesn't work.
1674// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1675// complete before it is really complete.
1676// if (!mNetTrackers[checkType].isAvailable()) continue;
1677
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001678// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001679
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001680 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1681 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1682 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1683 checkInfo.setFailover(true);
1684 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001685 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001686 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690
1691 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001692 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1693 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001694 }
1695
Wink Saville628b0852011-08-04 15:01:58 -07001696 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001697 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1698 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001699 }
1700
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001701 private void sendInetConditionBroadcast(NetworkInfo info) {
1702 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1703 }
1704
Wink Saville628b0852011-08-04 15:01:58 -07001705 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001706 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1708 if (info.isFailover()) {
1709 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1710 info.setFailover(false);
1711 }
1712 if (info.getReason() != null) {
1713 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1714 }
1715 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001716 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1717 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001719 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001720 return intent;
1721 }
1722
1723 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1724 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1725 }
1726
1727 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1728 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
1730
1731 /**
1732 * Called when an attempt to fail over to another network has failed.
1733 * @param info the {@link NetworkInfo} for the failed network
1734 */
1735 private void handleConnectionFailure(NetworkInfo info) {
1736 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737
Robert Greenwalt42acef32009-08-12 16:08:25 -07001738 String reason = info.getReason();
1739 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001740
Robert Greenwalt572172b2010-10-08 16:35:52 -07001741 String reasonText;
1742 if (reason == null) {
1743 reasonText = ".";
1744 } else {
1745 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001747 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001748
1749 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1750 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1751 if (getActiveNetworkInfo() == null) {
1752 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1753 }
1754 if (reason != null) {
1755 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1756 }
1757 if (extraInfo != null) {
1758 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1759 }
1760 if (info.isFailover()) {
1761 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1762 info.setFailover(false);
1763 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001764
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001765 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001766 tryFailover(info.getType());
1767 if (mActiveDefaultNetwork != -1) {
1768 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001769 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1770 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001771 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001772 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1773 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001774 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001775
Robert Greenwalt029be812010-09-20 18:01:43 -07001776 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001777
1778 final Intent immediateIntent = new Intent(intent);
1779 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1780 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001781 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001782 /*
1783 * If the failover network is already connected, then immediately send
1784 * out a followup broadcast indicating successful failover
1785 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001786 if (mActiveDefaultNetwork != -1) {
1787 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001788 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001789 }
1790
1791 private void sendStickyBroadcast(Intent intent) {
1792 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001793 if (!mSystemReady) {
1794 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001795 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001796 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001797 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001798 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001799 }
1800
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001801 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001802 }
1803 }
1804
Wink Saville628b0852011-08-04 15:01:58 -07001805 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1806 if (delayMs <= 0) {
1807 sendStickyBroadcast(intent);
1808 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001809 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001810 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1811 + intent.getAction());
1812 }
Wink Saville628b0852011-08-04 15:01:58 -07001813 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1814 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1815 }
1816 }
1817
Mike Lockwood0f79b542009-08-14 14:18:49 -04001818 void systemReady() {
1819 synchronized(this) {
1820 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001821 if (mInitialBroadcast != null) {
1822 mContext.sendStickyBroadcast(mInitialBroadcast);
1823 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001824 }
1825 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001826 // load the global proxy at startup
1827 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
1830 private void handleConnect(NetworkInfo info) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001831 final int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832
1833 // snapshot isFailover, because sendConnectedBroadcast() resets it
1834 boolean isFailover = info.isFailover();
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001835 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836
Robert Greenwalt42acef32009-08-12 16:08:25 -07001837 // if this is a default net and other default is running
1838 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001839 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001840 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1841 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001842 mNetConfigs[mActiveDefaultNetwork].priority >
1843 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001844 mNetworkPreference == mActiveDefaultNetwork) {
1845 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001846 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001847 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001848 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001849 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001850 teardown(thisNet);
1851 return;
1852 } else {
1853 // tear down the other
1854 NetworkStateTracker otherNet =
1855 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001856 if (DBG) {
1857 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001858 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001859 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001860 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001861 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001862 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001863 return;
1864 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001865 }
1866 }
1867 synchronized (ConnectivityService.this) {
1868 // have a new default network, release the transition wakelock in a second
1869 // if it's held. The second pause is to allow apps to reconnect over the
1870 // new network
1871 if (mNetTransitionWakeLock.isHeld()) {
1872 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001873 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001874 mNetTransitionWakeLockSerialNumber, 0),
1875 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001876 }
1877 }
1878 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001879 // this will cause us to come up initially as unconnected and switching
1880 // to connected after our normal pause unless somebody reports us as reall
1881 // disconnected
1882 mDefaultInetConditionPublished = 0;
1883 mDefaultConnectionSequence++;
1884 mInetConditionChangeInFlight = false;
1885 // Don't do this - if we never sign in stay, grey
1886 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001889 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001890 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001891 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001892
1893 // notify battery stats service about this network
1894 final String iface = thisNet.getLinkProperties().getInterfaceName();
1895 if (iface != null) {
1896 try {
1897 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1898 } catch (RemoteException e) {
1899 // ignored; service lives in system_server
1900 }
1901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001905 * After a change in the connectivity state of a network. We're mainly
1906 * concerned with making sure that the list of DNS servers is set up
1907 * according to which networks are connected, and ensuring that the
1908 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001910 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001911 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001914 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001915 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001917 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001918
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001919 LinkProperties curLp = mCurrentLinkProperties[netType];
1920 LinkProperties newLp = null;
1921
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001922 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001923 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001924 if (VDBG) {
1925 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1926 " doReset=" + doReset + " resetMask=" + resetMask +
1927 "\n curLp=" + curLp +
1928 "\n newLp=" + newLp);
1929 }
1930
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001931 if (curLp != null) {
1932 if (curLp.isIdenticalInterfaceName(newLp)) {
1933 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1934 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1935 for (LinkAddress linkAddr : car.removed) {
1936 if (linkAddr.getAddress() instanceof Inet4Address) {
1937 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1938 }
1939 if (linkAddr.getAddress() instanceof Inet6Address) {
1940 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1941 }
Wink Savillee8222252011-07-13 13:44:13 -07001942 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001943 if (DBG) {
1944 log("handleConnectivityChange: addresses changed" +
1945 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1946 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001947 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001948 } else {
1949 if (DBG) {
1950 log("handleConnectivityChange: address are the same reset per doReset" +
1951 " linkProperty[" + netType + "]:" +
1952 " resetMask=" + resetMask);
1953 }
Wink Savillee8222252011-07-13 13:44:13 -07001954 }
1955 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001956 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001957 if (DBG) {
1958 log("handleConnectivityChange: interface not not equivalent reset both" +
1959 " linkProperty[" + netType + "]:" +
1960 " resetMask=" + resetMask);
1961 }
Wink Savillee8222252011-07-13 13:44:13 -07001962 }
Wink Savillee8222252011-07-13 13:44:13 -07001963 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001964 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07001965 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001966 }
1967 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001968 if (VDBG) {
1969 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1970 " doReset=" + doReset + " resetMask=" + resetMask +
1971 "\n curLp=" + curLp +
1972 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001975 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001976 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001977
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001978 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001979 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1980 if (linkProperties != null) {
1981 String iface = linkProperties.getInterfaceName();
1982 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001983 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001984 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1985 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001986
1987 // Tell VPN the interface is down. It is a temporary
1988 // but effective fix to make VPN aware of the change.
1989 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1990 mVpn.interfaceStatusChanged(iface, false);
1991 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001992 }
1993 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07001994 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001995 try {
1996 mNetd.flushInterfaceDnsCache(iface);
1997 } catch (Exception e) {
1998 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001999 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002000 }
2001 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002002 }
2003 }
2004 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002005
2006 // TODO: Temporary notifying upstread change to Tethering.
2007 // @see bug/4455071
2008 /** Notify TetheringService if interface name has been changed. */
2009 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2010 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
2011 if (isTetheringSupported()) {
2012 mTethering.handleTetherIfaceChange();
2013 }
2014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 }
2016
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002017 /**
2018 * Add and remove routes using the old properties (null if not previously connected),
2019 * new properties (null if becoming disconnected). May even be double null, which
2020 * is a noop.
2021 * Uses isLinkDefault to determine if default routes should be set or conversely if
2022 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002023 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002024 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002025 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2026 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002027 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002028 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2029 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002030 if (curLp != null) {
2031 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002032 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002033 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002034 } else if (newLp != null) {
2035 routeDiff.added = newLp.getRoutes();
2036 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002037 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002038
Robert Greenwaltf125a092011-08-15 12:31:55 -07002039 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2040
Robert Greenwaltad55d352011-07-22 11:55:33 -07002041 for (RouteInfo r : routeDiff.removed) {
2042 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002043 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2044 }
2045 if (isLinkDefault == false) {
2046 // remove from a secondary route table
2047 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002048 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002049 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002050
Robert Greenwaltad55d352011-07-22 11:55:33 -07002051 for (RouteInfo r : routeDiff.added) {
2052 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002053 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002054 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002055 // add to a secondary route table
2056 addRoute(newLp, r, TO_SECONDARY_TABLE);
2057
Robert Greenwalte6b24292011-08-09 16:52:58 -07002058 // many radios add a default route even when we don't want one.
2059 // remove the default route unless somebody else has asked for it
2060 String ifaceName = newLp.getInterfaceName();
2061 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002062 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002063 try {
2064 mNetd.removeRoute(ifaceName, r);
2065 } catch (Exception e) {
2066 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08002067 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002068 }
2069 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002070 }
2071 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002072
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002073 if (!isLinkDefault) {
2074 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002075 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002076 // routes changed - remove all old dns entries and add new
2077 if (curLp != null) {
2078 for (InetAddress oldDns : curLp.getDnses()) {
2079 removeRouteToAddress(curLp, oldDns);
2080 }
2081 }
2082 if (newLp != null) {
2083 for (InetAddress newDns : newLp.getDnses()) {
2084 addRouteToAddress(newLp, newDns);
2085 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002086 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002087 } else {
2088 // no change in routes, check for change in dns themselves
2089 for (InetAddress oldDns : dnsDiff.removed) {
2090 removeRouteToAddress(curLp, oldDns);
2091 }
2092 for (InetAddress newDns : dnsDiff.added) {
2093 addRouteToAddress(newLp, newDns);
2094 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002095 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002096 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002097 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002098 }
2099
2100
Irfan Sheriffd649c122010-06-09 15:39:36 -07002101 /**
2102 * Reads the network specific TCP buffer sizes from SystemProperties
2103 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2104 * wide use
2105 */
2106 public void updateNetworkSettings(NetworkStateTracker nt) {
2107 String key = nt.getTcpBufferSizesPropName();
2108 String bufferSizes = SystemProperties.get(key);
2109
2110 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002111 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002112
2113 // Setting to default values so we won't be stuck to previous values
2114 key = "net.tcp.buffersize.default";
2115 bufferSizes = SystemProperties.get(key);
2116 }
2117
2118 // Set values in kernel
2119 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002120 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002121 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002122 + "] which comes from [" + key + "]");
2123 }
2124 setBufferSize(bufferSizes);
2125 }
2126 }
2127
2128 /**
2129 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2130 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2131 *
2132 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2133 * writeMin, writeInitial, writeMax"
2134 */
2135 private void setBufferSize(String bufferSizes) {
2136 try {
2137 String[] values = bufferSizes.split(",");
2138
2139 if (values.length == 6) {
2140 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002141 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2142 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2143 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2144 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2145 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2146 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002147 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002148 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002149 }
2150 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002151 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002152 }
2153 }
2154
Robert Greenwalt42acef32009-08-12 16:08:25 -07002155 /**
2156 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2157 * on the highest priority active net which this process requested.
2158 * If there aren't any, clear it out
2159 */
2160 private void reassessPidDns(int myPid, boolean doBump)
2161 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002162 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002163 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002164 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002165 continue;
2166 }
2167 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002168 if (nt.getNetworkInfo().isConnected() &&
2169 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002170 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002171 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002172 List pids = mNetRequestersPids[i];
2173 for (int j=0; j<pids.size(); j++) {
2174 Integer pid = (Integer)pids.get(j);
2175 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002176 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002177 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002178 if (doBump) {
2179 bumpDns();
2180 }
2181 return;
2182 }
2183 }
2184 }
2185 }
2186 // nothing found - delete
2187 for (int i = 1; ; i++) {
2188 String prop = "net.dns" + i + "." + myPid;
2189 if (SystemProperties.get(prop).length() == 0) {
2190 if (doBump) {
2191 bumpDns();
2192 }
2193 return;
2194 }
2195 SystemProperties.set(prop, "");
2196 }
2197 }
2198
Robert Greenwalt10398722010-12-17 15:20:36 -08002199 // return true if results in a change
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002200 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002201 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002202 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002203 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002204 String dnsString = dns.getHostAddress();
2205 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2206 changed = true;
yoonsung.nam7b72ea72012-03-02 19:56:16 +09002207 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt10398722010-12-17 15:20:36 -08002208 }
yoonsung.nam7b72ea72012-03-02 19:56:16 +09002209 j++;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002210 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002211 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002212 }
2213
2214 private void bumpDns() {
2215 /*
2216 * Bump the property that tells the name resolver library to reread
2217 * the DNS server list from the properties.
2218 */
2219 String propVal = SystemProperties.get("net.dnschange");
2220 int n = 0;
2221 if (propVal.length() != 0) {
2222 try {
2223 n = Integer.parseInt(propVal);
2224 } catch (NumberFormatException e) {}
2225 }
2226 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002227 /*
2228 * Tell the VMs to toss their DNS caches
2229 */
2230 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2231 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002232 /*
2233 * Connectivity events can happen before boot has completed ...
2234 */
2235 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002236 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002237 }
2238
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002239 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002240 private boolean updateDns(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002241 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002242 boolean changed = false;
2243 int last = 0;
2244 if (dnses.size() == 0 && mDefaultDns != null) {
2245 ++last;
2246 String value = mDefaultDns.getHostAddress();
2247 if (!value.equals(SystemProperties.get("net.dns1"))) {
2248 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002249 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002250 }
2251 changed = true;
2252 SystemProperties.set("net.dns1", value);
2253 }
2254 } else {
2255 for (InetAddress dns : dnses) {
2256 ++last;
2257 String key = "net.dns" + last;
2258 String value = dns.getHostAddress();
2259 if (!changed && value.equals(SystemProperties.get(key))) {
2260 continue;
2261 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002262 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002263 log("adding dns " + value + " for " + network);
2264 }
2265 changed = true;
2266 SystemProperties.set(key, value);
2267 }
2268 }
2269 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2270 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002271 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002272 changed = true;
2273 SystemProperties.set(key, "");
2274 }
2275 mNumDnsEntries = last;
2276
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002277 if (changed) {
2278 try {
2279 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2280 mNetd.setDefaultInterfaceForDns(iface);
2281 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002282 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002283 }
2284 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002285 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2286 SystemProperties.set("net.dns.search", domains);
2287 changed = true;
2288 }
2289 return changed;
2290 }
2291
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002292 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002293 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002294 NetworkStateTracker nt = mNetTrackers[netType];
2295 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002296 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002297 if (p == null) return;
2298 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002299 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002300 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002301 String network = nt.getNetworkInfo().getTypeName();
2302 synchronized (mDnsLock) {
2303 if (!mDnsOverridden) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002304 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002305 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002306 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002307 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002308 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002309 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002310 NetworkUtils.makeStrings(dnses));
2311 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002312 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002313 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002314 // set per-pid dns for attached secondary nets
2315 List pids = mNetRequestersPids[netType];
2316 for (int y=0; y< pids.size(); y++) {
2317 Integer pid = (Integer)pids.get(y);
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002318 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
2320 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002321 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002323 }
2324
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002325 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002326 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2327 NETWORK_RESTORE_DELAY_PROP_NAME);
2328 if(restoreDefaultNetworkDelayStr != null &&
2329 restoreDefaultNetworkDelayStr.length() != 0) {
2330 try {
2331 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2332 } catch (NumberFormatException e) {
2333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002335 // if the system property isn't set, use the value for the apn type
2336 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2337
2338 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2339 (mNetConfigs[networkType] != null)) {
2340 ret = mNetConfigs[networkType].restoreTime;
2341 }
2342 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 }
2344
2345 @Override
2346 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002347 if (mContext.checkCallingOrSelfPermission(
2348 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002350 pw.println("Permission Denial: can't dump ConnectivityService " +
2351 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2352 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 return;
2354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 pw.println();
2356 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002357 if (nst != null) {
2358 if (nst.getNetworkInfo().isConnected()) {
2359 pw.println("Active network: " + nst.getNetworkInfo().
2360 getTypeName());
2361 }
2362 pw.println(nst.getNetworkInfo());
2363 pw.println(nst);
2364 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002367
2368 pw.println("Network Requester Pids:");
2369 for (int net : mPriorityList) {
2370 String pidString = net + ": ";
2371 for (Object pid : mNetRequestersPids[net]) {
2372 pidString = pidString + pid.toString() + ", ";
2373 }
2374 pw.println(pidString);
2375 }
2376 pw.println();
2377
2378 pw.println("FeatureUsers:");
2379 for (Object requester : mFeatureUsers) {
2380 pw.println(requester.toString());
2381 }
2382 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002383
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002384 synchronized (this) {
2385 pw.println("NetworkTranstionWakeLock is currently " +
2386 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2387 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2388 }
2389 pw.println();
2390
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002391 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002392
2393 if (mInetLog != null) {
2394 pw.println();
2395 pw.println("Inet condition reports:");
2396 for(int i = 0; i < mInetLog.size(); i++) {
2397 pw.println(mInetLog.get(i));
2398 }
2399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 }
2401
Robert Greenwalt42acef32009-08-12 16:08:25 -07002402 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002404 public MyHandler(Looper looper) {
2405 super(looper);
2406 }
2407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 @Override
2409 public void handleMessage(Message msg) {
2410 NetworkInfo info;
2411 switch (msg.what) {
2412 case NetworkStateTracker.EVENT_STATE_CHANGED:
2413 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002414 int type = info.getType();
2415 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002416
Wink Savillec9acde92011-09-21 11:05:43 -07002417 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2418 (state == NetworkInfo.State.DISCONNECTED)) {
2419 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002420 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002421 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423
2424 // Connectivity state changed:
Robert Greenwalt3bc9a792012-04-25 13:45:02 -07002425 // [31-14] Reserved for future use
2426 // [13-10] Network subtype (for mobile network, as defined
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002427 // by TelephonyManager)
Robert Greenwalt3bc9a792012-04-25 13:45:02 -07002428 // [9-4] Detailed state ordinal (as defined by
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002429 // NetworkInfo.DetailedState)
Robert Greenwalt3bc9a792012-04-25 13:45:02 -07002430 // [3-0] Network type (as defined by ConnectivityManager)
2431 int eventLogParam = (info.getType() & 0xf) |
2432 ((info.getDetailedState().ordinal() & 0x3f) << 4) |
2433 (info.getSubtype() << 10);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002434 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002435 eventLogParam);
2436
2437 if (info.getDetailedState() ==
2438 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002440 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002442 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002444 // the logic here is, handle SUSPENDED the same as
2445 // DISCONNECTED. The only difference being we are
2446 // broadcasting an intent with NetworkInfo that's
2447 // suspended. This allows the applications an
2448 // opportunity to handle DISCONNECTED and SUSPENDED
2449 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002451 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 handleConnect(info);
2453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002456 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002457 // TODO: Temporary allowing network configuration
2458 // change not resetting sockets.
2459 // @see bug/4455071
2460 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002462 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002463 String causedBy = null;
2464 synchronized (ConnectivityService.this) {
2465 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2466 mNetTransitionWakeLock.isHeld()) {
2467 mNetTransitionWakeLock.release();
2468 causedBy = mNetTransitionWakeLockCausedBy;
2469 }
2470 }
2471 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002472 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002473 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002474 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002475 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002476 FeatureUser u = (FeatureUser)msg.obj;
2477 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002478 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002479 case EVENT_INET_CONDITION_CHANGE:
2480 {
2481 int netType = msg.arg1;
2482 int condition = msg.arg2;
2483 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002484 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002485 }
2486 case EVENT_INET_CONDITION_HOLD_END:
2487 {
2488 int netType = msg.arg1;
2489 int sequence = msg.arg2;
2490 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002491 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002492 }
2493 case EVENT_SET_NETWORK_PREFERENCE:
2494 {
2495 int preference = msg.arg1;
2496 handleSetNetworkPreference(preference);
2497 break;
2498 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002499 case EVENT_SET_MOBILE_DATA:
2500 {
2501 boolean enabled = (msg.arg1 == ENABLED);
2502 handleSetMobileData(enabled);
2503 break;
2504 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002505 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2506 {
2507 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002508 break;
2509 }
2510 case EVENT_SET_DEPENDENCY_MET:
2511 {
2512 boolean met = (msg.arg1 == ENABLED);
2513 handleSetDependencyMet(msg.arg2, met);
2514 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002515 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002516 case EVENT_RESTORE_DNS:
2517 {
2518 if (mActiveDefaultNetwork != -1) {
2519 handleDnsConfigurationChange(mActiveDefaultNetwork);
2520 }
2521 break;
2522 }
Wink Saville628b0852011-08-04 15:01:58 -07002523 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2524 {
2525 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002526 sendStickyBroadcast(intent);
2527 break;
2528 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002529 case EVENT_SET_POLICY_DATA_ENABLE: {
2530 final int networkType = msg.arg1;
2531 final boolean enabled = msg.arg2 == ENABLED;
2532 handleSetPolicyDataEnable(networkType, enabled);
2533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535 }
2536 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002537
2538 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002539 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002540 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002541
2542 if (isTetheringSupported()) {
2543 return mTethering.tether(iface);
2544 } else {
2545 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2546 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002547 }
2548
2549 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002550 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002551 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002552
2553 if (isTetheringSupported()) {
2554 return mTethering.untether(iface);
2555 } else {
2556 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2557 }
2558 }
2559
2560 // javadoc from interface
2561 public int getLastTetherError(String iface) {
2562 enforceTetherAccessPermission();
2563
2564 if (isTetheringSupported()) {
2565 return mTethering.getLastTetherError(iface);
2566 } else {
2567 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2568 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002569 }
2570
2571 // TODO - proper iface API for selection by property, inspection, etc
2572 public String[] getTetherableUsbRegexs() {
2573 enforceTetherAccessPermission();
2574 if (isTetheringSupported()) {
2575 return mTethering.getTetherableUsbRegexs();
2576 } else {
2577 return new String[0];
2578 }
2579 }
2580
2581 public String[] getTetherableWifiRegexs() {
2582 enforceTetherAccessPermission();
2583 if (isTetheringSupported()) {
2584 return mTethering.getTetherableWifiRegexs();
2585 } else {
2586 return new String[0];
2587 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002588 }
2589
Danica Chang6fdd0c62010-08-11 14:54:43 -07002590 public String[] getTetherableBluetoothRegexs() {
2591 enforceTetherAccessPermission();
2592 if (isTetheringSupported()) {
2593 return mTethering.getTetherableBluetoothRegexs();
2594 } else {
2595 return new String[0];
2596 }
2597 }
2598
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002599 public int setUsbTethering(boolean enable) {
2600 enforceTetherAccessPermission();
2601 if (isTetheringSupported()) {
2602 return mTethering.setUsbTethering(enable);
2603 } else {
2604 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2605 }
2606 }
2607
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002608 // TODO - move iface listing, queries, etc to new module
2609 // javadoc from interface
2610 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002611 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002612 return mTethering.getTetherableIfaces();
2613 }
2614
2615 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002616 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002617 return mTethering.getTetheredIfaces();
2618 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002619
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002620 @Override
2621 public String[] getTetheredIfacePairs() {
2622 enforceTetherAccessPermission();
2623 return mTethering.getTetheredIfacePairs();
2624 }
2625
Robert Greenwalt5a735062010-03-02 17:25:02 -08002626 public String[] getTetheringErroredIfaces() {
2627 enforceTetherAccessPermission();
2628 return mTethering.getErroredIfaces();
2629 }
2630
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002631 // if ro.tether.denied = true we default to no tethering
2632 // gservices could set the secure setting to 1 though to enable it on a build where it
2633 // had previously been turned off.
2634 public boolean isTetheringSupported() {
2635 enforceTetherAccessPermission();
2636 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002637 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2638 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2639 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002640 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002641
2642 // An API NetworkStateTrackers can call when they lose their network.
2643 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2644 // whichever happens first. The timer is started by the first caller and not
2645 // restarted by subsequent callers.
2646 public void requestNetworkTransitionWakelock(String forWhom) {
2647 enforceConnectivityInternalPermission();
2648 synchronized (this) {
2649 if (mNetTransitionWakeLock.isHeld()) return;
2650 mNetTransitionWakeLockSerialNumber++;
2651 mNetTransitionWakeLock.acquire();
2652 mNetTransitionWakeLockCausedBy = forWhom;
2653 }
2654 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002655 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002656 mNetTransitionWakeLockSerialNumber, 0),
2657 mNetTransitionWakeLockTimeout);
2658 return;
2659 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002660
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002661 // 100 percent is full good, 0 is full bad.
2662 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002663 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002664 mContext.enforceCallingOrSelfPermission(
2665 android.Manifest.permission.STATUS_BAR,
2666 "ConnectivityService");
2667
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002668 if (DBG) {
2669 int pid = getCallingPid();
2670 int uid = getCallingUid();
2671 String s = pid + "(" + uid + ") reports inet is " +
2672 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2673 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2674 mInetLog.add(s);
2675 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2676 mInetLog.remove(0);
2677 }
2678 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002679 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002680 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2681 }
2682
2683 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002684 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002685 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002686 return;
2687 }
2688 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002689 if (DBG) log("handleInetConditionChange: net=" + netType +
2690 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002691 return;
2692 }
Wink Savillec9acde92011-09-21 11:05:43 -07002693 if (VDBG) {
2694 log("handleInetConditionChange: net=" +
2695 netType + ", condition=" + condition +
2696 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2697 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002698 mDefaultInetCondition = condition;
2699 int delay;
2700 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002701 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002702 // setup a new hold to debounce this
2703 if (mDefaultInetCondition > 50) {
2704 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2705 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2706 } else {
2707 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2708 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2709 }
2710 mInetConditionChangeInFlight = true;
2711 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2712 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2713 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002714 // we've set the new condition, when this hold ends that will get picked up
2715 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002716 }
2717 }
2718
2719 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002720 if (DBG) {
2721 log("handleInetConditionHoldEnd: net=" + netType +
2722 ", condition=" + mDefaultInetCondition +
2723 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002724 }
2725 mInetConditionChangeInFlight = false;
2726
2727 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002728 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002729 return;
2730 }
2731 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002732 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002733 return;
2734 }
Wink Saville628b0852011-08-04 15:01:58 -07002735 // TODO: Figure out why this optimization sometimes causes a
2736 // change in mDefaultInetCondition to be missed and the
2737 // UI to not be updated.
2738 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2739 // if (DBG) log("no change in condition - aborting");
2740 // return;
2741 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002742 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2743 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002744 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002745 return;
2746 }
2747 mDefaultInetConditionPublished = mDefaultInetCondition;
2748 sendInetConditionBroadcast(networkInfo);
2749 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002750 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002751
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002752 public ProxyProperties getProxy() {
2753 synchronized (mDefaultProxyLock) {
2754 return mDefaultProxyDisabled ? null : mDefaultProxy;
2755 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 }
2757
2758 public void setGlobalProxy(ProxyProperties proxyProperties) {
2759 enforceChangePermission();
2760 synchronized (mGlobalProxyLock) {
2761 if (proxyProperties == mGlobalProxy) return;
2762 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2763 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2764
2765 String host = "";
2766 int port = 0;
2767 String exclList = "";
2768 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2769 mGlobalProxy = new ProxyProperties(proxyProperties);
2770 host = mGlobalProxy.getHost();
2771 port = mGlobalProxy.getPort();
2772 exclList = mGlobalProxy.getExclusionList();
2773 } else {
2774 mGlobalProxy = null;
2775 }
2776 ContentResolver res = mContext.getContentResolver();
2777 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2778 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002779 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002780 exclList);
2781 }
2782
2783 if (mGlobalProxy == null) {
2784 proxyProperties = mDefaultProxy;
2785 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07002786 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002787 }
2788
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002789 private void loadGlobalProxy() {
2790 ContentResolver res = mContext.getContentResolver();
2791 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2792 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2793 String exclList = Settings.Secure.getString(res,
2794 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2795 if (!TextUtils.isEmpty(host)) {
2796 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2797 synchronized (mGlobalProxyLock) {
2798 mGlobalProxy = proxyProperties;
2799 }
2800 }
2801 }
2802
Robert Greenwalt434203a2010-10-11 16:00:27 -07002803 public ProxyProperties getGlobalProxy() {
2804 synchronized (mGlobalProxyLock) {
2805 return mGlobalProxy;
2806 }
2807 }
2808
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002809 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2810 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2811 proxy = null;
2812 }
2813 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002814 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2815 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002816 mDefaultProxy = proxy;
2817
2818 if (!mDefaultProxyDisabled) {
2819 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002820 }
2821 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 }
2823
2824 private void handleDeprecatedGlobalHttpProxy() {
2825 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2826 Settings.Secure.HTTP_PROXY);
2827 if (!TextUtils.isEmpty(proxy)) {
2828 String data[] = proxy.split(":");
2829 String proxyHost = data[0];
2830 int proxyPort = 8080;
2831 if (data.length > 1) {
2832 try {
2833 proxyPort = Integer.parseInt(data[1]);
2834 } catch (NumberFormatException e) {
2835 return;
2836 }
2837 }
2838 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2839 setGlobalProxy(p);
2840 }
2841 }
2842
2843 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002844 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002845 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002847 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2848 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002849 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002850 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 }
2852
2853 private static class SettingsObserver extends ContentObserver {
2854 private int mWhat;
2855 private Handler mHandler;
2856 SettingsObserver(Handler handler, int what) {
2857 super(handler);
2858 mHandler = handler;
2859 mWhat = what;
2860 }
2861
2862 void observe(Context context) {
2863 ContentResolver resolver = context.getContentResolver();
2864 resolver.registerContentObserver(Settings.Secure.getUriFor(
2865 Settings.Secure.HTTP_PROXY), false, this);
2866 }
2867
2868 @Override
2869 public void onChange(boolean selfChange) {
2870 mHandler.obtainMessage(mWhat).sendToTarget();
2871 }
2872 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002873
2874 private void log(String s) {
2875 Slog.d(TAG, s);
2876 }
2877
2878 private void loge(String s) {
2879 Slog.e(TAG, s);
2880 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002881
repo syncaea743a2011-07-29 23:55:49 -07002882 int convertFeatureToNetworkType(int networkType, String feature) {
2883 int usedNetworkType = networkType;
2884
2885 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2886 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2887 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2888 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2889 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2890 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2891 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2892 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2893 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2894 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2895 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2896 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2897 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2898 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2899 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2900 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2901 } else {
2902 Slog.e(TAG, "Can't match any mobile netTracker!");
2903 }
2904 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2905 if (TextUtils.equals(feature, "p2p")) {
2906 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2907 } else {
2908 Slog.e(TAG, "Can't match any wifi netTracker!");
2909 }
2910 } else {
2911 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002912 }
repo syncaea743a2011-07-29 23:55:49 -07002913 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002914 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002915
2916 private static <T> T checkNotNull(T value, String message) {
2917 if (value == null) {
2918 throw new NullPointerException(message);
2919 }
2920 return value;
2921 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002922
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002923 /**
2924 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002925 * VpnBuilder and not available in ConnectivityManager. Permissions
2926 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002927 * @hide
2928 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002929 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002930 public boolean protectVpn(ParcelFileDescriptor socket) {
2931 try {
2932 int type = mActiveDefaultNetwork;
2933 if (ConnectivityManager.isNetworkTypeValid(type)) {
2934 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2935 return true;
2936 }
2937 } catch (Exception e) {
2938 // ignore
2939 } finally {
2940 try {
2941 socket.close();
2942 } catch (Exception e) {
2943 // ignore
2944 }
2945 }
2946 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002947 }
2948
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002949 /**
2950 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002951 * and not available in ConnectivityManager. Permissions are checked
2952 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002953 * @hide
2954 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002955 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002956 public boolean prepareVpn(String oldPackage, String newPackage) {
2957 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002958 }
2959
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002960 /**
2961 * Configure a TUN interface and return its file descriptor. Parameters
2962 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002963 * and not available in ConnectivityManager. Permissions are checked in
2964 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002965 * @hide
2966 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002967 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002968 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002969 return mVpn.establish(config);
2970 }
2971
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002972 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002973 * Start legacy VPN and return an intent to VpnDialogs. This method is
2974 * used by VpnSettings and not available in ConnectivityManager.
2975 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002976 * @hide
2977 */
2978 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002979 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2980 mVpn.startLegacyVpn(config, racoon, mtpd);
2981 }
2982
2983 /**
2984 * Return the information of the ongoing legacy VPN. This method is used
2985 * by VpnSettings and not available in ConnectivityManager. Permissions
2986 * are checked in Vpn class.
2987 * @hide
2988 */
2989 @Override
2990 public LegacyVpnInfo getLegacyVpnInfo() {
2991 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002992 }
2993
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002994 /**
2995 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2996 * through NetworkStateTracker since it works differently. For example, it
2997 * needs to override DNS servers but never takes the default routes. It
2998 * relies on another data network, and it could keep existing connections
2999 * alive after reconnecting, switching between networks, or even resuming
3000 * from deep sleep. Calls from applications should be done synchronously
3001 * to avoid race conditions. As these are all hidden APIs, refactoring can
3002 * be done whenever a better abstraction is developed.
3003 */
3004 public class VpnCallback {
3005
3006 private VpnCallback() {
3007 }
3008
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003009 public void override(List<String> dnsServers, List<String> searchDomains) {
3010 if (dnsServers == null) {
3011 restore();
3012 return;
3013 }
3014
3015 // Convert DNS servers into addresses.
3016 List<InetAddress> addresses = new ArrayList<InetAddress>();
3017 for (String address : dnsServers) {
3018 // Double check the addresses and remove invalid ones.
3019 try {
3020 addresses.add(InetAddress.parseNumericAddress(address));
3021 } catch (Exception e) {
3022 // ignore
3023 }
3024 }
3025 if (addresses.isEmpty()) {
3026 restore();
3027 return;
3028 }
3029
3030 // Concatenate search domains into a string.
3031 StringBuilder buffer = new StringBuilder();
3032 if (searchDomains != null) {
3033 for (String domain : searchDomains) {
3034 buffer.append(domain).append(' ');
3035 }
3036 }
3037 String domains = buffer.toString().trim();
3038
3039 // Apply DNS changes.
3040 boolean changed = false;
3041 synchronized (mDnsLock) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07003042 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003043 mDnsOverridden = true;
3044 }
3045 if (changed) {
3046 bumpDns();
3047 }
3048
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003049 // Temporarily disable the default proxy.
3050 synchronized (mDefaultProxyLock) {
3051 mDefaultProxyDisabled = true;
3052 if (mDefaultProxy != null) {
3053 sendProxyBroadcast(null);
3054 }
3055 }
3056
3057 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003058 }
3059
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003060 public void restore() {
3061 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003062 if (mDnsOverridden) {
3063 mDnsOverridden = false;
3064 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003065 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003066 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003067 synchronized (mDefaultProxyLock) {
3068 mDefaultProxyDisabled = false;
3069 if (mDefaultProxy != null) {
3070 sendProxyBroadcast(mDefaultProxy);
3071 }
3072 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003073 }
3074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075}