blob: 359074a07c9966fb48309baba312e121fc3789cd [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
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700878 @Override
879 public boolean isActiveNetworkMetered() {
880 enforceAccessPermission();
881 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
882 if (state != null) {
883 try {
884 return mPolicyManager.isNetworkMetered(state);
885 } catch (RemoteException e) {
886 }
887 }
888 return false;
889 }
890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 public boolean setRadios(boolean turnOn) {
892 boolean result = true;
893 enforceChangePermission();
894 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700895 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
897 return result;
898 }
899
900 public boolean setRadio(int netType, boolean turnOn) {
901 enforceChangePermission();
902 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
903 return false;
904 }
905 NetworkStateTracker tracker = mNetTrackers[netType];
906 return tracker != null && tracker.setRadio(turnOn);
907 }
908
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700909 /**
910 * Used to notice when the calling process dies so we can self-expire
911 *
912 * Also used to know if the process has cleaned up after itself when
913 * our auto-expire timer goes off. The timer has a link to an object.
914 *
915 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700916 private class FeatureUser implements IBinder.DeathRecipient {
917 int mNetworkType;
918 String mFeature;
919 IBinder mBinder;
920 int mPid;
921 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800922 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700923
924 FeatureUser(int type, String feature, IBinder binder) {
925 super();
926 mNetworkType = type;
927 mFeature = feature;
928 mBinder = binder;
929 mPid = getCallingPid();
930 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800931 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700932
Robert Greenwalt42acef32009-08-12 16:08:25 -0700933 try {
934 mBinder.linkToDeath(this, 0);
935 } catch (RemoteException e) {
936 binderDied();
937 }
938 }
939
940 void unlinkDeathRecipient() {
941 mBinder.unlinkToDeath(this, 0);
942 }
943
944 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800945 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800946 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
947 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700948 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700949 }
950
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700951 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700952 if (VDBG) {
953 log("ConnectivityService FeatureUser expire(" +
954 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
955 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
956 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700957 stopUsingNetworkFeature(this, false);
958 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800959
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500960 public boolean isSameUser(FeatureUser u) {
961 if (u == null) return false;
962
963 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
964 }
965
966 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
967 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
968 TextUtils.equals(mFeature, feature)) {
969 return true;
970 }
971 return false;
972 }
973
Robert Greenwaltb9285352009-12-21 18:24:07 -0800974 public String toString() {
975 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
976 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
977 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700978 }
979
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700980 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700981 public int startUsingNetworkFeature(int networkType, String feature,
982 IBinder binder) {
Wink Savillec9acde92011-09-21 11:05:43 -0700983 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800984 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700987 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700988 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700989 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700991
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700992 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700993
repo syncaea743a2011-07-29 23:55:49 -0700994 // TODO - move this into individual networktrackers
995 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -0700996
997 if (mProtectedNetworks.contains(usedNetworkType)) {
998 enforceConnectivityInternalPermission();
999 }
1000
Robert Greenwalt42acef32009-08-12 16:08:25 -07001001 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1002 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001003 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001004 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001005 NetworkInfo ni = network.getNetworkInfo();
1006
1007 if (ni.isAvailable() == false) {
Robert Greenwalte32e8122010-12-29 14:35:21 -08001008 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
Wink Savillec7d7eaf2012-01-25 13:47:54 -08001009 if (DBG) log("special network not available ni=" + ni.getTypeName());
Robert Greenwalte32e8122010-12-29 14:35:21 -08001010 return Phone.APN_TYPE_NOT_AVAILABLE;
1011 } else {
1012 // else make the attempt anyway - probably giving REQUEST_STARTED below
Wink Savillec7d7eaf2012-01-25 13:47:54 -08001013 if (DBG) {
1014 log("special network not available, but try anyway ni=" +
1015 ni.getTypeName());
1016 }
Robert Greenwalte32e8122010-12-29 14:35:21 -08001017 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001018 }
1019
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001020 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1021
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001022 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001023 boolean addToList = true;
1024 if (restoreTimer < 0) {
1025 // In case there is no timer is specified for the feature,
1026 // make sure we don't add duplicate entry with the same request.
1027 for (FeatureUser u : mFeatureUsers) {
1028 if (u.isSameUser(f)) {
1029 // Duplicate user is found. Do not add.
1030 addToList = false;
1031 break;
1032 }
1033 }
1034 }
1035
1036 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001037 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1038 // this gets used for per-pid dns when connected
1039 mNetRequestersPids[usedNetworkType].add(currentPid);
1040 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001041 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001042
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001043 if (restoreTimer >= 0) {
1044 mHandler.sendMessageDelayed(
1045 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1046 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001047
Robert Greenwalta64bf832009-08-19 20:19:33 -07001048 if ((ni.isConnectedOrConnecting() == true) &&
1049 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001050 if (ni.isConnected() == true) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001051 final long token = Binder.clearCallingIdentity();
1052 try {
1053 // add the pid-specific dns
1054 handleDnsConfigurationChange(usedNetworkType);
1055 if (VDBG) log("special network already active");
1056 } finally {
1057 Binder.restoreCallingIdentity(token);
1058 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001059 return Phone.APN_ALREADY_ACTIVE;
1060 }
Wink Savillec9acde92011-09-21 11:05:43 -07001061 if (VDBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001062 return Phone.APN_REQUEST_STARTED;
1063 }
1064
1065 // check if the radio in play can make another contact
1066 // assume if cannot for now
1067
Wink Savillec9acde92011-09-21 11:05:43 -07001068 if (DBG) {
1069 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
1070 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001071 network.reconnect();
1072 return Phone.APN_REQUEST_STARTED;
1073 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001074 // need to remember this unsupported request so we respond appropriately on stop
1075 synchronized(this) {
1076 mFeatureUsers.add(f);
1077 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1078 // this gets used for per-pid dns when connected
1079 mNetRequestersPids[usedNetworkType].add(currentPid);
1080 }
1081 }
Robert Greenwalt02648a42010-05-18 10:52:51 -07001082 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001083 }
1084 }
1085 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001088 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001090 enforceChangePermission();
1091
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001092 int pid = getCallingPid();
1093 int uid = getCallingUid();
1094
1095 FeatureUser u = null;
1096 boolean found = false;
1097
1098 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001099 for (FeatureUser x : mFeatureUsers) {
1100 if (x.isSameUser(pid, uid, networkType, feature)) {
1101 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001102 found = true;
1103 break;
1104 }
1105 }
1106 }
1107 if (found && u != null) {
1108 // stop regardless of how many other time this proc had called start
1109 return stopUsingNetworkFeature(u, true);
1110 } else {
1111 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001112 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001113 return 1;
1114 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001115 }
1116
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001117 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1118 int networkType = u.mNetworkType;
1119 String feature = u.mFeature;
1120 int pid = u.mPid;
1121 int uid = u.mUid;
1122
1123 NetworkStateTracker tracker = null;
1124 boolean callTeardown = false; // used to carry our decision outside of sync block
1125
Wink Savillec9acde92011-09-21 11:05:43 -07001126 if (VDBG) {
1127 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001128 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001131 if (DBG) {
1132 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1133 ", net is invalid");
1134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 return -1;
1136 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001137
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001138 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1139 // sync block
1140 synchronized(this) {
1141 // check if this process still has an outstanding start request
1142 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001143 if (VDBG) {
1144 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1145 ", ignoring");
1146 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001147 return 1;
1148 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001149 u.unlinkDeathRecipient();
1150 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1151 // If we care about duplicate requests, check for that here.
1152 //
1153 // This is done to support the extension of a request - the app
1154 // can request we start the network feature again and renew the
1155 // auto-shutoff delay. Normal "stop" calls from the app though
1156 // do not pay attention to duplicate requests - in effect the
1157 // API does not refcount and a single stop will counter multiple starts.
1158 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001159 for (FeatureUser x : mFeatureUsers) {
1160 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001161 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001162 return 1;
1163 }
1164 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001165 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001166
repo syncaea743a2011-07-29 23:55:49 -07001167 // TODO - move to individual network trackers
1168 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1169
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001170 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001171 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001172 if (DBG) {
1173 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1174 " no known tracker for used net type " + usedNetworkType);
1175 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001176 return -1;
1177 }
1178 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001179 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001180 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001181 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001182 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001183 if (VDBG) {
1184 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1185 " others still using it");
1186 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001187 return 1;
1188 }
1189 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001190 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001191 if (DBG) {
1192 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1193 " not a known feature - dropping");
1194 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001195 }
1196 }
Wink Savillec9acde92011-09-21 11:05:43 -07001197
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001198 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001199 if (DBG) {
1200 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1201 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001202 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001203 return 1;
1204 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001205 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 }
1208
1209 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001210 * @deprecated use requestRouteToHostAddress instead
1211 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 * Ensure that a network route exists to deliver traffic to the specified
1213 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001214 * @param networkType the type of the network over which traffic to the
1215 * specified host is to be routed
1216 * @param hostAddress the IP address of the host to which the route is
1217 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 * @return {@code true} on success, {@code false} on failure
1219 */
1220 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001221 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1222
1223 if (inetAddress == null) {
1224 return false;
1225 }
1226
1227 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1228 }
1229
1230 /**
1231 * Ensure that a network route exists to deliver traffic to the specified
1232 * host via the specified network interface.
1233 * @param networkType the type of the network over which traffic to the
1234 * specified host is to be routed
1235 * @param hostAddress the IP address of the host to which the route is
1236 * desired
1237 * @return {@code true} on success, {@code false} on failure
1238 */
1239 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001241 if (mProtectedNetworks.contains(networkType)) {
1242 enforceConnectivityInternalPermission();
1243 }
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001246 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 return false;
1248 }
1249 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001250
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001251 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1252 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001253 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001254 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001255 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001256 }
1257 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001259 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001260 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001261 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001262 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001263 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001264 } catch (UnknownHostException e) {
1265 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1266 } finally {
1267 Binder.restoreCallingIdentity(token);
1268 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001269 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001270 }
1271
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001272 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1273 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001274 }
1275
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001276 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1277 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001278 }
1279
Robert Greenwaltad55d352011-07-22 11:55:33 -07001280 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001281 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001282 }
1283
1284 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001285 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001286 }
1287
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001288 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1289 boolean toDefaultTable) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001290 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1291 if (bestRoute == null) {
1292 bestRoute = RouteInfo.makeHostRoute(addr);
1293 } else {
1294 if (bestRoute.getGateway().equals(addr)) {
1295 // if there is no better route, add the implied hostroute for our gateway
1296 bestRoute = RouteInfo.makeHostRoute(addr);
1297 } else {
1298 // if we will connect to this through another route, add a direct route
1299 // to it's gateway
1300 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1301 }
1302 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001303 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001304 }
1305
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001306 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001307 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001308 if ((ifaceName == null) || (lp == null) || (r == null)) {
1309 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1310 return false;
1311 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001312
1313 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001314 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001315 return false;
1316 }
1317
1318 if (r.isHostRoute() == false) {
1319 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1320 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001321 if (bestRoute.getGateway().equals(r.getGateway())) {
1322 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001323 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001324 } else {
1325 // if we will connect to our gateway through another route, add a direct
1326 // route to it's gateway
1327 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001328 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001329 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001330 }
1331 }
1332 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001333 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001334 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001335 if (toDefaultTable) {
1336 mAddedRoutes.add(r); // only track default table - only one apps can effect
1337 mNetd.addRoute(ifaceName, r);
1338 } else {
1339 mNetd.addSecondaryRoute(ifaceName, r);
1340 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001341 } catch (Exception e) {
1342 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001343 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001344 return false;
1345 }
1346 } else {
1347 // if we remove this one and there are no more like it, then refcount==0 and
1348 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001349 if (toDefaultTable) {
1350 mAddedRoutes.remove(r);
1351 if (mAddedRoutes.contains(r) == false) {
1352 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1353 try {
1354 mNetd.removeRoute(ifaceName, r);
1355 } catch (Exception e) {
1356 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001357 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001358 return false;
1359 }
1360 } else {
1361 if (VDBG) log("not removing " + r + " as it's still in use");
1362 }
1363 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001364 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001365 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001366 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001367 } catch (Exception e) {
1368 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001369 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001370 return false;
1371 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001372 }
1373 }
1374 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376
1377 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001378 * @see ConnectivityManager#getMobileDataEnabled()
1379 */
1380 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001381 // TODO: This detail should probably be in DataConnectionTracker's
1382 // which is where we store the value and maybe make this
1383 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001384 enforceAccessPermission();
1385 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1386 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001387 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001388 return retVal;
1389 }
1390
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001391 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001392 enforceConnectivityInternalPermission();
1393
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001394 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1395 (met ? ENABLED : DISABLED), networkType));
1396 }
1397
1398 private void handleSetDependencyMet(int networkType, boolean met) {
1399 if (mNetTrackers[networkType] != null) {
1400 if (DBG) {
1401 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1402 }
1403 mNetTrackers[networkType].setDependencyMet(met);
1404 }
1405 }
1406
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001407 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1408 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001409 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001410 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001411 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001412 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001413 }
1414
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001415 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001416 // skip update when we've already applied rules
1417 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1418 if (oldRules == uidRules) return;
1419
1420 mUidRules.put(uid, uidRules);
1421 }
1422
1423 // TODO: dispatch into NMS to push rules towards kernel module
1424 // TODO: notify UID when it has requested targeted updates
1425 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001426
1427 @Override
1428 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001429 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001430 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001431 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001432 }
1433
1434 synchronized (mRulesLock) {
1435 mMeteredIfaces.clear();
1436 for (String iface : meteredIfaces) {
1437 mMeteredIfaces.add(iface);
1438 }
1439 }
1440 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001441
1442 @Override
1443 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1444 // caller is NPMS, since we only register with them
1445 if (LOGD_RULES) {
1446 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1447 }
1448
1449 // kick off connectivity change broadcast for active network, since
1450 // global background policy change is radical.
1451 final int networkType = mActiveDefaultNetwork;
1452 if (isNetworkTypeValid(networkType)) {
1453 final NetworkStateTracker tracker = mNetTrackers[networkType];
1454 if (tracker != null) {
1455 final NetworkInfo info = tracker.getNetworkInfo();
1456 if (info != null && info.isConnected()) {
1457 sendConnectedBroadcast(info);
1458 }
1459 }
1460 }
1461 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001462 };
1463
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001464 /**
1465 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1466 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001467 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001468 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001469 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001470
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001471 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001472 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001473 }
1474
1475 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001476 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001477 if (VDBG) {
1478 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001479 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001480 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1481 }
tk.munb97d34c2012-01-06 10:43:52 +09001482 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1483 if (VDBG) {
1484 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1485 }
1486 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1487 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001488 }
1489
1490 @Override
1491 public void setPolicyDataEnable(int networkType, boolean enabled) {
1492 // only someone like NPMS should only be calling us
1493 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1494
1495 mHandler.sendMessage(mHandler.obtainMessage(
1496 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1497 }
1498
1499 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1500 if (isNetworkTypeValid(networkType)) {
1501 final NetworkStateTracker tracker = mNetTrackers[networkType];
1502 if (tracker != null) {
1503 tracker.setPolicyDataEnable(enabled);
1504 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001505 }
1506 }
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001509 mContext.enforceCallingOrSelfPermission(
1510 android.Manifest.permission.ACCESS_NETWORK_STATE,
1511 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513
1514 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001515 mContext.enforceCallingOrSelfPermission(
1516 android.Manifest.permission.CHANGE_NETWORK_STATE,
1517 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001520 // TODO Make this a special check when it goes public
1521 private void enforceTetherChangePermission() {
1522 mContext.enforceCallingOrSelfPermission(
1523 android.Manifest.permission.CHANGE_NETWORK_STATE,
1524 "ConnectivityService");
1525 }
1526
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001527 private void enforceTetherAccessPermission() {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.ACCESS_NETWORK_STATE,
1530 "ConnectivityService");
1531 }
1532
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001533 private void enforceConnectivityInternalPermission() {
1534 mContext.enforceCallingOrSelfPermission(
1535 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1536 "ConnectivityService");
1537 }
1538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001540 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1541 * network, we ignore it. If it is for the active network, we send out a
1542 * broadcast. But first, we check whether it might be possible to connect
1543 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 * @param info the {@code NetworkInfo} for the network
1545 */
1546 private void handleDisconnect(NetworkInfo info) {
1547
Robert Greenwalt42acef32009-08-12 16:08:25 -07001548 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549
Robert Greenwalt42acef32009-08-12 16:08:25 -07001550 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 /*
1552 * If the disconnected network is not the active one, then don't report
1553 * this as a loss of connectivity. What probably happened is that we're
1554 * getting the disconnect for a network that we explicitly disabled
1555 * in accordance with network preference policies.
1556 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001557 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001558 List pids = mNetRequestersPids[prevNetType];
1559 for (int i = 0; i<pids.size(); i++) {
1560 Integer pid = (Integer)pids.get(i);
1561 // will remove them because the net's no longer connected
1562 // need to do this now as only now do we know the pids and
1563 // can properly null things that are no longer referenced.
1564 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1569 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1570 if (info.isFailover()) {
1571 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1572 info.setFailover(false);
1573 }
1574 if (info.getReason() != null) {
1575 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1576 }
1577 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001578 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1579 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001581
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001582 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001583 tryFailover(prevNetType);
1584 if (mActiveDefaultNetwork != -1) {
1585 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001586 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1587 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001588 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001589 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1590 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001591 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001592 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001593
1594 // Reset interface if no other connections are using the same interface
1595 boolean doReset = true;
1596 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1597 if (linkProperties != null) {
1598 String oldIface = linkProperties.getInterfaceName();
1599 if (TextUtils.isEmpty(oldIface) == false) {
1600 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1601 if (networkStateTracker == null) continue;
1602 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1603 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1604 LinkProperties l = networkStateTracker.getLinkProperties();
1605 if (l == null) continue;
1606 if (oldIface.equals(l.getInterfaceName())) {
1607 doReset = false;
1608 break;
1609 }
1610 }
1611 }
1612 }
1613 }
1614
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001615 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001616 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001617
Jeff Sharkey961e3042011-08-29 16:02:57 -07001618 final Intent immediateIntent = new Intent(intent);
1619 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1620 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001621 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001622 /*
1623 * If the failover network is already connected, then immediately send
1624 * out a followup broadcast indicating successful failover
1625 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001626 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001627 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1628 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001629 }
1630 }
1631
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001632 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001633 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001634 * If this is a default network, check if other defaults are available.
1635 * Try to reconnect on all available and let them hash it out when
1636 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001637 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001638 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001639 if (mActiveDefaultNetwork == prevNetType) {
1640 mActiveDefaultNetwork = -1;
1641 }
1642
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001643 // don't signal a reconnect for anything lower or equal priority than our
1644 // current connected default
1645 // TODO - don't filter by priority now - nice optimization but risky
1646// int currentPriority = -1;
1647// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001648// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001649// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001650 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001651 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001652 if (mNetConfigs[checkType] == null) continue;
1653 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001654 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001655
1656// Enabling the isAvailable() optimization caused mobile to not get
1657// selected if it was in the middle of error handling. Specifically
1658// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1659// would not be available and we wouldn't get connected to anything.
1660// So removing the isAvailable() optimization below for now. TODO: This
1661// optimization should work and we need to investigate why it doesn't work.
1662// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1663// complete before it is really complete.
1664// if (!mNetTrackers[checkType].isAvailable()) continue;
1665
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001666// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001667
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001668 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1669 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1670 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1671 checkInfo.setFailover(true);
1672 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001673 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001674 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678
1679 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001680 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1681 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001682 }
1683
Wink Saville628b0852011-08-04 15:01:58 -07001684 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001685 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1686 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001687 }
1688
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001689 private void sendInetConditionBroadcast(NetworkInfo info) {
1690 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1691 }
1692
Wink Saville628b0852011-08-04 15:01:58 -07001693 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001694 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1696 if (info.isFailover()) {
1697 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1698 info.setFailover(false);
1699 }
1700 if (info.getReason() != null) {
1701 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1702 }
1703 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001704 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1705 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001707 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001708 return intent;
1709 }
1710
1711 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1712 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1713 }
1714
1715 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1716 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
1718
1719 /**
1720 * Called when an attempt to fail over to another network has failed.
1721 * @param info the {@link NetworkInfo} for the failed network
1722 */
1723 private void handleConnectionFailure(NetworkInfo info) {
1724 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726 String reason = info.getReason();
1727 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001728
Robert Greenwalt572172b2010-10-08 16:35:52 -07001729 String reasonText;
1730 if (reason == null) {
1731 reasonText = ".";
1732 } else {
1733 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001735 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001736
1737 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1738 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1739 if (getActiveNetworkInfo() == null) {
1740 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1741 }
1742 if (reason != null) {
1743 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1744 }
1745 if (extraInfo != null) {
1746 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1747 }
1748 if (info.isFailover()) {
1749 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1750 info.setFailover(false);
1751 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001752
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001753 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001754 tryFailover(info.getType());
1755 if (mActiveDefaultNetwork != -1) {
1756 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001757 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1758 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001759 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001760 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1761 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001762 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001763
Robert Greenwalt029be812010-09-20 18:01:43 -07001764 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001765
1766 final Intent immediateIntent = new Intent(intent);
1767 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1768 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001769 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001770 /*
1771 * If the failover network is already connected, then immediately send
1772 * out a followup broadcast indicating successful failover
1773 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001774 if (mActiveDefaultNetwork != -1) {
1775 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001776 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001777 }
1778
1779 private void sendStickyBroadcast(Intent intent) {
1780 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001781 if (!mSystemReady) {
1782 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001783 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001784 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001785 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001786 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001787 }
1788
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001789 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001790 }
1791 }
1792
Wink Saville628b0852011-08-04 15:01:58 -07001793 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1794 if (delayMs <= 0) {
1795 sendStickyBroadcast(intent);
1796 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001797 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001798 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1799 + intent.getAction());
1800 }
Wink Saville628b0852011-08-04 15:01:58 -07001801 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1802 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1803 }
1804 }
1805
Mike Lockwood0f79b542009-08-14 14:18:49 -04001806 void systemReady() {
1807 synchronized(this) {
1808 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001809 if (mInitialBroadcast != null) {
1810 mContext.sendStickyBroadcast(mInitialBroadcast);
1811 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001812 }
1813 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001814 // load the global proxy at startup
1815 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
1817
1818 private void handleConnect(NetworkInfo info) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001819 final int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820
1821 // snapshot isFailover, because sendConnectedBroadcast() resets it
1822 boolean isFailover = info.isFailover();
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001823 final NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824
Robert Greenwalt42acef32009-08-12 16:08:25 -07001825 // if this is a default net and other default is running
1826 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001827 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001828 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1829 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001830 mNetConfigs[mActiveDefaultNetwork].priority >
1831 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001832 mNetworkPreference == mActiveDefaultNetwork) {
1833 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001834 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001835 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001836 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001837 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001838 teardown(thisNet);
1839 return;
1840 } else {
1841 // tear down the other
1842 NetworkStateTracker otherNet =
1843 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001844 if (DBG) {
1845 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001846 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001847 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001848 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001849 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001850 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001851 return;
1852 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001853 }
1854 }
1855 synchronized (ConnectivityService.this) {
1856 // have a new default network, release the transition wakelock in a second
1857 // if it's held. The second pause is to allow apps to reconnect over the
1858 // new network
1859 if (mNetTransitionWakeLock.isHeld()) {
1860 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001861 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001862 mNetTransitionWakeLockSerialNumber, 0),
1863 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001864 }
1865 }
1866 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001867 // this will cause us to come up initially as unconnected and switching
1868 // to connected after our normal pause unless somebody reports us as reall
1869 // disconnected
1870 mDefaultInetConditionPublished = 0;
1871 mDefaultConnectionSequence++;
1872 mInetConditionChangeInFlight = false;
1873 // Don't do this - if we never sign in stay, grey
1874 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001877 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001878 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001879 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07001880
1881 // notify battery stats service about this network
1882 final String iface = thisNet.getLinkProperties().getInterfaceName();
1883 if (iface != null) {
1884 try {
1885 BatteryStatsService.getService().noteNetworkInterfaceType(iface, type);
1886 } catch (RemoteException e) {
1887 // ignored; service lives in system_server
1888 }
1889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
1891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001893 * After a change in the connectivity state of a network. We're mainly
1894 * concerned with making sure that the list of DNS servers is set up
1895 * according to which networks are connected, and ensuring that the
1896 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001898 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001899 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001903 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001905 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001906
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001907 LinkProperties curLp = mCurrentLinkProperties[netType];
1908 LinkProperties newLp = null;
1909
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001910 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001911 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001912 if (VDBG) {
1913 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1914 " doReset=" + doReset + " resetMask=" + resetMask +
1915 "\n curLp=" + curLp +
1916 "\n newLp=" + newLp);
1917 }
1918
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001919 if (curLp != null) {
1920 if (curLp.isIdenticalInterfaceName(newLp)) {
1921 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1922 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1923 for (LinkAddress linkAddr : car.removed) {
1924 if (linkAddr.getAddress() instanceof Inet4Address) {
1925 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1926 }
1927 if (linkAddr.getAddress() instanceof Inet6Address) {
1928 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1929 }
Wink Savillee8222252011-07-13 13:44:13 -07001930 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001931 if (DBG) {
1932 log("handleConnectivityChange: addresses changed" +
1933 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1934 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001935 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001936 } else {
1937 if (DBG) {
1938 log("handleConnectivityChange: address are the same reset per doReset" +
1939 " linkProperty[" + netType + "]:" +
1940 " resetMask=" + resetMask);
1941 }
Wink Savillee8222252011-07-13 13:44:13 -07001942 }
1943 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001944 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001945 if (DBG) {
1946 log("handleConnectivityChange: interface not not equivalent reset both" +
1947 " linkProperty[" + netType + "]:" +
1948 " resetMask=" + resetMask);
1949 }
Wink Savillee8222252011-07-13 13:44:13 -07001950 }
Wink Savillee8222252011-07-13 13:44:13 -07001951 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001952 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07001953 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001954 }
1955 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001956 if (VDBG) {
1957 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1958 " doReset=" + doReset + " resetMask=" + resetMask +
1959 "\n curLp=" + curLp +
1960 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001963 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001964 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001965
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001966 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001967 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1968 if (linkProperties != null) {
1969 String iface = linkProperties.getInterfaceName();
1970 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001971 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001972 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1973 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001974
1975 // Tell VPN the interface is down. It is a temporary
1976 // but effective fix to make VPN aware of the change.
1977 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1978 mVpn.interfaceStatusChanged(iface, false);
1979 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001980 }
1981 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07001982 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001983 try {
1984 mNetd.flushInterfaceDnsCache(iface);
1985 } catch (Exception e) {
1986 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001987 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001988 }
1989 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001990 }
1991 }
1992 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001993
1994 // TODO: Temporary notifying upstread change to Tethering.
1995 // @see bug/4455071
1996 /** Notify TetheringService if interface name has been changed. */
1997 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1998 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1999 if (isTetheringSupported()) {
2000 mTethering.handleTetherIfaceChange();
2001 }
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002005 /**
2006 * Add and remove routes using the old properties (null if not previously connected),
2007 * new properties (null if becoming disconnected). May even be double null, which
2008 * is a noop.
2009 * Uses isLinkDefault to determine if default routes should be set or conversely if
2010 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002011 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002012 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002013 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2014 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002015 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002016 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2017 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002018 if (curLp != null) {
2019 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002020 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002021 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002022 } else if (newLp != null) {
2023 routeDiff.added = newLp.getRoutes();
2024 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002025 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002026
Robert Greenwaltf125a092011-08-15 12:31:55 -07002027 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2028
Robert Greenwaltad55d352011-07-22 11:55:33 -07002029 for (RouteInfo r : routeDiff.removed) {
2030 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002031 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2032 }
2033 if (isLinkDefault == false) {
2034 // remove from a secondary route table
2035 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002036 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002037 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002038
Robert Greenwaltad55d352011-07-22 11:55:33 -07002039 for (RouteInfo r : routeDiff.added) {
2040 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002041 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002042 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002043 // add to a secondary route table
2044 addRoute(newLp, r, TO_SECONDARY_TABLE);
2045
Robert Greenwalte6b24292011-08-09 16:52:58 -07002046 // many radios add a default route even when we don't want one.
2047 // remove the default route unless somebody else has asked for it
2048 String ifaceName = newLp.getInterfaceName();
2049 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002050 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002051 try {
2052 mNetd.removeRoute(ifaceName, r);
2053 } catch (Exception e) {
2054 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08002055 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002056 }
2057 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002058 }
2059 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002060
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002061 if (!isLinkDefault) {
2062 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002063 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002064 // routes changed - remove all old dns entries and add new
2065 if (curLp != null) {
2066 for (InetAddress oldDns : curLp.getDnses()) {
2067 removeRouteToAddress(curLp, oldDns);
2068 }
2069 }
2070 if (newLp != null) {
2071 for (InetAddress newDns : newLp.getDnses()) {
2072 addRouteToAddress(newLp, newDns);
2073 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002074 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002075 } else {
2076 // no change in routes, check for change in dns themselves
2077 for (InetAddress oldDns : dnsDiff.removed) {
2078 removeRouteToAddress(curLp, oldDns);
2079 }
2080 for (InetAddress newDns : dnsDiff.added) {
2081 addRouteToAddress(newLp, newDns);
2082 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002083 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002084 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002085 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002086 }
2087
2088
Irfan Sheriffd649c122010-06-09 15:39:36 -07002089 /**
2090 * Reads the network specific TCP buffer sizes from SystemProperties
2091 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2092 * wide use
2093 */
2094 public void updateNetworkSettings(NetworkStateTracker nt) {
2095 String key = nt.getTcpBufferSizesPropName();
2096 String bufferSizes = SystemProperties.get(key);
2097
2098 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002099 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002100
2101 // Setting to default values so we won't be stuck to previous values
2102 key = "net.tcp.buffersize.default";
2103 bufferSizes = SystemProperties.get(key);
2104 }
2105
2106 // Set values in kernel
2107 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002108 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002109 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002110 + "] which comes from [" + key + "]");
2111 }
2112 setBufferSize(bufferSizes);
2113 }
2114 }
2115
2116 /**
2117 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2118 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2119 *
2120 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2121 * writeMin, writeInitial, writeMax"
2122 */
2123 private void setBufferSize(String bufferSizes) {
2124 try {
2125 String[] values = bufferSizes.split(",");
2126
2127 if (values.length == 6) {
2128 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002129 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2130 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2131 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2132 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2133 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2134 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002135 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002136 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002137 }
2138 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002139 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002140 }
2141 }
2142
Robert Greenwalt42acef32009-08-12 16:08:25 -07002143 /**
2144 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2145 * on the highest priority active net which this process requested.
2146 * If there aren't any, clear it out
2147 */
2148 private void reassessPidDns(int myPid, boolean doBump)
2149 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002150 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002151 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002152 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002153 continue;
2154 }
2155 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002156 if (nt.getNetworkInfo().isConnected() &&
2157 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002158 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002159 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002160 List pids = mNetRequestersPids[i];
2161 for (int j=0; j<pids.size(); j++) {
2162 Integer pid = (Integer)pids.get(j);
2163 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002164 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002165 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002166 if (doBump) {
2167 bumpDns();
2168 }
2169 return;
2170 }
2171 }
2172 }
2173 }
2174 // nothing found - delete
2175 for (int i = 1; ; i++) {
2176 String prop = "net.dns" + i + "." + myPid;
2177 if (SystemProperties.get(prop).length() == 0) {
2178 if (doBump) {
2179 bumpDns();
2180 }
2181 return;
2182 }
2183 SystemProperties.set(prop, "");
2184 }
2185 }
2186
Robert Greenwalt10398722010-12-17 15:20:36 -08002187 // return true if results in a change
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002188 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002189 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002190 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002191 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002192 String dnsString = dns.getHostAddress();
2193 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2194 changed = true;
yoonsung.nam7b72ea72012-03-02 19:56:16 +09002195 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt10398722010-12-17 15:20:36 -08002196 }
yoonsung.nam7b72ea72012-03-02 19:56:16 +09002197 j++;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002198 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002199 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002200 }
2201
2202 private void bumpDns() {
2203 /*
2204 * Bump the property that tells the name resolver library to reread
2205 * the DNS server list from the properties.
2206 */
2207 String propVal = SystemProperties.get("net.dnschange");
2208 int n = 0;
2209 if (propVal.length() != 0) {
2210 try {
2211 n = Integer.parseInt(propVal);
2212 } catch (NumberFormatException e) {}
2213 }
2214 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002215 /*
2216 * Tell the VMs to toss their DNS caches
2217 */
2218 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2219 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002220 /*
2221 * Connectivity events can happen before boot has completed ...
2222 */
2223 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002224 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002225 }
2226
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002227 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002228 private boolean updateDns(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002229 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002230 boolean changed = false;
2231 int last = 0;
2232 if (dnses.size() == 0 && mDefaultDns != null) {
2233 ++last;
2234 String value = mDefaultDns.getHostAddress();
2235 if (!value.equals(SystemProperties.get("net.dns1"))) {
2236 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002237 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002238 }
2239 changed = true;
2240 SystemProperties.set("net.dns1", value);
2241 }
2242 } else {
2243 for (InetAddress dns : dnses) {
2244 ++last;
2245 String key = "net.dns" + last;
2246 String value = dns.getHostAddress();
2247 if (!changed && value.equals(SystemProperties.get(key))) {
2248 continue;
2249 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002250 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002251 log("adding dns " + value + " for " + network);
2252 }
2253 changed = true;
2254 SystemProperties.set(key, value);
2255 }
2256 }
2257 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2258 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002259 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002260 changed = true;
2261 SystemProperties.set(key, "");
2262 }
2263 mNumDnsEntries = last;
2264
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002265 if (changed) {
2266 try {
2267 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2268 mNetd.setDefaultInterfaceForDns(iface);
2269 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002270 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002271 }
2272 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002273 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2274 SystemProperties.set("net.dns.search", domains);
2275 changed = true;
2276 }
2277 return changed;
2278 }
2279
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002280 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002281 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002282 NetworkStateTracker nt = mNetTrackers[netType];
2283 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002284 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002285 if (p == null) return;
2286 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002287 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002288 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002289 String network = nt.getNetworkInfo().getTypeName();
2290 synchronized (mDnsLock) {
2291 if (!mDnsOverridden) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002292 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002293 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002294 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002295 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002296 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002297 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002298 NetworkUtils.makeStrings(dnses));
2299 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002300 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002301 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002302 // set per-pid dns for attached secondary nets
2303 List pids = mNetRequestersPids[netType];
2304 for (int y=0; y< pids.size(); y++) {
2305 Integer pid = (Integer)pids.get(y);
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002306 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 }
2308 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002309 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002311 }
2312
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002313 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002314 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2315 NETWORK_RESTORE_DELAY_PROP_NAME);
2316 if(restoreDefaultNetworkDelayStr != null &&
2317 restoreDefaultNetworkDelayStr.length() != 0) {
2318 try {
2319 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2320 } catch (NumberFormatException e) {
2321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002323 // if the system property isn't set, use the value for the apn type
2324 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2325
2326 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2327 (mNetConfigs[networkType] != null)) {
2328 ret = mNetConfigs[networkType].restoreTime;
2329 }
2330 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332
2333 @Override
2334 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002335 if (mContext.checkCallingOrSelfPermission(
2336 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002338 pw.println("Permission Denial: can't dump ConnectivityService " +
2339 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2340 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 return;
2342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 pw.println();
2344 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002345 if (nst != null) {
2346 if (nst.getNetworkInfo().isConnected()) {
2347 pw.println("Active network: " + nst.getNetworkInfo().
2348 getTypeName());
2349 }
2350 pw.println(nst.getNetworkInfo());
2351 pw.println(nst);
2352 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002355
2356 pw.println("Network Requester Pids:");
2357 for (int net : mPriorityList) {
2358 String pidString = net + ": ";
2359 for (Object pid : mNetRequestersPids[net]) {
2360 pidString = pidString + pid.toString() + ", ";
2361 }
2362 pw.println(pidString);
2363 }
2364 pw.println();
2365
2366 pw.println("FeatureUsers:");
2367 for (Object requester : mFeatureUsers) {
2368 pw.println(requester.toString());
2369 }
2370 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002371
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002372 synchronized (this) {
2373 pw.println("NetworkTranstionWakeLock is currently " +
2374 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2375 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2376 }
2377 pw.println();
2378
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002379 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002380
2381 if (mInetLog != null) {
2382 pw.println();
2383 pw.println("Inet condition reports:");
2384 for(int i = 0; i < mInetLog.size(); i++) {
2385 pw.println(mInetLog.get(i));
2386 }
2387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
2389
Robert Greenwalt42acef32009-08-12 16:08:25 -07002390 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002392 public MyHandler(Looper looper) {
2393 super(looper);
2394 }
2395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 @Override
2397 public void handleMessage(Message msg) {
2398 NetworkInfo info;
2399 switch (msg.what) {
2400 case NetworkStateTracker.EVENT_STATE_CHANGED:
2401 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002402 int type = info.getType();
2403 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002404
Wink Savillec9acde92011-09-21 11:05:43 -07002405 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2406 (state == NetworkInfo.State.DISCONNECTED)) {
2407 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002408 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002409 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411
2412 // Connectivity state changed:
2413 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002414 // [12-9] Network subtype (for mobile network, as defined
2415 // by TelephonyManager)
2416 // [8-3] Detailed state ordinal (as defined by
2417 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 // [2-0] Network type (as defined by ConnectivityManager)
2419 int eventLogParam = (info.getType() & 0x7) |
2420 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2421 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002422 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002423 eventLogParam);
2424
2425 if (info.getDetailedState() ==
2426 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002428 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002430 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002432 // the logic here is, handle SUSPENDED the same as
2433 // DISCONNECTED. The only difference being we are
2434 // broadcasting an intent with NetworkInfo that's
2435 // suspended. This allows the applications an
2436 // opportunity to handle DISCONNECTED and SUSPENDED
2437 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002439 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 handleConnect(info);
2441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002444 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002445 // TODO: Temporary allowing network configuration
2446 // change not resetting sockets.
2447 // @see bug/4455071
2448 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002450 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002451 String causedBy = null;
2452 synchronized (ConnectivityService.this) {
2453 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2454 mNetTransitionWakeLock.isHeld()) {
2455 mNetTransitionWakeLock.release();
2456 causedBy = mNetTransitionWakeLockCausedBy;
2457 }
2458 }
2459 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002460 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002461 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002462 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002463 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002464 FeatureUser u = (FeatureUser)msg.obj;
2465 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002466 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002467 case EVENT_INET_CONDITION_CHANGE:
2468 {
2469 int netType = msg.arg1;
2470 int condition = msg.arg2;
2471 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002472 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002473 }
2474 case EVENT_INET_CONDITION_HOLD_END:
2475 {
2476 int netType = msg.arg1;
2477 int sequence = msg.arg2;
2478 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002479 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002480 }
2481 case EVENT_SET_NETWORK_PREFERENCE:
2482 {
2483 int preference = msg.arg1;
2484 handleSetNetworkPreference(preference);
2485 break;
2486 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002487 case EVENT_SET_MOBILE_DATA:
2488 {
2489 boolean enabled = (msg.arg1 == ENABLED);
2490 handleSetMobileData(enabled);
2491 break;
2492 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002493 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2494 {
2495 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002496 break;
2497 }
2498 case EVENT_SET_DEPENDENCY_MET:
2499 {
2500 boolean met = (msg.arg1 == ENABLED);
2501 handleSetDependencyMet(msg.arg2, met);
2502 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002503 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002504 case EVENT_RESTORE_DNS:
2505 {
2506 if (mActiveDefaultNetwork != -1) {
2507 handleDnsConfigurationChange(mActiveDefaultNetwork);
2508 }
2509 break;
2510 }
Wink Saville628b0852011-08-04 15:01:58 -07002511 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2512 {
2513 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002514 sendStickyBroadcast(intent);
2515 break;
2516 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002517 case EVENT_SET_POLICY_DATA_ENABLE: {
2518 final int networkType = msg.arg1;
2519 final boolean enabled = msg.arg2 == ENABLED;
2520 handleSetPolicyDataEnable(networkType, enabled);
2521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 }
2523 }
2524 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002525
2526 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002527 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002528 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002529
2530 if (isTetheringSupported()) {
2531 return mTethering.tether(iface);
2532 } else {
2533 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2534 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002535 }
2536
2537 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002538 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002539 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002540
2541 if (isTetheringSupported()) {
2542 return mTethering.untether(iface);
2543 } else {
2544 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2545 }
2546 }
2547
2548 // javadoc from interface
2549 public int getLastTetherError(String iface) {
2550 enforceTetherAccessPermission();
2551
2552 if (isTetheringSupported()) {
2553 return mTethering.getLastTetherError(iface);
2554 } else {
2555 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2556 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002557 }
2558
2559 // TODO - proper iface API for selection by property, inspection, etc
2560 public String[] getTetherableUsbRegexs() {
2561 enforceTetherAccessPermission();
2562 if (isTetheringSupported()) {
2563 return mTethering.getTetherableUsbRegexs();
2564 } else {
2565 return new String[0];
2566 }
2567 }
2568
2569 public String[] getTetherableWifiRegexs() {
2570 enforceTetherAccessPermission();
2571 if (isTetheringSupported()) {
2572 return mTethering.getTetherableWifiRegexs();
2573 } else {
2574 return new String[0];
2575 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002576 }
2577
Danica Chang6fdd0c62010-08-11 14:54:43 -07002578 public String[] getTetherableBluetoothRegexs() {
2579 enforceTetherAccessPermission();
2580 if (isTetheringSupported()) {
2581 return mTethering.getTetherableBluetoothRegexs();
2582 } else {
2583 return new String[0];
2584 }
2585 }
2586
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002587 public int setUsbTethering(boolean enable) {
2588 enforceTetherAccessPermission();
2589 if (isTetheringSupported()) {
2590 return mTethering.setUsbTethering(enable);
2591 } else {
2592 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2593 }
2594 }
2595
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002596 // TODO - move iface listing, queries, etc to new module
2597 // javadoc from interface
2598 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002599 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002600 return mTethering.getTetherableIfaces();
2601 }
2602
2603 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002604 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002605 return mTethering.getTetheredIfaces();
2606 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002607
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002608 @Override
2609 public String[] getTetheredIfacePairs() {
2610 enforceTetherAccessPermission();
2611 return mTethering.getTetheredIfacePairs();
2612 }
2613
Robert Greenwalt5a735062010-03-02 17:25:02 -08002614 public String[] getTetheringErroredIfaces() {
2615 enforceTetherAccessPermission();
2616 return mTethering.getErroredIfaces();
2617 }
2618
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002619 // if ro.tether.denied = true we default to no tethering
2620 // gservices could set the secure setting to 1 though to enable it on a build where it
2621 // had previously been turned off.
2622 public boolean isTetheringSupported() {
2623 enforceTetherAccessPermission();
2624 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002625 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2626 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2627 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002628 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002629
2630 // An API NetworkStateTrackers can call when they lose their network.
2631 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2632 // whichever happens first. The timer is started by the first caller and not
2633 // restarted by subsequent callers.
2634 public void requestNetworkTransitionWakelock(String forWhom) {
2635 enforceConnectivityInternalPermission();
2636 synchronized (this) {
2637 if (mNetTransitionWakeLock.isHeld()) return;
2638 mNetTransitionWakeLockSerialNumber++;
2639 mNetTransitionWakeLock.acquire();
2640 mNetTransitionWakeLockCausedBy = forWhom;
2641 }
2642 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002643 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002644 mNetTransitionWakeLockSerialNumber, 0),
2645 mNetTransitionWakeLockTimeout);
2646 return;
2647 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002648
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002649 // 100 percent is full good, 0 is full bad.
2650 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002651 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002652 mContext.enforceCallingOrSelfPermission(
2653 android.Manifest.permission.STATUS_BAR,
2654 "ConnectivityService");
2655
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002656 if (DBG) {
2657 int pid = getCallingPid();
2658 int uid = getCallingUid();
2659 String s = pid + "(" + uid + ") reports inet is " +
2660 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2661 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2662 mInetLog.add(s);
2663 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2664 mInetLog.remove(0);
2665 }
2666 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002667 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002668 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2669 }
2670
2671 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002672 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002673 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002674 return;
2675 }
2676 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002677 if (DBG) log("handleInetConditionChange: net=" + netType +
2678 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002679 return;
2680 }
Wink Savillec9acde92011-09-21 11:05:43 -07002681 if (VDBG) {
2682 log("handleInetConditionChange: net=" +
2683 netType + ", condition=" + condition +
2684 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2685 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002686 mDefaultInetCondition = condition;
2687 int delay;
2688 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002689 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002690 // setup a new hold to debounce this
2691 if (mDefaultInetCondition > 50) {
2692 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2693 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2694 } else {
2695 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2696 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2697 }
2698 mInetConditionChangeInFlight = true;
2699 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2700 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2701 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002702 // we've set the new condition, when this hold ends that will get picked up
2703 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002704 }
2705 }
2706
2707 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002708 if (DBG) {
2709 log("handleInetConditionHoldEnd: net=" + netType +
2710 ", condition=" + mDefaultInetCondition +
2711 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002712 }
2713 mInetConditionChangeInFlight = false;
2714
2715 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002716 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002717 return;
2718 }
2719 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002720 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002721 return;
2722 }
Wink Saville628b0852011-08-04 15:01:58 -07002723 // TODO: Figure out why this optimization sometimes causes a
2724 // change in mDefaultInetCondition to be missed and the
2725 // UI to not be updated.
2726 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2727 // if (DBG) log("no change in condition - aborting");
2728 // return;
2729 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002730 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2731 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002732 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002733 return;
2734 }
2735 mDefaultInetConditionPublished = mDefaultInetCondition;
2736 sendInetConditionBroadcast(networkInfo);
2737 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002738 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002739
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002740 public ProxyProperties getProxy() {
2741 synchronized (mDefaultProxyLock) {
2742 return mDefaultProxyDisabled ? null : mDefaultProxy;
2743 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002744 }
2745
2746 public void setGlobalProxy(ProxyProperties proxyProperties) {
2747 enforceChangePermission();
2748 synchronized (mGlobalProxyLock) {
2749 if (proxyProperties == mGlobalProxy) return;
2750 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2751 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2752
2753 String host = "";
2754 int port = 0;
2755 String exclList = "";
2756 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2757 mGlobalProxy = new ProxyProperties(proxyProperties);
2758 host = mGlobalProxy.getHost();
2759 port = mGlobalProxy.getPort();
2760 exclList = mGlobalProxy.getExclusionList();
2761 } else {
2762 mGlobalProxy = null;
2763 }
2764 ContentResolver res = mContext.getContentResolver();
2765 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2766 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002767 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002768 exclList);
2769 }
2770
2771 if (mGlobalProxy == null) {
2772 proxyProperties = mDefaultProxy;
2773 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07002774 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002775 }
2776
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002777 private void loadGlobalProxy() {
2778 ContentResolver res = mContext.getContentResolver();
2779 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2780 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2781 String exclList = Settings.Secure.getString(res,
2782 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2783 if (!TextUtils.isEmpty(host)) {
2784 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2785 synchronized (mGlobalProxyLock) {
2786 mGlobalProxy = proxyProperties;
2787 }
2788 }
2789 }
2790
Robert Greenwalt434203a2010-10-11 16:00:27 -07002791 public ProxyProperties getGlobalProxy() {
2792 synchronized (mGlobalProxyLock) {
2793 return mGlobalProxy;
2794 }
2795 }
2796
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002797 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2798 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2799 proxy = null;
2800 }
2801 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002802 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2803 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002804 mDefaultProxy = proxy;
2805
2806 if (!mDefaultProxyDisabled) {
2807 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002808 }
2809 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002810 }
2811
2812 private void handleDeprecatedGlobalHttpProxy() {
2813 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2814 Settings.Secure.HTTP_PROXY);
2815 if (!TextUtils.isEmpty(proxy)) {
2816 String data[] = proxy.split(":");
2817 String proxyHost = data[0];
2818 int proxyPort = 8080;
2819 if (data.length > 1) {
2820 try {
2821 proxyPort = Integer.parseInt(data[1]);
2822 } catch (NumberFormatException e) {
2823 return;
2824 }
2825 }
2826 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2827 setGlobalProxy(p);
2828 }
2829 }
2830
2831 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002832 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002833 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002835 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2836 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002837 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002838 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002839 }
2840
2841 private static class SettingsObserver extends ContentObserver {
2842 private int mWhat;
2843 private Handler mHandler;
2844 SettingsObserver(Handler handler, int what) {
2845 super(handler);
2846 mHandler = handler;
2847 mWhat = what;
2848 }
2849
2850 void observe(Context context) {
2851 ContentResolver resolver = context.getContentResolver();
2852 resolver.registerContentObserver(Settings.Secure.getUriFor(
2853 Settings.Secure.HTTP_PROXY), false, this);
2854 }
2855
2856 @Override
2857 public void onChange(boolean selfChange) {
2858 mHandler.obtainMessage(mWhat).sendToTarget();
2859 }
2860 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002861
2862 private void log(String s) {
2863 Slog.d(TAG, s);
2864 }
2865
2866 private void loge(String s) {
2867 Slog.e(TAG, s);
2868 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002869
repo syncaea743a2011-07-29 23:55:49 -07002870 int convertFeatureToNetworkType(int networkType, String feature) {
2871 int usedNetworkType = networkType;
2872
2873 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2874 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2875 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2876 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2877 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2878 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2879 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2880 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2881 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2882 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2883 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2884 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2885 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2886 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2887 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2888 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2889 } else {
2890 Slog.e(TAG, "Can't match any mobile netTracker!");
2891 }
2892 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2893 if (TextUtils.equals(feature, "p2p")) {
2894 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2895 } else {
2896 Slog.e(TAG, "Can't match any wifi netTracker!");
2897 }
2898 } else {
2899 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002900 }
repo syncaea743a2011-07-29 23:55:49 -07002901 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002902 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002903
2904 private static <T> T checkNotNull(T value, String message) {
2905 if (value == null) {
2906 throw new NullPointerException(message);
2907 }
2908 return value;
2909 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002910
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002911 /**
2912 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002913 * VpnBuilder and not available in ConnectivityManager. Permissions
2914 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002915 * @hide
2916 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002917 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002918 public boolean protectVpn(ParcelFileDescriptor socket) {
2919 try {
2920 int type = mActiveDefaultNetwork;
2921 if (ConnectivityManager.isNetworkTypeValid(type)) {
2922 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2923 return true;
2924 }
2925 } catch (Exception e) {
2926 // ignore
2927 } finally {
2928 try {
2929 socket.close();
2930 } catch (Exception e) {
2931 // ignore
2932 }
2933 }
2934 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002935 }
2936
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002937 /**
2938 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002939 * and not available in ConnectivityManager. Permissions are checked
2940 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002941 * @hide
2942 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002943 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002944 public boolean prepareVpn(String oldPackage, String newPackage) {
2945 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002946 }
2947
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002948 /**
2949 * Configure a TUN interface and return its file descriptor. Parameters
2950 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002951 * and not available in ConnectivityManager. Permissions are checked in
2952 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002953 * @hide
2954 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002955 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002956 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002957 return mVpn.establish(config);
2958 }
2959
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002960 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002961 * Start legacy VPN and return an intent to VpnDialogs. This method is
2962 * used by VpnSettings and not available in ConnectivityManager.
2963 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002964 * @hide
2965 */
2966 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002967 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2968 mVpn.startLegacyVpn(config, racoon, mtpd);
2969 }
2970
2971 /**
2972 * Return the information of the ongoing legacy VPN. This method is used
2973 * by VpnSettings and not available in ConnectivityManager. Permissions
2974 * are checked in Vpn class.
2975 * @hide
2976 */
2977 @Override
2978 public LegacyVpnInfo getLegacyVpnInfo() {
2979 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002980 }
2981
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002982 /**
2983 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2984 * through NetworkStateTracker since it works differently. For example, it
2985 * needs to override DNS servers but never takes the default routes. It
2986 * relies on another data network, and it could keep existing connections
2987 * alive after reconnecting, switching between networks, or even resuming
2988 * from deep sleep. Calls from applications should be done synchronously
2989 * to avoid race conditions. As these are all hidden APIs, refactoring can
2990 * be done whenever a better abstraction is developed.
2991 */
2992 public class VpnCallback {
2993
2994 private VpnCallback() {
2995 }
2996
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002997 public void override(List<String> dnsServers, List<String> searchDomains) {
2998 if (dnsServers == null) {
2999 restore();
3000 return;
3001 }
3002
3003 // Convert DNS servers into addresses.
3004 List<InetAddress> addresses = new ArrayList<InetAddress>();
3005 for (String address : dnsServers) {
3006 // Double check the addresses and remove invalid ones.
3007 try {
3008 addresses.add(InetAddress.parseNumericAddress(address));
3009 } catch (Exception e) {
3010 // ignore
3011 }
3012 }
3013 if (addresses.isEmpty()) {
3014 restore();
3015 return;
3016 }
3017
3018 // Concatenate search domains into a string.
3019 StringBuilder buffer = new StringBuilder();
3020 if (searchDomains != null) {
3021 for (String domain : searchDomains) {
3022 buffer.append(domain).append(' ');
3023 }
3024 }
3025 String domains = buffer.toString().trim();
3026
3027 // Apply DNS changes.
3028 boolean changed = false;
3029 synchronized (mDnsLock) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07003030 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003031 mDnsOverridden = true;
3032 }
3033 if (changed) {
3034 bumpDns();
3035 }
3036
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003037 // Temporarily disable the default proxy.
3038 synchronized (mDefaultProxyLock) {
3039 mDefaultProxyDisabled = true;
3040 if (mDefaultProxy != null) {
3041 sendProxyBroadcast(null);
3042 }
3043 }
3044
3045 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003046 }
3047
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003048 public void restore() {
3049 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003050 if (mDnsOverridden) {
3051 mDnsOverridden = false;
3052 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003053 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003054 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003055 synchronized (mDefaultProxyLock) {
3056 mDefaultProxyDisabled = false;
3057 if (mDefaultProxy != null) {
3058 sendProxyBroadcast(mDefaultProxy);
3059 }
3060 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003061 }
3062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063}