blob: 97fb0b0e48fff580b833d5e26d8eebee3f35dabd [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) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800995 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800996 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
997 return Phone.APN_TYPE_NOT_AVAILABLE;
998 } else {
999 // else make the attempt anyway - probably giving REQUEST_STARTED below
1000 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001001 }
1002
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001003 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1004
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001005 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001006 boolean addToList = true;
1007 if (restoreTimer < 0) {
1008 // In case there is no timer is specified for the feature,
1009 // make sure we don't add duplicate entry with the same request.
1010 for (FeatureUser u : mFeatureUsers) {
1011 if (u.isSameUser(f)) {
1012 // Duplicate user is found. Do not add.
1013 addToList = false;
1014 break;
1015 }
1016 }
1017 }
1018
1019 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001020 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1021 // this gets used for per-pid dns when connected
1022 mNetRequestersPids[usedNetworkType].add(currentPid);
1023 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001024 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001025
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001026 if (restoreTimer >= 0) {
1027 mHandler.sendMessageDelayed(
1028 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1029 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001030
Robert Greenwalta64bf832009-08-19 20:19:33 -07001031 if ((ni.isConnectedOrConnecting() == true) &&
1032 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001033 if (ni.isConnected() == true) {
1034 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -07001035 handleDnsConfigurationChange(usedNetworkType);
Wink Savillec9acde92011-09-21 11:05:43 -07001036 if (VDBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001037 return Phone.APN_ALREADY_ACTIVE;
1038 }
Wink Savillec9acde92011-09-21 11:05:43 -07001039 if (VDBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001040 return Phone.APN_REQUEST_STARTED;
1041 }
1042
1043 // check if the radio in play can make another contact
1044 // assume if cannot for now
1045
Wink Savillec9acde92011-09-21 11:05:43 -07001046 if (DBG) {
1047 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1048 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001049 network.reconnect();
1050 return Phone.APN_REQUEST_STARTED;
1051 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001052 // need to remember this unsupported request so we respond appropriately on stop
1053 synchronized(this) {
1054 mFeatureUsers.add(f);
1055 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1056 // this gets used for per-pid dns when connected
1057 mNetRequestersPids[usedNetworkType].add(currentPid);
1058 }
1059 }
Robert Greenwalt02648a42010-05-18 10:52:51 -07001060 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001061 }
1062 }
1063 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001066 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001068 enforceChangePermission();
1069
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001070 int pid = getCallingPid();
1071 int uid = getCallingUid();
1072
1073 FeatureUser u = null;
1074 boolean found = false;
1075
1076 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001077 for (FeatureUser x : mFeatureUsers) {
1078 if (x.isSameUser(pid, uid, networkType, feature)) {
1079 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001080 found = true;
1081 break;
1082 }
1083 }
1084 }
1085 if (found && u != null) {
1086 // stop regardless of how many other time this proc had called start
1087 return stopUsingNetworkFeature(u, true);
1088 } else {
1089 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001090 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001091 return 1;
1092 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001093 }
1094
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001095 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1096 int networkType = u.mNetworkType;
1097 String feature = u.mFeature;
1098 int pid = u.mPid;
1099 int uid = u.mUid;
1100
1101 NetworkStateTracker tracker = null;
1102 boolean callTeardown = false; // used to carry our decision outside of sync block
1103
Wink Savillec9acde92011-09-21 11:05:43 -07001104 if (VDBG) {
1105 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001106 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001109 if (DBG) {
1110 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1111 ", net is invalid");
1112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 return -1;
1114 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001115
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001116 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1117 // sync block
1118 synchronized(this) {
1119 // check if this process still has an outstanding start request
1120 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001121 if (VDBG) {
1122 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1123 ", ignoring");
1124 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001125 return 1;
1126 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001127 u.unlinkDeathRecipient();
1128 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1129 // If we care about duplicate requests, check for that here.
1130 //
1131 // This is done to support the extension of a request - the app
1132 // can request we start the network feature again and renew the
1133 // auto-shutoff delay. Normal "stop" calls from the app though
1134 // do not pay attention to duplicate requests - in effect the
1135 // API does not refcount and a single stop will counter multiple starts.
1136 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001137 for (FeatureUser x : mFeatureUsers) {
1138 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001139 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001140 return 1;
1141 }
1142 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001143 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001144
repo syncaea743a2011-07-29 23:55:49 -07001145 // TODO - move to individual network trackers
1146 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1147
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001148 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001149 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001150 if (DBG) {
1151 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1152 " no known tracker for used net type " + usedNetworkType);
1153 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001154 return -1;
1155 }
1156 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001157 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001158 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001159 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001160 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001161 if (VDBG) {
1162 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1163 " others still using it");
1164 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001165 return 1;
1166 }
1167 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001168 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001169 if (DBG) {
1170 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1171 " not a known feature - dropping");
1172 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001173 }
1174 }
Wink Savillec9acde92011-09-21 11:05:43 -07001175
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001176 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001177 if (DBG) {
1178 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1179 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001180 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001181 return 1;
1182 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001183 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186
1187 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001188 * @deprecated use requestRouteToHostAddress instead
1189 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 * Ensure that a network route exists to deliver traffic to the specified
1191 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001192 * @param networkType the type of the network over which traffic to the
1193 * specified host is to be routed
1194 * @param hostAddress the IP address of the host to which the route is
1195 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 * @return {@code true} on success, {@code false} on failure
1197 */
1198 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001199 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1200
1201 if (inetAddress == null) {
1202 return false;
1203 }
1204
1205 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1206 }
1207
1208 /**
1209 * Ensure that a network route exists to deliver traffic to the specified
1210 * host via the specified network interface.
1211 * @param networkType the type of the network over which traffic to the
1212 * specified host is to be routed
1213 * @param hostAddress the IP address of the host to which the route is
1214 * desired
1215 * @return {@code true} on success, {@code false} on failure
1216 */
1217 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001219 if (mProtectedNetworks.contains(networkType)) {
1220 enforceConnectivityInternalPermission();
1221 }
1222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1224 return false;
1225 }
1226 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001227
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001228 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1229 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001230 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001231 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001232 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001233 }
1234 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001236 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001237 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001238 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001239 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001240 } catch (UnknownHostException e) {}
1241 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001242 }
1243
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001244 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1245 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001246 }
1247
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001248 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1249 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001250 }
1251
Robert Greenwaltad55d352011-07-22 11:55:33 -07001252 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001253 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001254 }
1255
1256 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001257 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001258 }
1259
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001260 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1261 boolean toDefaultTable) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001262 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1263 if (bestRoute == null) {
1264 bestRoute = RouteInfo.makeHostRoute(addr);
1265 } else {
1266 if (bestRoute.getGateway().equals(addr)) {
1267 // if there is no better route, add the implied hostroute for our gateway
1268 bestRoute = RouteInfo.makeHostRoute(addr);
1269 } else {
1270 // if we will connect to this through another route, add a direct route
1271 // to it's gateway
1272 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1273 }
1274 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001275 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001276 }
1277
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001278 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001279 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001280 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1281
1282 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001283 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001284 return false;
1285 }
1286
1287 if (r.isHostRoute() == false) {
1288 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1289 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001290 if (bestRoute.getGateway().equals(r.getGateway())) {
1291 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001292 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001293 } else {
1294 // if we will connect to our gateway through another route, add a direct
1295 // route to it's gateway
1296 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001297 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001298 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001299 }
1300 }
1301 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001302 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001303 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001304 if (toDefaultTable) {
1305 mAddedRoutes.add(r); // only track default table - only one apps can effect
1306 mNetd.addRoute(ifaceName, r);
1307 } else {
1308 mNetd.addSecondaryRoute(ifaceName, r);
1309 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001310 } catch (Exception e) {
1311 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001312 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001313 return false;
1314 }
1315 } else {
1316 // if we remove this one and there are no more like it, then refcount==0 and
1317 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001318 if (toDefaultTable) {
1319 mAddedRoutes.remove(r);
1320 if (mAddedRoutes.contains(r) == false) {
1321 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1322 try {
1323 mNetd.removeRoute(ifaceName, r);
1324 } catch (Exception e) {
1325 // never crash - catch them all
1326 if (VDBG) loge("Exception trying to remove a route: " + e);
1327 return false;
1328 }
1329 } else {
1330 if (VDBG) log("not removing " + r + " as it's still in use");
1331 }
1332 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001333 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001334 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001335 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001336 } catch (Exception e) {
1337 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001338 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001339 return false;
1340 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001341 }
1342 }
1343 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
1345
1346 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001347 * @see ConnectivityManager#getMobileDataEnabled()
1348 */
1349 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001350 // TODO: This detail should probably be in DataConnectionTracker's
1351 // which is where we store the value and maybe make this
1352 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001353 enforceAccessPermission();
1354 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1355 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001356 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001357 return retVal;
1358 }
1359
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001360 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001361 enforceConnectivityInternalPermission();
1362
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001363 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1364 (met ? ENABLED : DISABLED), networkType));
1365 }
1366
1367 private void handleSetDependencyMet(int networkType, boolean met) {
1368 if (mNetTrackers[networkType] != null) {
1369 if (DBG) {
1370 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1371 }
1372 mNetTrackers[networkType].setDependencyMet(met);
1373 }
1374 }
1375
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1377 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001380 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001381
1382 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001383 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 }
1385
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001386 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 // skip update when we've already applied rules
1388 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1389 if (oldRules == uidRules) return;
1390
1391 mUidRules.put(uid, uidRules);
1392 }
1393
1394 // TODO: dispatch into NMS to push rules towards kernel module
1395 // TODO: notify UID when it has requested targeted updates
1396 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001397
1398 @Override
1399 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1400 // only someone like NPMS should only be calling us
1401 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1402
1403 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001404 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001405 }
1406
1407 synchronized (mRulesLock) {
1408 mMeteredIfaces.clear();
1409 for (String iface : meteredIfaces) {
1410 mMeteredIfaces.add(iface);
1411 }
1412 }
1413 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001414 };
1415
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001416 /**
1417 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1418 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001419 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001420 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001421 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001422
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001423 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001424 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001425 }
1426
1427 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001428 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001429 if (VDBG) {
1430 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001431 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001432 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1433 }
tk.munb97d34c2012-01-06 10:43:52 +09001434 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1435 if (VDBG) {
1436 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1437 }
1438 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1439 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001440 }
1441
1442 @Override
1443 public void setPolicyDataEnable(int networkType, boolean enabled) {
1444 // only someone like NPMS should only be calling us
1445 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1446
1447 mHandler.sendMessage(mHandler.obtainMessage(
1448 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1449 }
1450
1451 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1452 if (isNetworkTypeValid(networkType)) {
1453 final NetworkStateTracker tracker = mNetTrackers[networkType];
1454 if (tracker != null) {
1455 tracker.setPolicyDataEnable(enabled);
1456 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001457 }
1458 }
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001461 mContext.enforceCallingOrSelfPermission(
1462 android.Manifest.permission.ACCESS_NETWORK_STATE,
1463 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465
1466 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001467 mContext.enforceCallingOrSelfPermission(
1468 android.Manifest.permission.CHANGE_NETWORK_STATE,
1469 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001472 // TODO Make this a special check when it goes public
1473 private void enforceTetherChangePermission() {
1474 mContext.enforceCallingOrSelfPermission(
1475 android.Manifest.permission.CHANGE_NETWORK_STATE,
1476 "ConnectivityService");
1477 }
1478
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001479 private void enforceTetherAccessPermission() {
1480 mContext.enforceCallingOrSelfPermission(
1481 android.Manifest.permission.ACCESS_NETWORK_STATE,
1482 "ConnectivityService");
1483 }
1484
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001485 private void enforceConnectivityInternalPermission() {
1486 mContext.enforceCallingOrSelfPermission(
1487 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1488 "ConnectivityService");
1489 }
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001492 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1493 * network, we ignore it. If it is for the active network, we send out a
1494 * broadcast. But first, we check whether it might be possible to connect
1495 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 * @param info the {@code NetworkInfo} for the network
1497 */
1498 private void handleDisconnect(NetworkInfo info) {
1499
Robert Greenwalt42acef32009-08-12 16:08:25 -07001500 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
Robert Greenwalt42acef32009-08-12 16:08:25 -07001502 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 /*
1504 * If the disconnected network is not the active one, then don't report
1505 * this as a loss of connectivity. What probably happened is that we're
1506 * getting the disconnect for a network that we explicitly disabled
1507 * in accordance with network preference policies.
1508 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001509 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001510 List pids = mNetRequestersPids[prevNetType];
1511 for (int i = 0; i<pids.size(); i++) {
1512 Integer pid = (Integer)pids.get(i);
1513 // will remove them because the net's no longer connected
1514 // need to do this now as only now do we know the pids and
1515 // can properly null things that are no longer referenced.
1516 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1521 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1522 if (info.isFailover()) {
1523 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1524 info.setFailover(false);
1525 }
1526 if (info.getReason() != null) {
1527 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1528 }
1529 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001530 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1531 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001533
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001534 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001535 tryFailover(prevNetType);
1536 if (mActiveDefaultNetwork != -1) {
1537 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001538 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1539 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001540 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001541 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1542 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001543 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001544 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001545
1546 // Reset interface if no other connections are using the same interface
1547 boolean doReset = true;
1548 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1549 if (linkProperties != null) {
1550 String oldIface = linkProperties.getInterfaceName();
1551 if (TextUtils.isEmpty(oldIface) == false) {
1552 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1553 if (networkStateTracker == null) continue;
1554 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1555 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1556 LinkProperties l = networkStateTracker.getLinkProperties();
1557 if (l == null) continue;
1558 if (oldIface.equals(l.getInterfaceName())) {
1559 doReset = false;
1560 break;
1561 }
1562 }
1563 }
1564 }
1565 }
1566
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001567 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001568 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001569
Jeff Sharkey961e3042011-08-29 16:02:57 -07001570 final Intent immediateIntent = new Intent(intent);
1571 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1572 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001573 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001574 /*
1575 * If the failover network is already connected, then immediately send
1576 * out a followup broadcast indicating successful failover
1577 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001578 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001579 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1580 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001581 }
1582 }
1583
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001584 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001585 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001586 * If this is a default network, check if other defaults are available.
1587 * Try to reconnect on all available and let them hash it out when
1588 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001589 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001590 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001591 if (mActiveDefaultNetwork == prevNetType) {
1592 mActiveDefaultNetwork = -1;
1593 }
1594
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001595 // don't signal a reconnect for anything lower or equal priority than our
1596 // current connected default
1597 // TODO - don't filter by priority now - nice optimization but risky
1598// int currentPriority = -1;
1599// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001600// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001601// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001602 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001603 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001604 if (mNetConfigs[checkType] == null) continue;
1605 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001606 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001607
1608// Enabling the isAvailable() optimization caused mobile to not get
1609// selected if it was in the middle of error handling. Specifically
1610// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1611// would not be available and we wouldn't get connected to anything.
1612// So removing the isAvailable() optimization below for now. TODO: This
1613// optimization should work and we need to investigate why it doesn't work.
1614// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1615// complete before it is really complete.
1616// if (!mNetTrackers[checkType].isAvailable()) continue;
1617
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001618// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001619
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001620 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1621 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1622 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1623 checkInfo.setFailover(true);
1624 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001625 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001626 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 }
1630
1631 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001632 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1633 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001634 }
1635
Wink Saville628b0852011-08-04 15:01:58 -07001636 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001637 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1638 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001639 }
1640
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001641 private void sendInetConditionBroadcast(NetworkInfo info) {
1642 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1643 }
1644
Wink Saville628b0852011-08-04 15:01:58 -07001645 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001646 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1648 if (info.isFailover()) {
1649 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1650 info.setFailover(false);
1651 }
1652 if (info.getReason() != null) {
1653 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1654 }
1655 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001656 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1657 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001659 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001660 return intent;
1661 }
1662
1663 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1664 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1665 }
1666
1667 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1668 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670
1671 /**
1672 * Called when an attempt to fail over to another network has failed.
1673 * @param info the {@link NetworkInfo} for the failed network
1674 */
1675 private void handleConnectionFailure(NetworkInfo info) {
1676 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677
Robert Greenwalt42acef32009-08-12 16:08:25 -07001678 String reason = info.getReason();
1679 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001680
Robert Greenwalt572172b2010-10-08 16:35:52 -07001681 String reasonText;
1682 if (reason == null) {
1683 reasonText = ".";
1684 } else {
1685 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001687 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001688
1689 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1690 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1691 if (getActiveNetworkInfo() == null) {
1692 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1693 }
1694 if (reason != null) {
1695 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1696 }
1697 if (extraInfo != null) {
1698 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1699 }
1700 if (info.isFailover()) {
1701 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1702 info.setFailover(false);
1703 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001704
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001705 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001706 tryFailover(info.getType());
1707 if (mActiveDefaultNetwork != -1) {
1708 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001709 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1710 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001711 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001712 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1713 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001714 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001715
Robert Greenwalt029be812010-09-20 18:01:43 -07001716 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001717
1718 final Intent immediateIntent = new Intent(intent);
1719 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1720 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001721 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001722 /*
1723 * If the failover network is already connected, then immediately send
1724 * out a followup broadcast indicating successful failover
1725 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001726 if (mActiveDefaultNetwork != -1) {
1727 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001728 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001729 }
1730
1731 private void sendStickyBroadcast(Intent intent) {
1732 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001733 if (!mSystemReady) {
1734 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001735 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001736 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001737 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001738 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001739 }
1740
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001741 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001742 }
1743 }
1744
Wink Saville628b0852011-08-04 15:01:58 -07001745 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1746 if (delayMs <= 0) {
1747 sendStickyBroadcast(intent);
1748 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001749 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001750 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1751 + intent.getAction());
1752 }
Wink Saville628b0852011-08-04 15:01:58 -07001753 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1754 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1755 }
1756 }
1757
Mike Lockwood0f79b542009-08-14 14:18:49 -04001758 void systemReady() {
1759 synchronized(this) {
1760 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001761 if (mInitialBroadcast != null) {
1762 mContext.sendStickyBroadcast(mInitialBroadcast);
1763 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001764 }
1765 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001766 // load the global proxy at startup
1767 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769
1770 private void handleConnect(NetworkInfo info) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001771 final int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772
1773 // snapshot isFailover, because sendConnectedBroadcast() resets it
1774 boolean isFailover = info.isFailover();
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001775 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776
Robert Greenwalt42acef32009-08-12 16:08:25 -07001777 // if this is a default net and other default is running
1778 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001779 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001780 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1781 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001782 mNetConfigs[mActiveDefaultNetwork].priority >
1783 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001784 mNetworkPreference == mActiveDefaultNetwork) {
1785 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001786 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001787 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001788 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001789 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001790 teardown(thisNet);
1791 return;
1792 } else {
1793 // tear down the other
1794 NetworkStateTracker otherNet =
1795 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001796 if (DBG) {
1797 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001799 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001800 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001801 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001802 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001803 return;
1804 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001805 }
1806 }
1807 synchronized (ConnectivityService.this) {
1808 // have a new default network, release the transition wakelock in a second
1809 // if it's held. The second pause is to allow apps to reconnect over the
1810 // new network
1811 if (mNetTransitionWakeLock.isHeld()) {
1812 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001813 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001814 mNetTransitionWakeLockSerialNumber, 0),
1815 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001816 }
1817 }
1818 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001819 // this will cause us to come up initially as unconnected and switching
1820 // to connected after our normal pause unless somebody reports us as reall
1821 // disconnected
1822 mDefaultInetConditionPublished = 0;
1823 mDefaultConnectionSequence++;
1824 mInetConditionChangeInFlight = false;
1825 // Don't do this - if we never sign in stay, grey
1826 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001829 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001830 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001831 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001832
1833 // notify battery stats service about this network
1834 final String iface = thisNet.getLinkProperties().getInterfaceName();
1835 if (iface != null) {
1836 try {
1837 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1838 } catch (RemoteException e) {
1839 // ignored; service lives in system_server
1840 }
1841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001845 * After a change in the connectivity state of a network. We're mainly
1846 * concerned with making sure that the list of DNS servers is set up
1847 * according to which networks are connected, and ensuring that the
1848 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001850 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001851 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001854 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001855 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001857 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001858
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001859 LinkProperties curLp = mCurrentLinkProperties[netType];
1860 LinkProperties newLp = null;
1861
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001862 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001863 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001864 if (VDBG) {
1865 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1866 " doReset=" + doReset + " resetMask=" + resetMask +
1867 "\n curLp=" + curLp +
1868 "\n newLp=" + newLp);
1869 }
1870
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001871 if (curLp != null) {
1872 if (curLp.isIdenticalInterfaceName(newLp)) {
1873 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1874 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1875 for (LinkAddress linkAddr : car.removed) {
1876 if (linkAddr.getAddress() instanceof Inet4Address) {
1877 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1878 }
1879 if (linkAddr.getAddress() instanceof Inet6Address) {
1880 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1881 }
Wink Savillee8222252011-07-13 13:44:13 -07001882 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001883 if (DBG) {
1884 log("handleConnectivityChange: addresses changed" +
1885 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1886 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001887 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001888 } else {
1889 if (DBG) {
1890 log("handleConnectivityChange: address are the same reset per doReset" +
1891 " linkProperty[" + netType + "]:" +
1892 " resetMask=" + resetMask);
1893 }
Wink Savillee8222252011-07-13 13:44:13 -07001894 }
1895 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001896 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001897 if (DBG) {
1898 log("handleConnectivityChange: interface not not equivalent reset both" +
1899 " linkProperty[" + netType + "]:" +
1900 " resetMask=" + resetMask);
1901 }
Wink Savillee8222252011-07-13 13:44:13 -07001902 }
Wink Savillee8222252011-07-13 13:44:13 -07001903 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001904 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07001905 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001906 }
1907 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001908 if (VDBG) {
1909 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1910 " doReset=" + doReset + " resetMask=" + resetMask +
1911 "\n curLp=" + curLp +
1912 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001915 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001916 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001917
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001918 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001919 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1920 if (linkProperties != null) {
1921 String iface = linkProperties.getInterfaceName();
1922 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001923 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001924 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1925 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001926
1927 // Tell VPN the interface is down. It is a temporary
1928 // but effective fix to make VPN aware of the change.
1929 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1930 mVpn.interfaceStatusChanged(iface, false);
1931 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001932 }
1933 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07001934 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001935 try {
1936 mNetd.flushInterfaceDnsCache(iface);
1937 } catch (Exception e) {
1938 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001939 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001940 }
1941 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001942 }
1943 }
1944 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001945
1946 // TODO: Temporary notifying upstread change to Tethering.
1947 // @see bug/4455071
1948 /** Notify TetheringService if interface name has been changed. */
1949 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1950 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1951 if (isTetheringSupported()) {
1952 mTethering.handleTetherIfaceChange();
1953 }
1954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001957 /**
1958 * Add and remove routes using the old properties (null if not previously connected),
1959 * new properties (null if becoming disconnected). May even be double null, which
1960 * is a noop.
1961 * Uses isLinkDefault to determine if default routes should be set or conversely if
1962 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07001963 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001964 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07001965 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1966 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001967 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001968 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1969 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001970 if (curLp != null) {
1971 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001972 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001973 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001974 } else if (newLp != null) {
1975 routeDiff.added = newLp.getRoutes();
1976 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001977 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001978
Robert Greenwaltf125a092011-08-15 12:31:55 -07001979 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1980
Robert Greenwaltad55d352011-07-22 11:55:33 -07001981 for (RouteInfo r : routeDiff.removed) {
1982 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001983 removeRoute(curLp, r, TO_DEFAULT_TABLE);
1984 }
1985 if (isLinkDefault == false) {
1986 // remove from a secondary route table
1987 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001988 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001989 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001990
Robert Greenwaltad55d352011-07-22 11:55:33 -07001991 for (RouteInfo r : routeDiff.added) {
1992 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001993 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001994 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001995 // add to a secondary route table
1996 addRoute(newLp, r, TO_SECONDARY_TABLE);
1997
Robert Greenwalte6b24292011-08-09 16:52:58 -07001998 // many radios add a default route even when we don't want one.
1999 // remove the default route unless somebody else has asked for it
2000 String ifaceName = newLp.getInterfaceName();
2001 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002002 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002003 try {
2004 mNetd.removeRoute(ifaceName, r);
2005 } catch (Exception e) {
2006 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07002007 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002008 }
2009 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002010 }
2011 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002012
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002013 if (!isLinkDefault) {
2014 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002015 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002016 // routes changed - remove all old dns entries and add new
2017 if (curLp != null) {
2018 for (InetAddress oldDns : curLp.getDnses()) {
2019 removeRouteToAddress(curLp, oldDns);
2020 }
2021 }
2022 if (newLp != null) {
2023 for (InetAddress newDns : newLp.getDnses()) {
2024 addRouteToAddress(newLp, newDns);
2025 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002026 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002027 } else {
2028 // no change in routes, check for change in dns themselves
2029 for (InetAddress oldDns : dnsDiff.removed) {
2030 removeRouteToAddress(curLp, oldDns);
2031 }
2032 for (InetAddress newDns : dnsDiff.added) {
2033 addRouteToAddress(newLp, newDns);
2034 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002035 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002036 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002037 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002038 }
2039
2040
Irfan Sheriffd649c122010-06-09 15:39:36 -07002041 /**
2042 * Reads the network specific TCP buffer sizes from SystemProperties
2043 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2044 * wide use
2045 */
2046 public void updateNetworkSettings(NetworkStateTracker nt) {
2047 String key = nt.getTcpBufferSizesPropName();
2048 String bufferSizes = SystemProperties.get(key);
2049
2050 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002051 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002052
2053 // Setting to default values so we won't be stuck to previous values
2054 key = "net.tcp.buffersize.default";
2055 bufferSizes = SystemProperties.get(key);
2056 }
2057
2058 // Set values in kernel
2059 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002060 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002061 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002062 + "] which comes from [" + key + "]");
2063 }
2064 setBufferSize(bufferSizes);
2065 }
2066 }
2067
2068 /**
2069 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2070 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2071 *
2072 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2073 * writeMin, writeInitial, writeMax"
2074 */
2075 private void setBufferSize(String bufferSizes) {
2076 try {
2077 String[] values = bufferSizes.split(",");
2078
2079 if (values.length == 6) {
2080 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002081 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2082 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2083 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2084 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2085 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2086 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002087 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002088 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002089 }
2090 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002091 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002092 }
2093 }
2094
Robert Greenwalt42acef32009-08-12 16:08:25 -07002095 /**
2096 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2097 * on the highest priority active net which this process requested.
2098 * If there aren't any, clear it out
2099 */
2100 private void reassessPidDns(int myPid, boolean doBump)
2101 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002102 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002103 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002104 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002105 continue;
2106 }
2107 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002108 if (nt.getNetworkInfo().isConnected() &&
2109 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002110 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002111 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002112 List pids = mNetRequestersPids[i];
2113 for (int j=0; j<pids.size(); j++) {
2114 Integer pid = (Integer)pids.get(j);
2115 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002116 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002117 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002118 if (doBump) {
2119 bumpDns();
2120 }
2121 return;
2122 }
2123 }
2124 }
2125 }
2126 // nothing found - delete
2127 for (int i = 1; ; i++) {
2128 String prop = "net.dns" + i + "." + myPid;
2129 if (SystemProperties.get(prop).length() == 0) {
2130 if (doBump) {
2131 bumpDns();
2132 }
2133 return;
2134 }
2135 SystemProperties.set(prop, "");
2136 }
2137 }
2138
Robert Greenwalt10398722010-12-17 15:20:36 -08002139 // return true if results in a change
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002140 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002141 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002142 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002143 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002144 String dnsString = dns.getHostAddress();
2145 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2146 changed = true;
2147 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2148 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002149 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002150 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002151 }
2152
2153 private void bumpDns() {
2154 /*
2155 * Bump the property that tells the name resolver library to reread
2156 * the DNS server list from the properties.
2157 */
2158 String propVal = SystemProperties.get("net.dnschange");
2159 int n = 0;
2160 if (propVal.length() != 0) {
2161 try {
2162 n = Integer.parseInt(propVal);
2163 } catch (NumberFormatException e) {}
2164 }
2165 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002166 /*
2167 * Tell the VMs to toss their DNS caches
2168 */
2169 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2170 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002171 /*
2172 * Connectivity events can happen before boot has completed ...
2173 */
2174 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002175 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002176 }
2177
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002178 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002179 private boolean updateDns(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002180 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002181 boolean changed = false;
2182 int last = 0;
2183 if (dnses.size() == 0 && mDefaultDns != null) {
2184 ++last;
2185 String value = mDefaultDns.getHostAddress();
2186 if (!value.equals(SystemProperties.get("net.dns1"))) {
2187 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002188 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002189 }
2190 changed = true;
2191 SystemProperties.set("net.dns1", value);
2192 }
2193 } else {
2194 for (InetAddress dns : dnses) {
2195 ++last;
2196 String key = "net.dns" + last;
2197 String value = dns.getHostAddress();
2198 if (!changed && value.equals(SystemProperties.get(key))) {
2199 continue;
2200 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002201 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002202 log("adding dns " + value + " for " + network);
2203 }
2204 changed = true;
2205 SystemProperties.set(key, value);
2206 }
2207 }
2208 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2209 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002210 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002211 changed = true;
2212 SystemProperties.set(key, "");
2213 }
2214 mNumDnsEntries = last;
2215
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002216 if (changed) {
2217 try {
2218 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2219 mNetd.setDefaultInterfaceForDns(iface);
2220 } catch (Exception e) {
Wink Savillec9acde92011-09-21 11:05:43 -07002221 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002222 }
2223 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002224 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2225 SystemProperties.set("net.dns.search", domains);
2226 changed = true;
2227 }
2228 return changed;
2229 }
2230
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002231 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002232 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002233 NetworkStateTracker nt = mNetTrackers[netType];
2234 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002235 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002236 if (p == null) return;
2237 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002238 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002239 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002240 String network = nt.getNetworkInfo().getTypeName();
2241 synchronized (mDnsLock) {
2242 if (!mDnsOverridden) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002243 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002244 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002245 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002246 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002247 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002248 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002249 NetworkUtils.makeStrings(dnses));
2250 } catch (Exception e) {
Wink Savillec9acde92011-09-21 11:05:43 -07002251 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002252 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002253 // set per-pid dns for attached secondary nets
2254 List pids = mNetRequestersPids[netType];
2255 for (int y=0; y< pids.size(); y++) {
2256 Integer pid = (Integer)pids.get(y);
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002257 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002260 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002262 }
2263
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002264 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002265 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2266 NETWORK_RESTORE_DELAY_PROP_NAME);
2267 if(restoreDefaultNetworkDelayStr != null &&
2268 restoreDefaultNetworkDelayStr.length() != 0) {
2269 try {
2270 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2271 } catch (NumberFormatException e) {
2272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002274 // if the system property isn't set, use the value for the apn type
2275 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2276
2277 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2278 (mNetConfigs[networkType] != null)) {
2279 ret = mNetConfigs[networkType].restoreTime;
2280 }
2281 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283
2284 @Override
2285 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002286 if (mContext.checkCallingOrSelfPermission(
2287 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002289 pw.println("Permission Denial: can't dump ConnectivityService " +
2290 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2291 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 return;
2293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 pw.println();
2295 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002296 if (nst != null) {
2297 if (nst.getNetworkInfo().isConnected()) {
2298 pw.println("Active network: " + nst.getNetworkInfo().
2299 getTypeName());
2300 }
2301 pw.println(nst.getNetworkInfo());
2302 pw.println(nst);
2303 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002306
2307 pw.println("Network Requester Pids:");
2308 for (int net : mPriorityList) {
2309 String pidString = net + ": ";
2310 for (Object pid : mNetRequestersPids[net]) {
2311 pidString = pidString + pid.toString() + ", ";
2312 }
2313 pw.println(pidString);
2314 }
2315 pw.println();
2316
2317 pw.println("FeatureUsers:");
2318 for (Object requester : mFeatureUsers) {
2319 pw.println(requester.toString());
2320 }
2321 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002322
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002323 synchronized (this) {
2324 pw.println("NetworkTranstionWakeLock is currently " +
2325 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2326 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2327 }
2328 pw.println();
2329
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002330 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002331
2332 if (mInetLog != null) {
2333 pw.println();
2334 pw.println("Inet condition reports:");
2335 for(int i = 0; i < mInetLog.size(); i++) {
2336 pw.println(mInetLog.get(i));
2337 }
2338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340
Robert Greenwalt42acef32009-08-12 16:08:25 -07002341 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002343 public MyHandler(Looper looper) {
2344 super(looper);
2345 }
2346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 @Override
2348 public void handleMessage(Message msg) {
2349 NetworkInfo info;
2350 switch (msg.what) {
2351 case NetworkStateTracker.EVENT_STATE_CHANGED:
2352 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002353 int type = info.getType();
2354 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002355
Wink Savillec9acde92011-09-21 11:05:43 -07002356 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2357 (state == NetworkInfo.State.DISCONNECTED)) {
2358 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002359 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002360 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362
2363 // Connectivity state changed:
2364 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002365 // [12-9] Network subtype (for mobile network, as defined
2366 // by TelephonyManager)
2367 // [8-3] Detailed state ordinal (as defined by
2368 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 // [2-0] Network type (as defined by ConnectivityManager)
2370 int eventLogParam = (info.getType() & 0x7) |
2371 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2372 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002373 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002374 eventLogParam);
2375
2376 if (info.getDetailedState() ==
2377 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002379 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002381 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002383 // the logic here is, handle SUSPENDED the same as
2384 // DISCONNECTED. The only difference being we are
2385 // broadcasting an intent with NetworkInfo that's
2386 // suspended. This allows the applications an
2387 // opportunity to handle DISCONNECTED and SUSPENDED
2388 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002390 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 handleConnect(info);
2392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002395 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002396 // TODO: Temporary allowing network configuration
2397 // change not resetting sockets.
2398 // @see bug/4455071
2399 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002401 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002402 String causedBy = null;
2403 synchronized (ConnectivityService.this) {
2404 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2405 mNetTransitionWakeLock.isHeld()) {
2406 mNetTransitionWakeLock.release();
2407 causedBy = mNetTransitionWakeLockCausedBy;
2408 }
2409 }
2410 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002411 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002412 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002413 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002414 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002415 FeatureUser u = (FeatureUser)msg.obj;
2416 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002417 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002418 case EVENT_INET_CONDITION_CHANGE:
2419 {
2420 int netType = msg.arg1;
2421 int condition = msg.arg2;
2422 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002423 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002424 }
2425 case EVENT_INET_CONDITION_HOLD_END:
2426 {
2427 int netType = msg.arg1;
2428 int sequence = msg.arg2;
2429 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002430 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002431 }
2432 case EVENT_SET_NETWORK_PREFERENCE:
2433 {
2434 int preference = msg.arg1;
2435 handleSetNetworkPreference(preference);
2436 break;
2437 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002438 case EVENT_SET_MOBILE_DATA:
2439 {
2440 boolean enabled = (msg.arg1 == ENABLED);
2441 handleSetMobileData(enabled);
2442 break;
2443 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002444 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2445 {
2446 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002447 break;
2448 }
2449 case EVENT_SET_DEPENDENCY_MET:
2450 {
2451 boolean met = (msg.arg1 == ENABLED);
2452 handleSetDependencyMet(msg.arg2, met);
2453 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002454 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002455 case EVENT_RESTORE_DNS:
2456 {
2457 if (mActiveDefaultNetwork != -1) {
2458 handleDnsConfigurationChange(mActiveDefaultNetwork);
2459 }
2460 break;
2461 }
Wink Saville628b0852011-08-04 15:01:58 -07002462 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2463 {
2464 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002465 sendStickyBroadcast(intent);
2466 break;
2467 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002468 case EVENT_SET_POLICY_DATA_ENABLE: {
2469 final int networkType = msg.arg1;
2470 final boolean enabled = msg.arg2 == ENABLED;
2471 handleSetPolicyDataEnable(networkType, enabled);
2472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 }
2474 }
2475 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002476
2477 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002478 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002479 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002480
2481 if (isTetheringSupported()) {
2482 return mTethering.tether(iface);
2483 } else {
2484 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2485 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002486 }
2487
2488 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002489 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002490 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002491
2492 if (isTetheringSupported()) {
2493 return mTethering.untether(iface);
2494 } else {
2495 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2496 }
2497 }
2498
2499 // javadoc from interface
2500 public int getLastTetherError(String iface) {
2501 enforceTetherAccessPermission();
2502
2503 if (isTetheringSupported()) {
2504 return mTethering.getLastTetherError(iface);
2505 } else {
2506 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2507 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002508 }
2509
2510 // TODO - proper iface API for selection by property, inspection, etc
2511 public String[] getTetherableUsbRegexs() {
2512 enforceTetherAccessPermission();
2513 if (isTetheringSupported()) {
2514 return mTethering.getTetherableUsbRegexs();
2515 } else {
2516 return new String[0];
2517 }
2518 }
2519
2520 public String[] getTetherableWifiRegexs() {
2521 enforceTetherAccessPermission();
2522 if (isTetheringSupported()) {
2523 return mTethering.getTetherableWifiRegexs();
2524 } else {
2525 return new String[0];
2526 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002527 }
2528
Danica Chang6fdd0c62010-08-11 14:54:43 -07002529 public String[] getTetherableBluetoothRegexs() {
2530 enforceTetherAccessPermission();
2531 if (isTetheringSupported()) {
2532 return mTethering.getTetherableBluetoothRegexs();
2533 } else {
2534 return new String[0];
2535 }
2536 }
2537
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002538 public int setUsbTethering(boolean enable) {
2539 enforceTetherAccessPermission();
2540 if (isTetheringSupported()) {
2541 return mTethering.setUsbTethering(enable);
2542 } else {
2543 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2544 }
2545 }
2546
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002547 // TODO - move iface listing, queries, etc to new module
2548 // javadoc from interface
2549 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002550 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002551 return mTethering.getTetherableIfaces();
2552 }
2553
2554 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002555 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002556 return mTethering.getTetheredIfaces();
2557 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002558
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002559 @Override
2560 public String[] getTetheredIfacePairs() {
2561 enforceTetherAccessPermission();
2562 return mTethering.getTetheredIfacePairs();
2563 }
2564
Robert Greenwalt5a735062010-03-02 17:25:02 -08002565 public String[] getTetheringErroredIfaces() {
2566 enforceTetherAccessPermission();
2567 return mTethering.getErroredIfaces();
2568 }
2569
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002570 // if ro.tether.denied = true we default to no tethering
2571 // gservices could set the secure setting to 1 though to enable it on a build where it
2572 // had previously been turned off.
2573 public boolean isTetheringSupported() {
2574 enforceTetherAccessPermission();
2575 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002576 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2577 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2578 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002579 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002580
2581 // An API NetworkStateTrackers can call when they lose their network.
2582 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2583 // whichever happens first. The timer is started by the first caller and not
2584 // restarted by subsequent callers.
2585 public void requestNetworkTransitionWakelock(String forWhom) {
2586 enforceConnectivityInternalPermission();
2587 synchronized (this) {
2588 if (mNetTransitionWakeLock.isHeld()) return;
2589 mNetTransitionWakeLockSerialNumber++;
2590 mNetTransitionWakeLock.acquire();
2591 mNetTransitionWakeLockCausedBy = forWhom;
2592 }
2593 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002594 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002595 mNetTransitionWakeLockSerialNumber, 0),
2596 mNetTransitionWakeLockTimeout);
2597 return;
2598 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002599
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002600 // 100 percent is full good, 0 is full bad.
2601 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002602 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002603 mContext.enforceCallingOrSelfPermission(
2604 android.Manifest.permission.STATUS_BAR,
2605 "ConnectivityService");
2606
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002607 if (DBG) {
2608 int pid = getCallingPid();
2609 int uid = getCallingUid();
2610 String s = pid + "(" + uid + ") reports inet is " +
2611 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2612 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2613 mInetLog.add(s);
2614 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2615 mInetLog.remove(0);
2616 }
2617 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002618 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002619 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2620 }
2621
2622 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002623 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002624 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002625 return;
2626 }
2627 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002628 if (DBG) log("handleInetConditionChange: net=" + netType +
2629 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002630 return;
2631 }
Wink Savillec9acde92011-09-21 11:05:43 -07002632 if (VDBG) {
2633 log("handleInetConditionChange: net=" +
2634 netType + ", condition=" + condition +
2635 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2636 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002637 mDefaultInetCondition = condition;
2638 int delay;
2639 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002640 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002641 // setup a new hold to debounce this
2642 if (mDefaultInetCondition > 50) {
2643 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2644 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2645 } else {
2646 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2647 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2648 }
2649 mInetConditionChangeInFlight = true;
2650 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2651 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2652 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002653 // we've set the new condition, when this hold ends that will get picked up
2654 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002655 }
2656 }
2657
2658 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002659 if (DBG) {
2660 log("handleInetConditionHoldEnd: net=" + netType +
2661 ", condition=" + mDefaultInetCondition +
2662 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002663 }
2664 mInetConditionChangeInFlight = false;
2665
2666 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002667 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002668 return;
2669 }
2670 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002671 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002672 return;
2673 }
Wink Saville628b0852011-08-04 15:01:58 -07002674 // TODO: Figure out why this optimization sometimes causes a
2675 // change in mDefaultInetCondition to be missed and the
2676 // UI to not be updated.
2677 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2678 // if (DBG) log("no change in condition - aborting");
2679 // return;
2680 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002681 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2682 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002683 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002684 return;
2685 }
2686 mDefaultInetConditionPublished = mDefaultInetCondition;
2687 sendInetConditionBroadcast(networkInfo);
2688 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002689 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002690
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002691 public ProxyProperties getProxy() {
2692 synchronized (mDefaultProxyLock) {
2693 return mDefaultProxyDisabled ? null : mDefaultProxy;
2694 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002695 }
2696
2697 public void setGlobalProxy(ProxyProperties proxyProperties) {
2698 enforceChangePermission();
2699 synchronized (mGlobalProxyLock) {
2700 if (proxyProperties == mGlobalProxy) return;
2701 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2702 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2703
2704 String host = "";
2705 int port = 0;
2706 String exclList = "";
2707 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2708 mGlobalProxy = new ProxyProperties(proxyProperties);
2709 host = mGlobalProxy.getHost();
2710 port = mGlobalProxy.getPort();
2711 exclList = mGlobalProxy.getExclusionList();
2712 } else {
2713 mGlobalProxy = null;
2714 }
2715 ContentResolver res = mContext.getContentResolver();
2716 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2717 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002718 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002719 exclList);
2720 }
2721
2722 if (mGlobalProxy == null) {
2723 proxyProperties = mDefaultProxy;
2724 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07002725 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002726 }
2727
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002728 private void loadGlobalProxy() {
2729 ContentResolver res = mContext.getContentResolver();
2730 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2731 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2732 String exclList = Settings.Secure.getString(res,
2733 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2734 if (!TextUtils.isEmpty(host)) {
2735 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2736 synchronized (mGlobalProxyLock) {
2737 mGlobalProxy = proxyProperties;
2738 }
2739 }
2740 }
2741
Robert Greenwalt434203a2010-10-11 16:00:27 -07002742 public ProxyProperties getGlobalProxy() {
2743 synchronized (mGlobalProxyLock) {
2744 return mGlobalProxy;
2745 }
2746 }
2747
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002748 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2749 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2750 proxy = null;
2751 }
2752 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002753 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2754 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002755 mDefaultProxy = proxy;
2756
2757 if (!mDefaultProxyDisabled) {
2758 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002759 }
2760 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002761 }
2762
2763 private void handleDeprecatedGlobalHttpProxy() {
2764 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2765 Settings.Secure.HTTP_PROXY);
2766 if (!TextUtils.isEmpty(proxy)) {
2767 String data[] = proxy.split(":");
2768 String proxyHost = data[0];
2769 int proxyPort = 8080;
2770 if (data.length > 1) {
2771 try {
2772 proxyPort = Integer.parseInt(data[1]);
2773 } catch (NumberFormatException e) {
2774 return;
2775 }
2776 }
2777 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2778 setGlobalProxy(p);
2779 }
2780 }
2781
2782 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002783 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002784 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002785 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002786 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2787 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002788 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002789 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002790 }
2791
2792 private static class SettingsObserver extends ContentObserver {
2793 private int mWhat;
2794 private Handler mHandler;
2795 SettingsObserver(Handler handler, int what) {
2796 super(handler);
2797 mHandler = handler;
2798 mWhat = what;
2799 }
2800
2801 void observe(Context context) {
2802 ContentResolver resolver = context.getContentResolver();
2803 resolver.registerContentObserver(Settings.Secure.getUriFor(
2804 Settings.Secure.HTTP_PROXY), false, this);
2805 }
2806
2807 @Override
2808 public void onChange(boolean selfChange) {
2809 mHandler.obtainMessage(mWhat).sendToTarget();
2810 }
2811 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002812
2813 private void log(String s) {
2814 Slog.d(TAG, s);
2815 }
2816
2817 private void loge(String s) {
2818 Slog.e(TAG, s);
2819 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002820
repo syncaea743a2011-07-29 23:55:49 -07002821 int convertFeatureToNetworkType(int networkType, String feature) {
2822 int usedNetworkType = networkType;
2823
2824 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2825 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2826 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2827 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2828 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2829 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2830 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2831 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2832 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2833 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2834 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2835 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2836 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2837 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2838 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2839 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2840 } else {
2841 Slog.e(TAG, "Can't match any mobile netTracker!");
2842 }
2843 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2844 if (TextUtils.equals(feature, "p2p")) {
2845 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2846 } else {
2847 Slog.e(TAG, "Can't match any wifi netTracker!");
2848 }
2849 } else {
2850 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002851 }
repo syncaea743a2011-07-29 23:55:49 -07002852 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002853 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002854
2855 private static <T> T checkNotNull(T value, String message) {
2856 if (value == null) {
2857 throw new NullPointerException(message);
2858 }
2859 return value;
2860 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002861
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002862 /**
2863 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002864 * VpnBuilder and not available in ConnectivityManager. Permissions
2865 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002866 * @hide
2867 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002868 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002869 public boolean protectVpn(ParcelFileDescriptor socket) {
2870 try {
2871 int type = mActiveDefaultNetwork;
2872 if (ConnectivityManager.isNetworkTypeValid(type)) {
2873 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2874 return true;
2875 }
2876 } catch (Exception e) {
2877 // ignore
2878 } finally {
2879 try {
2880 socket.close();
2881 } catch (Exception e) {
2882 // ignore
2883 }
2884 }
2885 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002886 }
2887
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002888 /**
2889 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002890 * and not available in ConnectivityManager. Permissions are checked
2891 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002892 * @hide
2893 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002894 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002895 public boolean prepareVpn(String oldPackage, String newPackage) {
2896 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002897 }
2898
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002899 /**
2900 * Configure a TUN interface and return its file descriptor. Parameters
2901 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002902 * and not available in ConnectivityManager. Permissions are checked in
2903 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002904 * @hide
2905 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002906 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002907 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002908 return mVpn.establish(config);
2909 }
2910
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002911 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002912 * Start legacy VPN and return an intent to VpnDialogs. This method is
2913 * used by VpnSettings and not available in ConnectivityManager.
2914 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002915 * @hide
2916 */
2917 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002918 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2919 mVpn.startLegacyVpn(config, racoon, mtpd);
2920 }
2921
2922 /**
2923 * Return the information of the ongoing legacy VPN. This method is used
2924 * by VpnSettings and not available in ConnectivityManager. Permissions
2925 * are checked in Vpn class.
2926 * @hide
2927 */
2928 @Override
2929 public LegacyVpnInfo getLegacyVpnInfo() {
2930 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002931 }
2932
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002933 /**
2934 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2935 * through NetworkStateTracker since it works differently. For example, it
2936 * needs to override DNS servers but never takes the default routes. It
2937 * relies on another data network, and it could keep existing connections
2938 * alive after reconnecting, switching between networks, or even resuming
2939 * from deep sleep. Calls from applications should be done synchronously
2940 * to avoid race conditions. As these are all hidden APIs, refactoring can
2941 * be done whenever a better abstraction is developed.
2942 */
2943 public class VpnCallback {
2944
2945 private VpnCallback() {
2946 }
2947
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002948 public void override(List<String> dnsServers, List<String> searchDomains) {
2949 if (dnsServers == null) {
2950 restore();
2951 return;
2952 }
2953
2954 // Convert DNS servers into addresses.
2955 List<InetAddress> addresses = new ArrayList<InetAddress>();
2956 for (String address : dnsServers) {
2957 // Double check the addresses and remove invalid ones.
2958 try {
2959 addresses.add(InetAddress.parseNumericAddress(address));
2960 } catch (Exception e) {
2961 // ignore
2962 }
2963 }
2964 if (addresses.isEmpty()) {
2965 restore();
2966 return;
2967 }
2968
2969 // Concatenate search domains into a string.
2970 StringBuilder buffer = new StringBuilder();
2971 if (searchDomains != null) {
2972 for (String domain : searchDomains) {
2973 buffer.append(domain).append(' ');
2974 }
2975 }
2976 String domains = buffer.toString().trim();
2977
2978 // Apply DNS changes.
2979 boolean changed = false;
2980 synchronized (mDnsLock) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002981 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002982 mDnsOverridden = true;
2983 }
2984 if (changed) {
2985 bumpDns();
2986 }
2987
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002988 // Temporarily disable the default proxy.
2989 synchronized (mDefaultProxyLock) {
2990 mDefaultProxyDisabled = true;
2991 if (mDefaultProxy != null) {
2992 sendProxyBroadcast(null);
2993 }
2994 }
2995
2996 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002997 }
2998
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002999 public void restore() {
3000 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003001 if (mDnsOverridden) {
3002 mDnsOverridden = false;
3003 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003004 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003005 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003006 synchronized (mDefaultProxyLock) {
3007 mDefaultProxyDisabled = false;
3008 if (mDefaultProxy != null) {
3009 sendProxyBroadcast(mDefaultProxy);
3010 }
3011 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003012 }
3013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014}