blob: a372fb8e06cf31915347273f9689a02e91393fcb [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();
868 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
869 if (state != null) {
870 try {
871 return mPolicyManager.getNetworkQuotaInfo(state);
872 } catch (RemoteException e) {
873 }
874 }
875 return null;
876 }
877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 public boolean setRadios(boolean turnOn) {
879 boolean result = true;
880 enforceChangePermission();
881 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700882 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
884 return result;
885 }
886
887 public boolean setRadio(int netType, boolean turnOn) {
888 enforceChangePermission();
889 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
890 return false;
891 }
892 NetworkStateTracker tracker = mNetTrackers[netType];
893 return tracker != null && tracker.setRadio(turnOn);
894 }
895
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700896 /**
897 * Used to notice when the calling process dies so we can self-expire
898 *
899 * Also used to know if the process has cleaned up after itself when
900 * our auto-expire timer goes off. The timer has a link to an object.
901 *
902 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700903 private class FeatureUser implements IBinder.DeathRecipient {
904 int mNetworkType;
905 String mFeature;
906 IBinder mBinder;
907 int mPid;
908 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800909 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700910
911 FeatureUser(int type, String feature, IBinder binder) {
912 super();
913 mNetworkType = type;
914 mFeature = feature;
915 mBinder = binder;
916 mPid = getCallingPid();
917 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800918 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700919
Robert Greenwalt42acef32009-08-12 16:08:25 -0700920 try {
921 mBinder.linkToDeath(this, 0);
922 } catch (RemoteException e) {
923 binderDied();
924 }
925 }
926
927 void unlinkDeathRecipient() {
928 mBinder.unlinkToDeath(this, 0);
929 }
930
931 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800932 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800933 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
934 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700935 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700936 }
937
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700938 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700939 if (VDBG) {
940 log("ConnectivityService FeatureUser expire(" +
941 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
942 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
943 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700944 stopUsingNetworkFeature(this, false);
945 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800946
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500947 public boolean isSameUser(FeatureUser u) {
948 if (u == null) return false;
949
950 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
951 }
952
953 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
954 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
955 TextUtils.equals(mFeature, feature)) {
956 return true;
957 }
958 return false;
959 }
960
Robert Greenwaltb9285352009-12-21 18:24:07 -0800961 public String toString() {
962 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
963 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
964 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700965 }
966
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700967 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700968 public int startUsingNetworkFeature(int networkType, String feature,
969 IBinder binder) {
Wink Savillec9acde92011-09-21 11:05:43 -0700970 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800971 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700974 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700975 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700976 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700978
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700979 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700980
repo syncaea743a2011-07-29 23:55:49 -0700981 // TODO - move this into individual networktrackers
982 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -0700983
984 if (mProtectedNetworks.contains(usedNetworkType)) {
985 enforceConnectivityInternalPermission();
986 }
987
Robert Greenwalt42acef32009-08-12 16:08:25 -0700988 NetworkStateTracker network = mNetTrackers[usedNetworkType];
989 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800990 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700991 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700992 NetworkInfo ni = network.getNetworkInfo();
993
994 if (ni.isAvailable() == false) {
Robert Greenwalte32e8122010-12-29 14:35:21 -0800995 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
Wink Savillec7d7eaf2012-01-25 13:47:54 -0800996 if (DBG) log("special network not available ni=" + ni.getTypeName());
Robert Greenwalte32e8122010-12-29 14:35:21 -0800997 return Phone.APN_TYPE_NOT_AVAILABLE;
998 } else {
999 // else make the attempt anyway - probably giving REQUEST_STARTED below
Wink Savillec7d7eaf2012-01-25 13:47:54 -08001000 if (DBG) {
1001 log("special network not available, but try anyway ni=" +
1002 ni.getTypeName());
1003 }
Robert Greenwalte32e8122010-12-29 14:35:21 -08001004 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001005 }
1006
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001007 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1008
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001009 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001010 boolean addToList = true;
1011 if (restoreTimer < 0) {
1012 // In case there is no timer is specified for the feature,
1013 // make sure we don't add duplicate entry with the same request.
1014 for (FeatureUser u : mFeatureUsers) {
1015 if (u.isSameUser(f)) {
1016 // Duplicate user is found. Do not add.
1017 addToList = false;
1018 break;
1019 }
1020 }
1021 }
1022
1023 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001024 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1025 // this gets used for per-pid dns when connected
1026 mNetRequestersPids[usedNetworkType].add(currentPid);
1027 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001028 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001029
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001030 if (restoreTimer >= 0) {
1031 mHandler.sendMessageDelayed(
1032 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1033 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001034
Robert Greenwalta64bf832009-08-19 20:19:33 -07001035 if ((ni.isConnectedOrConnecting() == true) &&
1036 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001037 if (ni.isConnected() == true) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001038 final long token = Binder.clearCallingIdentity();
1039 try {
1040 // add the pid-specific dns
1041 handleDnsConfigurationChange(usedNetworkType);
1042 if (VDBG) log("special network already active");
1043 } finally {
1044 Binder.restoreCallingIdentity(token);
1045 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001046 return Phone.APN_ALREADY_ACTIVE;
1047 }
Wink Savillec9acde92011-09-21 11:05:43 -07001048 if (VDBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001049 return Phone.APN_REQUEST_STARTED;
1050 }
1051
1052 // check if the radio in play can make another contact
1053 // assume if cannot for now
1054
Wink Savillec9acde92011-09-21 11:05:43 -07001055 if (DBG) {
1056 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1057 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001058 network.reconnect();
1059 return Phone.APN_REQUEST_STARTED;
1060 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001061 // need to remember this unsupported request so we respond appropriately on stop
1062 synchronized(this) {
1063 mFeatureUsers.add(f);
1064 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1065 // this gets used for per-pid dns when connected
1066 mNetRequestersPids[usedNetworkType].add(currentPid);
1067 }
1068 }
Robert Greenwalt02648a42010-05-18 10:52:51 -07001069 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001070 }
1071 }
1072 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001075 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001077 enforceChangePermission();
1078
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001079 int pid = getCallingPid();
1080 int uid = getCallingUid();
1081
1082 FeatureUser u = null;
1083 boolean found = false;
1084
1085 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001086 for (FeatureUser x : mFeatureUsers) {
1087 if (x.isSameUser(pid, uid, networkType, feature)) {
1088 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001089 found = true;
1090 break;
1091 }
1092 }
1093 }
1094 if (found && u != null) {
1095 // stop regardless of how many other time this proc had called start
1096 return stopUsingNetworkFeature(u, true);
1097 } else {
1098 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001099 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001100 return 1;
1101 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001102 }
1103
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001104 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1105 int networkType = u.mNetworkType;
1106 String feature = u.mFeature;
1107 int pid = u.mPid;
1108 int uid = u.mUid;
1109
1110 NetworkStateTracker tracker = null;
1111 boolean callTeardown = false; // used to carry our decision outside of sync block
1112
Wink Savillec9acde92011-09-21 11:05:43 -07001113 if (VDBG) {
1114 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001115 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001118 if (DBG) {
1119 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1120 ", net is invalid");
1121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 return -1;
1123 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001124
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001125 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1126 // sync block
1127 synchronized(this) {
1128 // check if this process still has an outstanding start request
1129 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001130 if (VDBG) {
1131 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1132 ", ignoring");
1133 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001134 return 1;
1135 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001136 u.unlinkDeathRecipient();
1137 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1138 // If we care about duplicate requests, check for that here.
1139 //
1140 // This is done to support the extension of a request - the app
1141 // can request we start the network feature again and renew the
1142 // auto-shutoff delay. Normal "stop" calls from the app though
1143 // do not pay attention to duplicate requests - in effect the
1144 // API does not refcount and a single stop will counter multiple starts.
1145 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001146 for (FeatureUser x : mFeatureUsers) {
1147 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001148 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001149 return 1;
1150 }
1151 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001152 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001153
repo syncaea743a2011-07-29 23:55:49 -07001154 // TODO - move to individual network trackers
1155 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1156
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001157 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001158 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001159 if (DBG) {
1160 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1161 " no known tracker for used net type " + usedNetworkType);
1162 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001163 return -1;
1164 }
1165 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001166 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001167 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001168 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001169 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001170 if (VDBG) {
1171 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1172 " others still using it");
1173 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001174 return 1;
1175 }
1176 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001177 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001178 if (DBG) {
1179 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1180 " not a known feature - dropping");
1181 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001182 }
1183 }
Wink Savillec9acde92011-09-21 11:05:43 -07001184
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001185 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001186 if (DBG) {
1187 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1188 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001189 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001190 return 1;
1191 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001192 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
1195
1196 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001197 * @deprecated use requestRouteToHostAddress instead
1198 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 * Ensure that a network route exists to deliver traffic to the specified
1200 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001201 * @param networkType the type of the network over which traffic to the
1202 * specified host is to be routed
1203 * @param hostAddress the IP address of the host to which the route is
1204 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 * @return {@code true} on success, {@code false} on failure
1206 */
1207 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001208 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1209
1210 if (inetAddress == null) {
1211 return false;
1212 }
1213
1214 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1215 }
1216
1217 /**
1218 * Ensure that a network route exists to deliver traffic to the specified
1219 * host via the specified network interface.
1220 * @param networkType the type of the network over which traffic to the
1221 * specified host is to be routed
1222 * @param hostAddress the IP address of the host to which the route is
1223 * desired
1224 * @return {@code true} on success, {@code false} on failure
1225 */
1226 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001228 if (mProtectedNetworks.contains(networkType)) {
1229 enforceConnectivityInternalPermission();
1230 }
1231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001233 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 return false;
1235 }
1236 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001237
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001238 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1239 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001240 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001241 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001242 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001243 }
1244 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001246 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001247 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001248 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001249 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001250 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001251 } catch (UnknownHostException e) {
1252 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1253 } finally {
1254 Binder.restoreCallingIdentity(token);
1255 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001256 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001257 }
1258
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001259 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1260 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001261 }
1262
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001263 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1264 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001265 }
1266
Robert Greenwaltad55d352011-07-22 11:55:33 -07001267 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001268 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001269 }
1270
1271 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001272 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001273 }
1274
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001275 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1276 boolean toDefaultTable) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001277 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1278 if (bestRoute == null) {
1279 bestRoute = RouteInfo.makeHostRoute(addr);
1280 } else {
1281 if (bestRoute.getGateway().equals(addr)) {
1282 // if there is no better route, add the implied hostroute for our gateway
1283 bestRoute = RouteInfo.makeHostRoute(addr);
1284 } else {
1285 // if we will connect to this through another route, add a direct route
1286 // to it's gateway
1287 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1288 }
1289 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001290 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001291 }
1292
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001293 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001294 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001295 if ((ifaceName == null) || (lp == null) || (r == null)) {
1296 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1297 return false;
1298 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001299
1300 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001301 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001302 return false;
1303 }
1304
1305 if (r.isHostRoute() == false) {
1306 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1307 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001308 if (bestRoute.getGateway().equals(r.getGateway())) {
1309 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001310 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001311 } else {
1312 // if we will connect to our gateway through another route, add a direct
1313 // route to it's gateway
1314 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001315 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001316 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001317 }
1318 }
1319 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001320 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001321 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001322 if (toDefaultTable) {
1323 mAddedRoutes.add(r); // only track default table - only one apps can effect
1324 mNetd.addRoute(ifaceName, r);
1325 } else {
1326 mNetd.addSecondaryRoute(ifaceName, r);
1327 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001328 } catch (Exception e) {
1329 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001330 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001331 return false;
1332 }
1333 } else {
1334 // if we remove this one and there are no more like it, then refcount==0 and
1335 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001336 if (toDefaultTable) {
1337 mAddedRoutes.remove(r);
1338 if (mAddedRoutes.contains(r) == false) {
1339 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1340 try {
1341 mNetd.removeRoute(ifaceName, r);
1342 } catch (Exception e) {
1343 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001344 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001345 return false;
1346 }
1347 } else {
1348 if (VDBG) log("not removing " + r + " as it's still in use");
1349 }
1350 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001351 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001352 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001353 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001354 } catch (Exception e) {
1355 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001356 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001357 return false;
1358 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001359 }
1360 }
1361 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363
1364 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001365 * @see ConnectivityManager#getMobileDataEnabled()
1366 */
1367 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001368 // TODO: This detail should probably be in DataConnectionTracker's
1369 // which is where we store the value and maybe make this
1370 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001371 enforceAccessPermission();
1372 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1373 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001374 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001375 return retVal;
1376 }
1377
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001378 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001379 enforceConnectivityInternalPermission();
1380
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001381 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1382 (met ? ENABLED : DISABLED), networkType));
1383 }
1384
1385 private void handleSetDependencyMet(int networkType, boolean met) {
1386 if (mNetTrackers[networkType] != null) {
1387 if (DBG) {
1388 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1389 }
1390 mNetTrackers[networkType].setDependencyMet(met);
1391 }
1392 }
1393
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1395 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001396 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001398 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001399
1400 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001401 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001402 }
1403
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001404 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001405 // skip update when we've already applied rules
1406 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1407 if (oldRules == uidRules) return;
1408
1409 mUidRules.put(uid, uidRules);
1410 }
1411
1412 // TODO: dispatch into NMS to push rules towards kernel module
1413 // TODO: notify UID when it has requested targeted updates
1414 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001415
1416 @Override
1417 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1418 // only someone like NPMS should only be calling us
1419 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1420
1421 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001422 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001423 }
1424
1425 synchronized (mRulesLock) {
1426 mMeteredIfaces.clear();
1427 for (String iface : meteredIfaces) {
1428 mMeteredIfaces.add(iface);
1429 }
1430 }
1431 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001432 };
1433
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001434 /**
1435 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1436 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001437 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001438 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001439 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001440
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001441 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001442 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001443 }
1444
1445 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001446 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001447 if (VDBG) {
1448 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001449 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001450 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1451 }
tk.munb97d34c2012-01-06 10:43:52 +09001452 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1453 if (VDBG) {
1454 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1455 }
1456 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1457 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001458 }
1459
1460 @Override
1461 public void setPolicyDataEnable(int networkType, boolean enabled) {
1462 // only someone like NPMS should only be calling us
1463 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1464
1465 mHandler.sendMessage(mHandler.obtainMessage(
1466 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1467 }
1468
1469 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1470 if (isNetworkTypeValid(networkType)) {
1471 final NetworkStateTracker tracker = mNetTrackers[networkType];
1472 if (tracker != null) {
1473 tracker.setPolicyDataEnable(enabled);
1474 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001475 }
1476 }
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001479 mContext.enforceCallingOrSelfPermission(
1480 android.Manifest.permission.ACCESS_NETWORK_STATE,
1481 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483
1484 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001485 mContext.enforceCallingOrSelfPermission(
1486 android.Manifest.permission.CHANGE_NETWORK_STATE,
1487 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001490 // TODO Make this a special check when it goes public
1491 private void enforceTetherChangePermission() {
1492 mContext.enforceCallingOrSelfPermission(
1493 android.Manifest.permission.CHANGE_NETWORK_STATE,
1494 "ConnectivityService");
1495 }
1496
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001497 private void enforceTetherAccessPermission() {
1498 mContext.enforceCallingOrSelfPermission(
1499 android.Manifest.permission.ACCESS_NETWORK_STATE,
1500 "ConnectivityService");
1501 }
1502
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001503 private void enforceConnectivityInternalPermission() {
1504 mContext.enforceCallingOrSelfPermission(
1505 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1506 "ConnectivityService");
1507 }
1508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001510 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1511 * network, we ignore it. If it is for the active network, we send out a
1512 * broadcast. But first, we check whether it might be possible to connect
1513 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 * @param info the {@code NetworkInfo} for the network
1515 */
1516 private void handleDisconnect(NetworkInfo info) {
1517
Robert Greenwalt42acef32009-08-12 16:08:25 -07001518 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519
Robert Greenwalt42acef32009-08-12 16:08:25 -07001520 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 /*
1522 * If the disconnected network is not the active one, then don't report
1523 * this as a loss of connectivity. What probably happened is that we're
1524 * getting the disconnect for a network that we explicitly disabled
1525 * in accordance with network preference policies.
1526 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001527 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001528 List pids = mNetRequestersPids[prevNetType];
1529 for (int i = 0; i<pids.size(); i++) {
1530 Integer pid = (Integer)pids.get(i);
1531 // will remove them because the net's no longer connected
1532 // need to do this now as only now do we know the pids and
1533 // can properly null things that are no longer referenced.
1534 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1539 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1540 if (info.isFailover()) {
1541 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1542 info.setFailover(false);
1543 }
1544 if (info.getReason() != null) {
1545 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1546 }
1547 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001548 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1549 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001551
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001552 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001553 tryFailover(prevNetType);
1554 if (mActiveDefaultNetwork != -1) {
1555 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001556 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1557 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001558 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001559 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1560 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001561 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001562 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001563
1564 // Reset interface if no other connections are using the same interface
1565 boolean doReset = true;
1566 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1567 if (linkProperties != null) {
1568 String oldIface = linkProperties.getInterfaceName();
1569 if (TextUtils.isEmpty(oldIface) == false) {
1570 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1571 if (networkStateTracker == null) continue;
1572 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1573 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1574 LinkProperties l = networkStateTracker.getLinkProperties();
1575 if (l == null) continue;
1576 if (oldIface.equals(l.getInterfaceName())) {
1577 doReset = false;
1578 break;
1579 }
1580 }
1581 }
1582 }
1583 }
1584
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001585 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001586 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001587
Jeff Sharkey961e3042011-08-29 16:02:57 -07001588 final Intent immediateIntent = new Intent(intent);
1589 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1590 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001591 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001592 /*
1593 * If the failover network is already connected, then immediately send
1594 * out a followup broadcast indicating successful failover
1595 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001596 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001597 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1598 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001599 }
1600 }
1601
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001602 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001603 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001604 * If this is a default network, check if other defaults are available.
1605 * Try to reconnect on all available and let them hash it out when
1606 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001607 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001608 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001609 if (mActiveDefaultNetwork == prevNetType) {
1610 mActiveDefaultNetwork = -1;
1611 }
1612
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001613 // don't signal a reconnect for anything lower or equal priority than our
1614 // current connected default
1615 // TODO - don't filter by priority now - nice optimization but risky
1616// int currentPriority = -1;
1617// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001618// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001619// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001620 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001621 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001622 if (mNetConfigs[checkType] == null) continue;
1623 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001624 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001625
1626// Enabling the isAvailable() optimization caused mobile to not get
1627// selected if it was in the middle of error handling. Specifically
1628// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1629// would not be available and we wouldn't get connected to anything.
1630// So removing the isAvailable() optimization below for now. TODO: This
1631// optimization should work and we need to investigate why it doesn't work.
1632// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1633// complete before it is really complete.
1634// if (!mNetTrackers[checkType].isAvailable()) continue;
1635
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001636// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001637
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001638 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1639 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1640 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1641 checkInfo.setFailover(true);
1642 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001643 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001644 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648
1649 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001650 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1651 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001652 }
1653
Wink Saville628b0852011-08-04 15:01:58 -07001654 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001655 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1656 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001657 }
1658
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001659 private void sendInetConditionBroadcast(NetworkInfo info) {
1660 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1661 }
1662
Wink Saville628b0852011-08-04 15:01:58 -07001663 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001664 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1666 if (info.isFailover()) {
1667 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1668 info.setFailover(false);
1669 }
1670 if (info.getReason() != null) {
1671 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1672 }
1673 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001674 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1675 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001677 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001678 return intent;
1679 }
1680
1681 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1682 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1683 }
1684
1685 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1686 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688
1689 /**
1690 * Called when an attempt to fail over to another network has failed.
1691 * @param info the {@link NetworkInfo} for the failed network
1692 */
1693 private void handleConnectionFailure(NetworkInfo info) {
1694 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695
Robert Greenwalt42acef32009-08-12 16:08:25 -07001696 String reason = info.getReason();
1697 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001698
Robert Greenwalt572172b2010-10-08 16:35:52 -07001699 String reasonText;
1700 if (reason == null) {
1701 reasonText = ".";
1702 } else {
1703 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001705 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001706
1707 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1708 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1709 if (getActiveNetworkInfo() == null) {
1710 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1711 }
1712 if (reason != null) {
1713 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1714 }
1715 if (extraInfo != null) {
1716 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1717 }
1718 if (info.isFailover()) {
1719 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1720 info.setFailover(false);
1721 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001722
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001723 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001724 tryFailover(info.getType());
1725 if (mActiveDefaultNetwork != -1) {
1726 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001727 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1728 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001729 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001730 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1731 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001732 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001733
Robert Greenwalt029be812010-09-20 18:01:43 -07001734 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001735
1736 final Intent immediateIntent = new Intent(intent);
1737 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1738 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001739 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001740 /*
1741 * If the failover network is already connected, then immediately send
1742 * out a followup broadcast indicating successful failover
1743 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001744 if (mActiveDefaultNetwork != -1) {
1745 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001746 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001747 }
1748
1749 private void sendStickyBroadcast(Intent intent) {
1750 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001751 if (!mSystemReady) {
1752 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001753 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001754 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001755 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001756 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001757 }
1758
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001759 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001760 }
1761 }
1762
Wink Saville628b0852011-08-04 15:01:58 -07001763 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1764 if (delayMs <= 0) {
1765 sendStickyBroadcast(intent);
1766 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001767 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001768 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1769 + intent.getAction());
1770 }
Wink Saville628b0852011-08-04 15:01:58 -07001771 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1772 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1773 }
1774 }
1775
Mike Lockwood0f79b542009-08-14 14:18:49 -04001776 void systemReady() {
1777 synchronized(this) {
1778 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001779 if (mInitialBroadcast != null) {
1780 mContext.sendStickyBroadcast(mInitialBroadcast);
1781 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001782 }
1783 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001784 // load the global proxy at startup
1785 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787
1788 private void handleConnect(NetworkInfo info) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001789 final int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790
1791 // snapshot isFailover, because sendConnectedBroadcast() resets it
1792 boolean isFailover = info.isFailover();
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001793 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794
Robert Greenwalt42acef32009-08-12 16:08:25 -07001795 // if this is a default net and other default is running
1796 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001797 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1799 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001800 mNetConfigs[mActiveDefaultNetwork].priority >
1801 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001802 mNetworkPreference == mActiveDefaultNetwork) {
1803 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001804 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001805 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001806 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001807 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001808 teardown(thisNet);
1809 return;
1810 } else {
1811 // tear down the other
1812 NetworkStateTracker otherNet =
1813 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001814 if (DBG) {
1815 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001816 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001817 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001818 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001819 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001820 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001821 return;
1822 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001823 }
1824 }
1825 synchronized (ConnectivityService.this) {
1826 // have a new default network, release the transition wakelock in a second
1827 // if it's held. The second pause is to allow apps to reconnect over the
1828 // new network
1829 if (mNetTransitionWakeLock.isHeld()) {
1830 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001831 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001832 mNetTransitionWakeLockSerialNumber, 0),
1833 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001834 }
1835 }
1836 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001837 // this will cause us to come up initially as unconnected and switching
1838 // to connected after our normal pause unless somebody reports us as reall
1839 // disconnected
1840 mDefaultInetConditionPublished = 0;
1841 mDefaultConnectionSequence++;
1842 mInetConditionChangeInFlight = false;
1843 // Don't do this - if we never sign in stay, grey
1844 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001847 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001848 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001849 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001850
1851 // notify battery stats service about this network
1852 final String iface = thisNet.getLinkProperties().getInterfaceName();
1853 if (iface != null) {
1854 try {
1855 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1856 } catch (RemoteException e) {
1857 // ignored; service lives in system_server
1858 }
1859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001863 * After a change in the connectivity state of a network. We're mainly
1864 * concerned with making sure that the list of DNS servers is set up
1865 * according to which networks are connected, and ensuring that the
1866 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001868 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001869 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001872 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001873 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001875 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001876
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001877 LinkProperties curLp = mCurrentLinkProperties[netType];
1878 LinkProperties newLp = null;
1879
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001880 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001881 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001882 if (VDBG) {
1883 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1884 " doReset=" + doReset + " resetMask=" + resetMask +
1885 "\n curLp=" + curLp +
1886 "\n newLp=" + newLp);
1887 }
1888
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001889 if (curLp != null) {
1890 if (curLp.isIdenticalInterfaceName(newLp)) {
1891 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1892 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1893 for (LinkAddress linkAddr : car.removed) {
1894 if (linkAddr.getAddress() instanceof Inet4Address) {
1895 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1896 }
1897 if (linkAddr.getAddress() instanceof Inet6Address) {
1898 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1899 }
Wink Savillee8222252011-07-13 13:44:13 -07001900 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001901 if (DBG) {
1902 log("handleConnectivityChange: addresses changed" +
1903 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1904 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001905 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001906 } else {
1907 if (DBG) {
1908 log("handleConnectivityChange: address are the same reset per doReset" +
1909 " linkProperty[" + netType + "]:" +
1910 " resetMask=" + resetMask);
1911 }
Wink Savillee8222252011-07-13 13:44:13 -07001912 }
1913 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001914 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001915 if (DBG) {
1916 log("handleConnectivityChange: interface not not equivalent reset both" +
1917 " linkProperty[" + netType + "]:" +
1918 " resetMask=" + resetMask);
1919 }
Wink Savillee8222252011-07-13 13:44:13 -07001920 }
Wink Savillee8222252011-07-13 13:44:13 -07001921 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001922 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07001923 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001924 }
1925 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001926 if (VDBG) {
1927 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1928 " doReset=" + doReset + " resetMask=" + resetMask +
1929 "\n curLp=" + curLp +
1930 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001933 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001934 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001935
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001936 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001937 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1938 if (linkProperties != null) {
1939 String iface = linkProperties.getInterfaceName();
1940 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001941 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001942 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1943 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001944
1945 // Tell VPN the interface is down. It is a temporary
1946 // but effective fix to make VPN aware of the change.
1947 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1948 mVpn.interfaceStatusChanged(iface, false);
1949 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001950 }
1951 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07001952 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001953 try {
1954 mNetd.flushInterfaceDnsCache(iface);
1955 } catch (Exception e) {
1956 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001957 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001958 }
1959 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001960 }
1961 }
1962 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001963
1964 // TODO: Temporary notifying upstread change to Tethering.
1965 // @see bug/4455071
1966 /** Notify TetheringService if interface name has been changed. */
1967 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1968 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1969 if (isTetheringSupported()) {
1970 mTethering.handleTetherIfaceChange();
1971 }
1972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001975 /**
1976 * Add and remove routes using the old properties (null if not previously connected),
1977 * new properties (null if becoming disconnected). May even be double null, which
1978 * is a noop.
1979 * Uses isLinkDefault to determine if default routes should be set or conversely if
1980 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07001981 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001982 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07001983 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1984 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001985 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001986 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1987 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001988 if (curLp != null) {
1989 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001990 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001991 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001992 } else if (newLp != null) {
1993 routeDiff.added = newLp.getRoutes();
1994 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001995 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001996
Robert Greenwaltf125a092011-08-15 12:31:55 -07001997 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1998
Robert Greenwaltad55d352011-07-22 11:55:33 -07001999 for (RouteInfo r : routeDiff.removed) {
2000 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002001 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2002 }
2003 if (isLinkDefault == false) {
2004 // remove from a secondary route table
2005 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002006 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002007 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002008
Robert Greenwaltad55d352011-07-22 11:55:33 -07002009 for (RouteInfo r : routeDiff.added) {
2010 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002011 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002012 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002013 // add to a secondary route table
2014 addRoute(newLp, r, TO_SECONDARY_TABLE);
2015
Robert Greenwalte6b24292011-08-09 16:52:58 -07002016 // many radios add a default route even when we don't want one.
2017 // remove the default route unless somebody else has asked for it
2018 String ifaceName = newLp.getInterfaceName();
2019 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002020 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002021 try {
2022 mNetd.removeRoute(ifaceName, r);
2023 } catch (Exception e) {
2024 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08002025 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002026 }
2027 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002028 }
2029 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002030
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002031 if (!isLinkDefault) {
2032 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002033 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002034 // routes changed - remove all old dns entries and add new
2035 if (curLp != null) {
2036 for (InetAddress oldDns : curLp.getDnses()) {
2037 removeRouteToAddress(curLp, oldDns);
2038 }
2039 }
2040 if (newLp != null) {
2041 for (InetAddress newDns : newLp.getDnses()) {
2042 addRouteToAddress(newLp, newDns);
2043 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002044 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002045 } else {
2046 // no change in routes, check for change in dns themselves
2047 for (InetAddress oldDns : dnsDiff.removed) {
2048 removeRouteToAddress(curLp, oldDns);
2049 }
2050 for (InetAddress newDns : dnsDiff.added) {
2051 addRouteToAddress(newLp, newDns);
2052 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002053 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002054 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002055 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002056 }
2057
2058
Irfan Sheriffd649c122010-06-09 15:39:36 -07002059 /**
2060 * Reads the network specific TCP buffer sizes from SystemProperties
2061 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2062 * wide use
2063 */
2064 public void updateNetworkSettings(NetworkStateTracker nt) {
2065 String key = nt.getTcpBufferSizesPropName();
2066 String bufferSizes = SystemProperties.get(key);
2067
2068 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002069 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002070
2071 // Setting to default values so we won't be stuck to previous values
2072 key = "net.tcp.buffersize.default";
2073 bufferSizes = SystemProperties.get(key);
2074 }
2075
2076 // Set values in kernel
2077 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002078 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002079 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002080 + "] which comes from [" + key + "]");
2081 }
2082 setBufferSize(bufferSizes);
2083 }
2084 }
2085
2086 /**
2087 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2088 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2089 *
2090 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2091 * writeMin, writeInitial, writeMax"
2092 */
2093 private void setBufferSize(String bufferSizes) {
2094 try {
2095 String[] values = bufferSizes.split(",");
2096
2097 if (values.length == 6) {
2098 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002099 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2100 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2101 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2102 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2103 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2104 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002105 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002106 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002107 }
2108 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002109 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002110 }
2111 }
2112
Robert Greenwalt42acef32009-08-12 16:08:25 -07002113 /**
2114 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2115 * on the highest priority active net which this process requested.
2116 * If there aren't any, clear it out
2117 */
2118 private void reassessPidDns(int myPid, boolean doBump)
2119 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002120 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002121 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002122 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002123 continue;
2124 }
2125 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002126 if (nt.getNetworkInfo().isConnected() &&
2127 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002128 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002129 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002130 List pids = mNetRequestersPids[i];
2131 for (int j=0; j<pids.size(); j++) {
2132 Integer pid = (Integer)pids.get(j);
2133 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002134 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002135 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002136 if (doBump) {
2137 bumpDns();
2138 }
2139 return;
2140 }
2141 }
2142 }
2143 }
2144 // nothing found - delete
2145 for (int i = 1; ; i++) {
2146 String prop = "net.dns" + i + "." + myPid;
2147 if (SystemProperties.get(prop).length() == 0) {
2148 if (doBump) {
2149 bumpDns();
2150 }
2151 return;
2152 }
2153 SystemProperties.set(prop, "");
2154 }
2155 }
2156
Robert Greenwalt10398722010-12-17 15:20:36 -08002157 // return true if results in a change
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002158 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002159 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002160 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002161 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002162 String dnsString = dns.getHostAddress();
2163 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2164 changed = true;
2165 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2166 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002167 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002168 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002169 }
2170
2171 private void bumpDns() {
2172 /*
2173 * Bump the property that tells the name resolver library to reread
2174 * the DNS server list from the properties.
2175 */
2176 String propVal = SystemProperties.get("net.dnschange");
2177 int n = 0;
2178 if (propVal.length() != 0) {
2179 try {
2180 n = Integer.parseInt(propVal);
2181 } catch (NumberFormatException e) {}
2182 }
2183 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002184 /*
2185 * Tell the VMs to toss their DNS caches
2186 */
2187 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2188 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002189 /*
2190 * Connectivity events can happen before boot has completed ...
2191 */
2192 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002193 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002194 }
2195
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002196 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002197 private boolean updateDns(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002198 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002199 boolean changed = false;
2200 int last = 0;
2201 if (dnses.size() == 0 && mDefaultDns != null) {
2202 ++last;
2203 String value = mDefaultDns.getHostAddress();
2204 if (!value.equals(SystemProperties.get("net.dns1"))) {
2205 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002206 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002207 }
2208 changed = true;
2209 SystemProperties.set("net.dns1", value);
2210 }
2211 } else {
2212 for (InetAddress dns : dnses) {
2213 ++last;
2214 String key = "net.dns" + last;
2215 String value = dns.getHostAddress();
2216 if (!changed && value.equals(SystemProperties.get(key))) {
2217 continue;
2218 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002219 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002220 log("adding dns " + value + " for " + network);
2221 }
2222 changed = true;
2223 SystemProperties.set(key, value);
2224 }
2225 }
2226 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2227 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002228 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002229 changed = true;
2230 SystemProperties.set(key, "");
2231 }
2232 mNumDnsEntries = last;
2233
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002234 if (changed) {
2235 try {
2236 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2237 mNetd.setDefaultInterfaceForDns(iface);
2238 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002239 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002240 }
2241 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002242 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2243 SystemProperties.set("net.dns.search", domains);
2244 changed = true;
2245 }
2246 return changed;
2247 }
2248
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002249 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002250 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002251 NetworkStateTracker nt = mNetTrackers[netType];
2252 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002253 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002254 if (p == null) return;
2255 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002256 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002257 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002258 String network = nt.getNetworkInfo().getTypeName();
2259 synchronized (mDnsLock) {
2260 if (!mDnsOverridden) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002261 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002262 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002263 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002264 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002265 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002266 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002267 NetworkUtils.makeStrings(dnses));
2268 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002269 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002270 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002271 // set per-pid dns for attached secondary nets
2272 List pids = mNetRequestersPids[netType];
2273 for (int y=0; y< pids.size(); y++) {
2274 Integer pid = (Integer)pids.get(y);
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002275 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 }
2277 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002278 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002280 }
2281
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002282 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002283 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2284 NETWORK_RESTORE_DELAY_PROP_NAME);
2285 if(restoreDefaultNetworkDelayStr != null &&
2286 restoreDefaultNetworkDelayStr.length() != 0) {
2287 try {
2288 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2289 } catch (NumberFormatException e) {
2290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002292 // if the system property isn't set, use the value for the apn type
2293 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2294
2295 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2296 (mNetConfigs[networkType] != null)) {
2297 ret = mNetConfigs[networkType].restoreTime;
2298 }
2299 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 }
2301
2302 @Override
2303 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002304 if (mContext.checkCallingOrSelfPermission(
2305 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002307 pw.println("Permission Denial: can't dump ConnectivityService " +
2308 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2309 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 return;
2311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 pw.println();
2313 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002314 if (nst != null) {
2315 if (nst.getNetworkInfo().isConnected()) {
2316 pw.println("Active network: " + nst.getNetworkInfo().
2317 getTypeName());
2318 }
2319 pw.println(nst.getNetworkInfo());
2320 pw.println(nst);
2321 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002324
2325 pw.println("Network Requester Pids:");
2326 for (int net : mPriorityList) {
2327 String pidString = net + ": ";
2328 for (Object pid : mNetRequestersPids[net]) {
2329 pidString = pidString + pid.toString() + ", ";
2330 }
2331 pw.println(pidString);
2332 }
2333 pw.println();
2334
2335 pw.println("FeatureUsers:");
2336 for (Object requester : mFeatureUsers) {
2337 pw.println(requester.toString());
2338 }
2339 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002340
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002341 synchronized (this) {
2342 pw.println("NetworkTranstionWakeLock is currently " +
2343 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2344 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2345 }
2346 pw.println();
2347
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002348 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002349
2350 if (mInetLog != null) {
2351 pw.println();
2352 pw.println("Inet condition reports:");
2353 for(int i = 0; i < mInetLog.size(); i++) {
2354 pw.println(mInetLog.get(i));
2355 }
2356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
2358
Robert Greenwalt42acef32009-08-12 16:08:25 -07002359 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002361 public MyHandler(Looper looper) {
2362 super(looper);
2363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 @Override
2366 public void handleMessage(Message msg) {
2367 NetworkInfo info;
2368 switch (msg.what) {
2369 case NetworkStateTracker.EVENT_STATE_CHANGED:
2370 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002371 int type = info.getType();
2372 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002373
Wink Savillec9acde92011-09-21 11:05:43 -07002374 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2375 (state == NetworkInfo.State.DISCONNECTED)) {
2376 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002377 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002378 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380
2381 // Connectivity state changed:
2382 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002383 // [12-9] Network subtype (for mobile network, as defined
2384 // by TelephonyManager)
2385 // [8-3] Detailed state ordinal (as defined by
2386 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 // [2-0] Network type (as defined by ConnectivityManager)
2388 int eventLogParam = (info.getType() & 0x7) |
2389 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2390 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002391 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002392 eventLogParam);
2393
2394 if (info.getDetailedState() ==
2395 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002397 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002399 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002401 // the logic here is, handle SUSPENDED the same as
2402 // DISCONNECTED. The only difference being we are
2403 // broadcasting an intent with NetworkInfo that's
2404 // suspended. This allows the applications an
2405 // opportunity to handle DISCONNECTED and SUSPENDED
2406 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002408 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 handleConnect(info);
2410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002413 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002414 // TODO: Temporary allowing network configuration
2415 // change not resetting sockets.
2416 // @see bug/4455071
2417 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002419 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002420 String causedBy = null;
2421 synchronized (ConnectivityService.this) {
2422 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2423 mNetTransitionWakeLock.isHeld()) {
2424 mNetTransitionWakeLock.release();
2425 causedBy = mNetTransitionWakeLockCausedBy;
2426 }
2427 }
2428 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002429 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002430 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002431 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002432 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002433 FeatureUser u = (FeatureUser)msg.obj;
2434 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002435 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002436 case EVENT_INET_CONDITION_CHANGE:
2437 {
2438 int netType = msg.arg1;
2439 int condition = msg.arg2;
2440 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002441 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002442 }
2443 case EVENT_INET_CONDITION_HOLD_END:
2444 {
2445 int netType = msg.arg1;
2446 int sequence = msg.arg2;
2447 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002448 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002449 }
2450 case EVENT_SET_NETWORK_PREFERENCE:
2451 {
2452 int preference = msg.arg1;
2453 handleSetNetworkPreference(preference);
2454 break;
2455 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002456 case EVENT_SET_MOBILE_DATA:
2457 {
2458 boolean enabled = (msg.arg1 == ENABLED);
2459 handleSetMobileData(enabled);
2460 break;
2461 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002462 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2463 {
2464 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002465 break;
2466 }
2467 case EVENT_SET_DEPENDENCY_MET:
2468 {
2469 boolean met = (msg.arg1 == ENABLED);
2470 handleSetDependencyMet(msg.arg2, met);
2471 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002472 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002473 case EVENT_RESTORE_DNS:
2474 {
2475 if (mActiveDefaultNetwork != -1) {
2476 handleDnsConfigurationChange(mActiveDefaultNetwork);
2477 }
2478 break;
2479 }
Wink Saville628b0852011-08-04 15:01:58 -07002480 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2481 {
2482 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002483 sendStickyBroadcast(intent);
2484 break;
2485 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002486 case EVENT_SET_POLICY_DATA_ENABLE: {
2487 final int networkType = msg.arg1;
2488 final boolean enabled = msg.arg2 == ENABLED;
2489 handleSetPolicyDataEnable(networkType, enabled);
2490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 }
2492 }
2493 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002494
2495 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002496 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002497 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002498
2499 if (isTetheringSupported()) {
2500 return mTethering.tether(iface);
2501 } else {
2502 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2503 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002504 }
2505
2506 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002507 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002508 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002509
2510 if (isTetheringSupported()) {
2511 return mTethering.untether(iface);
2512 } else {
2513 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2514 }
2515 }
2516
2517 // javadoc from interface
2518 public int getLastTetherError(String iface) {
2519 enforceTetherAccessPermission();
2520
2521 if (isTetheringSupported()) {
2522 return mTethering.getLastTetherError(iface);
2523 } else {
2524 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2525 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002526 }
2527
2528 // TODO - proper iface API for selection by property, inspection, etc
2529 public String[] getTetherableUsbRegexs() {
2530 enforceTetherAccessPermission();
2531 if (isTetheringSupported()) {
2532 return mTethering.getTetherableUsbRegexs();
2533 } else {
2534 return new String[0];
2535 }
2536 }
2537
2538 public String[] getTetherableWifiRegexs() {
2539 enforceTetherAccessPermission();
2540 if (isTetheringSupported()) {
2541 return mTethering.getTetherableWifiRegexs();
2542 } else {
2543 return new String[0];
2544 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002545 }
2546
Danica Chang6fdd0c62010-08-11 14:54:43 -07002547 public String[] getTetherableBluetoothRegexs() {
2548 enforceTetherAccessPermission();
2549 if (isTetheringSupported()) {
2550 return mTethering.getTetherableBluetoothRegexs();
2551 } else {
2552 return new String[0];
2553 }
2554 }
2555
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002556 public int setUsbTethering(boolean enable) {
2557 enforceTetherAccessPermission();
2558 if (isTetheringSupported()) {
2559 return mTethering.setUsbTethering(enable);
2560 } else {
2561 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2562 }
2563 }
2564
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002565 // TODO - move iface listing, queries, etc to new module
2566 // javadoc from interface
2567 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002568 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002569 return mTethering.getTetherableIfaces();
2570 }
2571
2572 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002573 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002574 return mTethering.getTetheredIfaces();
2575 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002576
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002577 @Override
2578 public String[] getTetheredIfacePairs() {
2579 enforceTetherAccessPermission();
2580 return mTethering.getTetheredIfacePairs();
2581 }
2582
Robert Greenwalt5a735062010-03-02 17:25:02 -08002583 public String[] getTetheringErroredIfaces() {
2584 enforceTetherAccessPermission();
2585 return mTethering.getErroredIfaces();
2586 }
2587
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002588 // if ro.tether.denied = true we default to no tethering
2589 // gservices could set the secure setting to 1 though to enable it on a build where it
2590 // had previously been turned off.
2591 public boolean isTetheringSupported() {
2592 enforceTetherAccessPermission();
2593 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002594 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2595 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2596 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002597 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002598
2599 // An API NetworkStateTrackers can call when they lose their network.
2600 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2601 // whichever happens first. The timer is started by the first caller and not
2602 // restarted by subsequent callers.
2603 public void requestNetworkTransitionWakelock(String forWhom) {
2604 enforceConnectivityInternalPermission();
2605 synchronized (this) {
2606 if (mNetTransitionWakeLock.isHeld()) return;
2607 mNetTransitionWakeLockSerialNumber++;
2608 mNetTransitionWakeLock.acquire();
2609 mNetTransitionWakeLockCausedBy = forWhom;
2610 }
2611 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002612 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002613 mNetTransitionWakeLockSerialNumber, 0),
2614 mNetTransitionWakeLockTimeout);
2615 return;
2616 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002617
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002618 // 100 percent is full good, 0 is full bad.
2619 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002620 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002621 mContext.enforceCallingOrSelfPermission(
2622 android.Manifest.permission.STATUS_BAR,
2623 "ConnectivityService");
2624
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002625 if (DBG) {
2626 int pid = getCallingPid();
2627 int uid = getCallingUid();
2628 String s = pid + "(" + uid + ") reports inet is " +
2629 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2630 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2631 mInetLog.add(s);
2632 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2633 mInetLog.remove(0);
2634 }
2635 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002636 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002637 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2638 }
2639
2640 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002641 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002642 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002643 return;
2644 }
2645 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002646 if (DBG) log("handleInetConditionChange: net=" + netType +
2647 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002648 return;
2649 }
Wink Savillec9acde92011-09-21 11:05:43 -07002650 if (VDBG) {
2651 log("handleInetConditionChange: net=" +
2652 netType + ", condition=" + condition +
2653 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2654 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002655 mDefaultInetCondition = condition;
2656 int delay;
2657 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002658 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002659 // setup a new hold to debounce this
2660 if (mDefaultInetCondition > 50) {
2661 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2662 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2663 } else {
2664 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2665 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2666 }
2667 mInetConditionChangeInFlight = true;
2668 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2669 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2670 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002671 // we've set the new condition, when this hold ends that will get picked up
2672 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002673 }
2674 }
2675
2676 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002677 if (DBG) {
2678 log("handleInetConditionHoldEnd: net=" + netType +
2679 ", condition=" + mDefaultInetCondition +
2680 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002681 }
2682 mInetConditionChangeInFlight = false;
2683
2684 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002685 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002686 return;
2687 }
2688 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002689 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002690 return;
2691 }
Wink Saville628b0852011-08-04 15:01:58 -07002692 // TODO: Figure out why this optimization sometimes causes a
2693 // change in mDefaultInetCondition to be missed and the
2694 // UI to not be updated.
2695 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2696 // if (DBG) log("no change in condition - aborting");
2697 // return;
2698 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002699 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2700 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002701 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002702 return;
2703 }
2704 mDefaultInetConditionPublished = mDefaultInetCondition;
2705 sendInetConditionBroadcast(networkInfo);
2706 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002707 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002708
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002709 public ProxyProperties getProxy() {
2710 synchronized (mDefaultProxyLock) {
2711 return mDefaultProxyDisabled ? null : mDefaultProxy;
2712 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002713 }
2714
2715 public void setGlobalProxy(ProxyProperties proxyProperties) {
2716 enforceChangePermission();
2717 synchronized (mGlobalProxyLock) {
2718 if (proxyProperties == mGlobalProxy) return;
2719 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2720 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2721
2722 String host = "";
2723 int port = 0;
2724 String exclList = "";
2725 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2726 mGlobalProxy = new ProxyProperties(proxyProperties);
2727 host = mGlobalProxy.getHost();
2728 port = mGlobalProxy.getPort();
2729 exclList = mGlobalProxy.getExclusionList();
2730 } else {
2731 mGlobalProxy = null;
2732 }
2733 ContentResolver res = mContext.getContentResolver();
2734 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2735 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002736 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002737 exclList);
2738 }
2739
2740 if (mGlobalProxy == null) {
2741 proxyProperties = mDefaultProxy;
2742 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07002743 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002744 }
2745
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002746 private void loadGlobalProxy() {
2747 ContentResolver res = mContext.getContentResolver();
2748 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2749 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2750 String exclList = Settings.Secure.getString(res,
2751 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2752 if (!TextUtils.isEmpty(host)) {
2753 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2754 synchronized (mGlobalProxyLock) {
2755 mGlobalProxy = proxyProperties;
2756 }
2757 }
2758 }
2759
Robert Greenwalt434203a2010-10-11 16:00:27 -07002760 public ProxyProperties getGlobalProxy() {
2761 synchronized (mGlobalProxyLock) {
2762 return mGlobalProxy;
2763 }
2764 }
2765
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002766 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2767 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2768 proxy = null;
2769 }
2770 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002771 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2772 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002773 mDefaultProxy = proxy;
2774
2775 if (!mDefaultProxyDisabled) {
2776 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002777 }
2778 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002779 }
2780
2781 private void handleDeprecatedGlobalHttpProxy() {
2782 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2783 Settings.Secure.HTTP_PROXY);
2784 if (!TextUtils.isEmpty(proxy)) {
2785 String data[] = proxy.split(":");
2786 String proxyHost = data[0];
2787 int proxyPort = 8080;
2788 if (data.length > 1) {
2789 try {
2790 proxyPort = Integer.parseInt(data[1]);
2791 } catch (NumberFormatException e) {
2792 return;
2793 }
2794 }
2795 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2796 setGlobalProxy(p);
2797 }
2798 }
2799
2800 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002801 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002802 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002803 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002804 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2805 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002806 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002807 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002808 }
2809
2810 private static class SettingsObserver extends ContentObserver {
2811 private int mWhat;
2812 private Handler mHandler;
2813 SettingsObserver(Handler handler, int what) {
2814 super(handler);
2815 mHandler = handler;
2816 mWhat = what;
2817 }
2818
2819 void observe(Context context) {
2820 ContentResolver resolver = context.getContentResolver();
2821 resolver.registerContentObserver(Settings.Secure.getUriFor(
2822 Settings.Secure.HTTP_PROXY), false, this);
2823 }
2824
2825 @Override
2826 public void onChange(boolean selfChange) {
2827 mHandler.obtainMessage(mWhat).sendToTarget();
2828 }
2829 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002830
2831 private void log(String s) {
2832 Slog.d(TAG, s);
2833 }
2834
2835 private void loge(String s) {
2836 Slog.e(TAG, s);
2837 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002838
repo syncaea743a2011-07-29 23:55:49 -07002839 int convertFeatureToNetworkType(int networkType, String feature) {
2840 int usedNetworkType = networkType;
2841
2842 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2843 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2844 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2845 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2846 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2847 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2848 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2849 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2850 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2851 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2852 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2853 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2854 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2855 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2856 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2857 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2858 } else {
2859 Slog.e(TAG, "Can't match any mobile netTracker!");
2860 }
2861 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2862 if (TextUtils.equals(feature, "p2p")) {
2863 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2864 } else {
2865 Slog.e(TAG, "Can't match any wifi netTracker!");
2866 }
2867 } else {
2868 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002869 }
repo syncaea743a2011-07-29 23:55:49 -07002870 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002871 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002872
2873 private static <T> T checkNotNull(T value, String message) {
2874 if (value == null) {
2875 throw new NullPointerException(message);
2876 }
2877 return value;
2878 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002879
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002880 /**
2881 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002882 * VpnBuilder and not available in ConnectivityManager. Permissions
2883 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002884 * @hide
2885 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002886 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002887 public boolean protectVpn(ParcelFileDescriptor socket) {
2888 try {
2889 int type = mActiveDefaultNetwork;
2890 if (ConnectivityManager.isNetworkTypeValid(type)) {
2891 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2892 return true;
2893 }
2894 } catch (Exception e) {
2895 // ignore
2896 } finally {
2897 try {
2898 socket.close();
2899 } catch (Exception e) {
2900 // ignore
2901 }
2902 }
2903 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002904 }
2905
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002906 /**
2907 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002908 * and not available in ConnectivityManager. Permissions are checked
2909 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002910 * @hide
2911 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002912 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002913 public boolean prepareVpn(String oldPackage, String newPackage) {
2914 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002915 }
2916
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002917 /**
2918 * Configure a TUN interface and return its file descriptor. Parameters
2919 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002920 * and not available in ConnectivityManager. Permissions are checked in
2921 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002922 * @hide
2923 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002924 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002925 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002926 return mVpn.establish(config);
2927 }
2928
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002929 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002930 * Start legacy VPN and return an intent to VpnDialogs. This method is
2931 * used by VpnSettings and not available in ConnectivityManager.
2932 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002933 * @hide
2934 */
2935 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002936 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2937 mVpn.startLegacyVpn(config, racoon, mtpd);
2938 }
2939
2940 /**
2941 * Return the information of the ongoing legacy VPN. This method is used
2942 * by VpnSettings and not available in ConnectivityManager. Permissions
2943 * are checked in Vpn class.
2944 * @hide
2945 */
2946 @Override
2947 public LegacyVpnInfo getLegacyVpnInfo() {
2948 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002949 }
2950
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002951 /**
2952 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2953 * through NetworkStateTracker since it works differently. For example, it
2954 * needs to override DNS servers but never takes the default routes. It
2955 * relies on another data network, and it could keep existing connections
2956 * alive after reconnecting, switching between networks, or even resuming
2957 * from deep sleep. Calls from applications should be done synchronously
2958 * to avoid race conditions. As these are all hidden APIs, refactoring can
2959 * be done whenever a better abstraction is developed.
2960 */
2961 public class VpnCallback {
2962
2963 private VpnCallback() {
2964 }
2965
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002966 public void override(List<String> dnsServers, List<String> searchDomains) {
2967 if (dnsServers == null) {
2968 restore();
2969 return;
2970 }
2971
2972 // Convert DNS servers into addresses.
2973 List<InetAddress> addresses = new ArrayList<InetAddress>();
2974 for (String address : dnsServers) {
2975 // Double check the addresses and remove invalid ones.
2976 try {
2977 addresses.add(InetAddress.parseNumericAddress(address));
2978 } catch (Exception e) {
2979 // ignore
2980 }
2981 }
2982 if (addresses.isEmpty()) {
2983 restore();
2984 return;
2985 }
2986
2987 // Concatenate search domains into a string.
2988 StringBuilder buffer = new StringBuilder();
2989 if (searchDomains != null) {
2990 for (String domain : searchDomains) {
2991 buffer.append(domain).append(' ');
2992 }
2993 }
2994 String domains = buffer.toString().trim();
2995
2996 // Apply DNS changes.
2997 boolean changed = false;
2998 synchronized (mDnsLock) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002999 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003000 mDnsOverridden = true;
3001 }
3002 if (changed) {
3003 bumpDns();
3004 }
3005
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003006 // Temporarily disable the default proxy.
3007 synchronized (mDefaultProxyLock) {
3008 mDefaultProxyDisabled = true;
3009 if (mDefaultProxy != null) {
3010 sendProxyBroadcast(null);
3011 }
3012 }
3013
3014 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003015 }
3016
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003017 public void restore() {
3018 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003019 if (mDnsOverridden) {
3020 mDnsOverridden = false;
3021 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003022 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003023 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003024 synchronized (mDefaultProxyLock) {
3025 mDefaultProxyDisabled = false;
3026 if (mDefaultProxy != null) {
3027 sendProxyBroadcast(mDefaultProxy);
3028 }
3029 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003030 }
3031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032}