blob: 206be68b3d044bcf70e0f339d984821443e218f7 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080034import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080035import android.content.ContentResolver;
36import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090037import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090040import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070041import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080043import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080044import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080045import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070046import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070047import android.net.INetworkPolicyListener;
48import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070049import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070050import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080051import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070052import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080053import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070054import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080055import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070056import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070057import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070058import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070060import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070061import android.net.Proxy;
62import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070063import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080064import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090065import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project28527d22009-03-03 19:31:44 -080066import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040067import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070069import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070070import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070071import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.os.Looper;
73import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070074import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070075import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070076import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070078import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.SystemProperties;
80import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070081import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080083import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070084import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070086import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070087import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070088import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -070089import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -070090import com.android.server.am.BatteryStatsService;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080091import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070092import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -070093import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey21062e72011-05-28 20:56:34 -070094import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070095import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070096
tk.mun093f55c2011-10-13 22:51:57 +090097import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070098
The Android Open Source Project28527d22009-03-03 19:31:44 -080099import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700100import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900102import java.lang.reflect.Constructor;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700103import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700104import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700105import java.net.InetAddress;
106import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700107import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700108import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700109import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700110import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700111import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700112import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800113
114/**
115 * @hide
116 */
117public class ConnectivityService extends IConnectivityManager.Stub {
118
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700119 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700120 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 private static final String TAG = "ConnectivityService";
122
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700123 private static final boolean LOGD_RULES = false;
124
Robert Greenwalt2034b912009-08-12 16:08:25 -0700125 // how long to wait before switching back to a radio's default network
126 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
127 // system property that can override the above value
128 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
129 "android.telephony.apn-restore";
130
Robert Greenwaltbd492212011-05-06 17:10:53 -0700131 // used in recursive route setting to add gateways for the host for which
132 // a host route was requested.
133 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
134
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800135 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800136 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800137
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700138 private Vpn mVpn;
139
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700140 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
141 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700142 /** Currently active network rules by UID. */
143 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700144 /** Set of ifaces that are costly. */
145 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700146
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147 /**
148 * Sometimes we want to refer to the individual network state
149 * trackers separately, and sometimes we just want to treat them
150 * abstractly.
151 */
152 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153
154 /**
Wink Saville051a6642011-07-13 13:44:13 -0700155 * The link properties that define the current links
156 */
157 private LinkProperties mCurrentLinkProperties[];
158
159 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700160 * A per Net list of the PID's that requested access to the net
161 * used both as a refcount and for per-PID DNS selection
162 */
163 private List mNetRequestersPids[];
164
Robert Greenwalt2034b912009-08-12 16:08:25 -0700165 // priority order of the nettrackers
166 // (excluding dynamically set mNetworkPreference)
167 // TODO - move mNetworkTypePreference into this
168 private int[] mPriorityList;
169
The Android Open Source Project28527d22009-03-03 19:31:44 -0800170 private Context mContext;
171 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700172 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700173 // 0 is full bad, 100 is full good
174 private int mDefaultInetCondition = 0;
175 private int mDefaultInetConditionPublished = 0;
176 private boolean mInetConditionChangeInFlight = false;
177 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800178
Chia-chi Yehcc844502011-07-14 18:01:57 -0700179 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800180 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700181 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800182
183 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700184 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800185
Robert Greenwalt355205c2011-05-10 15:05:02 -0700186 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700187 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700188
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700189 private static final int ENABLED = 1;
190 private static final int DISABLED = 0;
191
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700192 private static final boolean ADD = true;
193 private static final boolean REMOVE = false;
194
195 private static final boolean TO_DEFAULT_TABLE = true;
196 private static final boolean TO_SECONDARY_TABLE = false;
197
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700198 /**
199 * used internally as a delayed event to make us switch back to the
200 * default network
201 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700202 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700203
204 /**
205 * used internally to change our mobile data enabled flag
206 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700207 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700208
209 /**
210 * used internally to change our network preference setting
211 * arg1 = networkType to prefer
212 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700213 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700214
215 /**
216 * used internally to synchronize inet condition reports
217 * arg1 = networkType
218 * arg2 = condition (0 bad, 100 good)
219 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700220 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700221
222 /**
223 * used internally to mark the end of inet condition hold periods
224 * arg1 = networkType
225 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700226 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700227
228 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700229 * used internally to set enable/disable cellular data
230 * arg1 = ENBALED or DISABLED
231 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700232 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700233
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700234 /**
235 * used internally to clear a wakelock when transitioning
236 * from one net to another
237 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700238 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700239
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700240 /**
241 * used internally to reload global proxy settings
242 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700243 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700244
Robert Greenwalt34848c02011-03-25 13:09:25 -0700245 /**
246 * used internally to set external dependency met/unmet
247 * arg1 = ENABLED (met) or DISABLED (unmet)
248 * arg2 = NetworkType
249 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700250 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700251
Chia-chi Yehcc844502011-07-14 18:01:57 -0700252 /**
253 * used internally to restore DNS properties back to the
254 * default network
255 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700256 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700257
Wink Saville7e4333c2011-08-05 11:40:22 -0700258 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700259 * used internally to send a sticky broadcast delayed.
260 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700261 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700262
Jeff Sharkey805662d2011-08-19 02:24:24 -0700263 /**
264 * Used internally to
265 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
266 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700267 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700268
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700269 /** Handler used for internal events. */
270 private InternalHandler mHandler;
271 /** Handler used for incoming {@link NetworkStateTracker} events. */
272 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700273
274 // list of DeathRecipients used to make sure features are turned off when
275 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500276 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700277
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400278 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800279 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400280
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700281 private PowerManager.WakeLock mNetTransitionWakeLock;
282 private String mNetTransitionWakeLockCausedBy = "";
283 private int mNetTransitionWakeLockSerialNumber;
284 private int mNetTransitionWakeLockTimeout;
285
Robert Greenwalt94daa182010-09-01 11:34:05 -0700286 private InetAddress mDefaultDns;
287
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700288 // this collection is used to refcount the added routes - if there are none left
289 // it's time to remove the route from the route table
290 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
291
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700292 // used in DBG mode to track inet condition reports
293 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
294 private ArrayList mInetLog;
295
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700296 // track the current default http proxy - tell the world if we get a new one (real change)
297 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700298 private Object mDefaultProxyLock = new Object();
299 private boolean mDefaultProxyDisabled = false;
300
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700301 // track the global proxy.
302 private ProxyProperties mGlobalProxy = null;
303 private final Object mGlobalProxyLock = new Object();
304
305 private SettingsObserver mSettingsObserver;
306
Robert Greenwalt34848c02011-03-25 13:09:25 -0700307 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700308 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700309
Robert Greenwalt12c44552009-12-07 11:33:18 -0800310 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700311 public int mSimultaneity;
312 public int mType;
313 public RadioAttributes(String init) {
314 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700315 mType = Integer.parseInt(fragments[0]);
316 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700317 }
318 }
319 RadioAttributes[] mRadioAttributes;
320
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700321 // the set of network types that can only be enabled by system/sig apps
322 List mProtectedNetworks;
323
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700324 public ConnectivityService(Context context, INetworkManagementService netd,
325 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700326 // Currently, omitting a NetworkFactory will create one internally
327 // TODO: create here when we have cleaner WiMAX support
328 this(context, netd, statsService, policyManager, null);
329 }
330
331 public ConnectivityService(Context context, INetworkManagementService netd,
332 INetworkStatsService statsService, INetworkPolicyManager policyManager,
333 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800334 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800335
Wink Saville775aad62010-09-02 19:23:52 -0700336 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
337 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700338 mHandler = new InternalHandler(handlerThread.getLooper());
339 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700340
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700341 if (netFactory == null) {
342 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
343 }
344
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800345 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800346 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
347 String id = Settings.Secure.getString(context.getContentResolver(),
348 Settings.Secure.ANDROID_ID);
349 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700350 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800351 SystemProperties.set("net.hostname", name);
352 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800353 }
354
Robert Greenwalt94daa182010-09-01 11:34:05 -0700355 // read our default dns server ip
356 String dns = Settings.Secure.getString(context.getContentResolver(),
357 Settings.Secure.DEFAULT_DNS_SERVER);
358 if (dns == null || dns.length() == 0) {
359 dns = context.getResources().getString(
360 com.android.internal.R.string.config_default_dns_server);
361 }
362 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800363 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
364 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800365 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700366 }
367
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700368 mContext = checkNotNull(context, "missing Context");
369 mNetd = checkNotNull(netd, "missing INetworkManagementService");
370 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700371
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700372 try {
373 mPolicyManager.registerListener(mPolicyListener);
374 } catch (RemoteException e) {
375 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700376 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700377 }
378
379 final PowerManager powerManager = (PowerManager) context.getSystemService(
380 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700381 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
382 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
383 com.android.internal.R.integer.config_networkTransitionTimeout);
384
Robert Greenwalt2034b912009-08-12 16:08:25 -0700385 mNetTrackers = new NetworkStateTracker[
386 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700387 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700388
The Android Open Source Project28527d22009-03-03 19:31:44 -0800389 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700390
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700392 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700393
Robert Greenwalt2034b912009-08-12 16:08:25 -0700394 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700395 String[] raStrings = context.getResources().getStringArray(
396 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700397 for (String raString : raStrings) {
398 RadioAttributes r = new RadioAttributes(raString);
399 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800400 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700401 continue;
402 }
403 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800404 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700405 r.mType);
406 continue;
407 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408 mRadioAttributes[r.mType] = r;
409 }
410
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700411 String[] naStrings = context.getResources().getStringArray(
412 com.android.internal.R.array.networkAttributes);
413 for (String naString : naStrings) {
414 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700415 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700416 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800417 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700418 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700419 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700420 }
Wink Savillef2a62832011-04-07 14:23:45 -0700421 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800422 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700423 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700424 continue;
425 }
Wink Savillef2a62832011-04-07 14:23:45 -0700426 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800427 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700428 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700429 continue;
430 }
Wink Savillef2a62832011-04-07 14:23:45 -0700431 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700432 mNetworksDefined++;
433 } catch(Exception e) {
434 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700435 }
436 }
437
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700438 mProtectedNetworks = new ArrayList<Integer>();
439 int[] protectedNetworks = context.getResources().getIntArray(
440 com.android.internal.R.array.config_protectedNetworks);
441 for (int p : protectedNetworks) {
442 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
443 mProtectedNetworks.add(p);
444 } else {
445 if (DBG) loge("Ignoring protectedNetwork " + p);
446 }
447 }
448
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700449 // high priority first
450 mPriorityList = new int[mNetworksDefined];
451 {
452 int insertionPoint = mNetworksDefined-1;
453 int currentLowest = 0;
454 int nextLowest = 0;
455 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700456 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700457 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700458 if (na.priority < currentLowest) continue;
459 if (na.priority > currentLowest) {
460 if (na.priority < nextLowest || nextLowest == 0) {
461 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 }
463 continue;
464 }
Wink Savillef2a62832011-04-07 14:23:45 -0700465 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700466 }
467 currentLowest = nextLowest;
468 nextLowest = 0;
469 }
470 }
471
472 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
473 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700474 mNetRequestersPids[i] = new ArrayList();
475 }
476
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500477 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700478
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700479 mNumDnsEntries = 0;
480
481 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
482 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700483
484 // Create and start trackers for hard-coded networks
485 for (int targetNetworkType : mPriorityList) {
486 final NetworkConfig config = mNetConfigs[targetNetworkType];
487 final NetworkStateTracker tracker;
488 try {
489 tracker = netFactory.createTracker(targetNetworkType, config);
490 mNetTrackers[targetNetworkType] = tracker;
491 } catch (IllegalArgumentException e) {
492 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
493 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700494 continue;
495 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700496
497 tracker.startMonitoring(context, mTrackerHandler);
498 if (config.isDefault()) {
499 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800500 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700501 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800502
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700503 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700504 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700505 mTethering.getTetherableWifiRegexs().length != 0 ||
506 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700507 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800508
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700509 mVpn = new Vpn(mContext, new VpnCallback());
510
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700511 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700512 mNetd.registerObserver(mTethering);
513 mNetd.registerObserver(mVpn);
514 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700515 } catch (RemoteException e) {
516 loge("Error registering observer :" + e);
517 }
518
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700519 if (DBG) {
520 mInetLog = new ArrayList();
521 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700522
523 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
524 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800525
526 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800527 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700528
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700529 /**
530 * Factory that creates {@link NetworkStateTracker} instances using given
531 * {@link NetworkConfig}.
532 */
533 public interface NetworkFactory {
534 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
535 }
536
537 private static class DefaultNetworkFactory implements NetworkFactory {
538 private final Context mContext;
539 private final Handler mTrackerHandler;
540
541 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
542 mContext = context;
543 mTrackerHandler = trackerHandler;
544 }
545
546 @Override
547 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
548 switch (config.radio) {
549 case TYPE_WIFI:
550 return new WifiStateTracker(targetNetworkType, config.name);
551 case TYPE_MOBILE:
552 return new MobileDataStateTracker(targetNetworkType, config.name);
553 case TYPE_DUMMY:
554 return new DummyDataStateTracker(targetNetworkType, config.name);
555 case TYPE_BLUETOOTH:
556 return BluetoothTetheringDataTracker.getInstance();
557 case TYPE_WIMAX:
558 return makeWimaxStateTracker(mContext, mTrackerHandler);
559 case TYPE_ETHERNET:
560 return EthernetDataTracker.getInstance();
561 default:
562 throw new IllegalArgumentException(
563 "Trying to create a NetworkStateTracker for an unknown radio type: "
564 + config.radio);
565 }
566 }
567 }
568
569 /**
570 * Loads external WiMAX library and registers as system service, returning a
571 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
572 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
573 */
574 private static NetworkStateTracker makeWimaxStateTracker(
575 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700576 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900577 DexClassLoader wimaxClassLoader;
578 Class wimaxStateTrackerClass = null;
579 Class wimaxServiceClass = null;
580 Class wimaxManagerClass;
581 String wimaxJarLocation;
582 String wimaxLibLocation;
583 String wimaxManagerClassName;
584 String wimaxServiceClassName;
585 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800586
tk.mun093f55c2011-10-13 22:51:57 +0900587 NetworkStateTracker wimaxStateTracker = null;
588
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700589 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900590 com.android.internal.R.bool.config_wimaxEnabled);
591
592 if (isWimaxEnabled) {
593 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700594 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900595 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700596 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900597 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700598 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900599 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700600 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900601 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700602 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900603 com.android.internal.R.string.config_wimaxStateTrackerClassname);
604
605 log("wimaxJarLocation: " + wimaxJarLocation);
606 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700607 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900608 wimaxLibLocation, ClassLoader.getSystemClassLoader());
609
610 try {
611 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
612 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
613 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
614 } catch (ClassNotFoundException ex) {
615 loge("Exception finding Wimax classes: " + ex.toString());
616 return null;
617 }
618 } catch(Resources.NotFoundException ex) {
619 loge("Wimax Resources does not exist!!! ");
620 return null;
621 }
622
623 try {
624 log("Starting Wimax Service... ");
625
626 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
627 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700628 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
629 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900630
631 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
632 (new Class[] {Context.class, wimaxStateTrackerClass});
633 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700634 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900635 wmxSrvConst.setAccessible(false);
636
637 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
638
639 } catch(Exception ex) {
640 loge("Exception creating Wimax classes: " + ex.toString());
641 return null;
642 }
643 } else {
644 loge("Wimax is not enabled or not added to the network attributes!!! ");
645 return null;
646 }
647
648 return wimaxStateTracker;
649 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700650
The Android Open Source Project28527d22009-03-03 19:31:44 -0800651 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700652 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800653 * @param preference the new preference
654 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700655 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800656 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700657
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700658 mHandler.sendMessage(
659 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800660 }
661
662 public int getNetworkPreference() {
663 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700664 int preference;
665 synchronized(this) {
666 preference = mNetworkPreference;
667 }
668 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800669 }
670
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700671 private void handleSetNetworkPreference(int preference) {
672 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700673 mNetConfigs[preference] != null &&
674 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700675 if (mNetworkPreference != preference) {
676 final ContentResolver cr = mContext.getContentResolver();
677 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
678 synchronized(this) {
679 mNetworkPreference = preference;
680 }
681 enforcePreference();
682 }
683 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800684 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700685
Wink Saville4f0de1e2011-08-04 15:01:58 -0700686 private int getConnectivityChangeDelay() {
687 final ContentResolver cr = mContext.getContentResolver();
688
689 /** Check system properties for the default value then use secure settings value, if any. */
690 int defaultDelay = SystemProperties.getInt(
691 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
692 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
693 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
694 defaultDelay);
695 }
696
The Android Open Source Project28527d22009-03-03 19:31:44 -0800697 private int getPersistedNetworkPreference() {
698 final ContentResolver cr = mContext.getContentResolver();
699
700 final int networkPrefSetting = Settings.Secure
701 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
702 if (networkPrefSetting != -1) {
703 return networkPrefSetting;
704 }
705
706 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
707 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700708
The Android Open Source Project28527d22009-03-03 19:31:44 -0800709 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700710 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800711 * In this method, we only tear down a non-preferred network. Establishing
712 * a connection to the preferred network is taken care of when we handle
713 * the disconnect event from the non-preferred network
714 * (see {@link #handleDisconnect(NetworkInfo)}).
715 */
716 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700717 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800718 return;
719
Robert Greenwalt2034b912009-08-12 16:08:25 -0700720 if (!mNetTrackers[mNetworkPreference].isAvailable())
721 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800722
Robert Greenwalt2034b912009-08-12 16:08:25 -0700723 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700724 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700725 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700726 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800727 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700728 " in enforcePreference");
729 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700730 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800731 }
732 }
733 }
734
735 private boolean teardown(NetworkStateTracker netTracker) {
736 if (netTracker.teardown()) {
737 netTracker.setTeardownRequested(true);
738 return true;
739 } else {
740 return false;
741 }
742 }
743
744 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700745 * Check if UID should be blocked from using the network represented by the
746 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700747 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700748 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
749 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700750
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700751 final boolean networkCostly;
752 final int uidRules;
753 synchronized (mRulesLock) {
754 networkCostly = mMeteredIfaces.contains(iface);
755 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700756 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700757
758 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
759 return true;
760 }
761
762 // no restrictive rules; network is visible
763 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700764 }
765
766 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700767 * Return a filtered {@link NetworkInfo}, potentially marked
768 * {@link DetailedState#BLOCKED} based on
769 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700770 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700771 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
772 NetworkInfo info = tracker.getNetworkInfo();
773 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700774 // network is blocked; clone and override state
775 info = new NetworkInfo(info);
776 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700777 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700778 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700779 }
780
781 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782 * Return NetworkInfo for the active (i.e., connected) network interface.
783 * It is assumed that at most one network is active at a time. If more
784 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700785 * @return the info for the active network, or {@code null} if none is
786 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800787 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700788 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700790 enforceAccessPermission();
791 final int uid = Binder.getCallingUid();
792 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800793 }
794
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700795 @Override
796 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
797 enforceConnectivityInternalPermission();
798 return getNetworkInfo(mActiveDefaultNetwork, uid);
799 }
800
801 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800802 public NetworkInfo getNetworkInfo(int networkType) {
803 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700804 final int uid = Binder.getCallingUid();
805 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800806 }
807
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700808 private NetworkInfo getNetworkInfo(int networkType, int uid) {
809 NetworkInfo info = null;
810 if (isNetworkTypeValid(networkType)) {
811 final NetworkStateTracker tracker = mNetTrackers[networkType];
812 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700813 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700814 }
815 }
816 return info;
817 }
818
819 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800820 public NetworkInfo[] getAllNetworkInfo() {
821 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700822 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700823 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700824 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700825 for (NetworkStateTracker tracker : mNetTrackers) {
826 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700827 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700828 }
829 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800830 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700831 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800832 }
833
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700834 @Override
835 public boolean isNetworkSupported(int networkType) {
836 enforceAccessPermission();
837 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
838 }
839
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700840 /**
841 * Return LinkProperties for the active (i.e., connected) default
842 * network interface. It is assumed that at most one default network
843 * is active at a time. If more than one is active, it is indeterminate
844 * which will be returned.
845 * @return the ip properties for the active network, or {@code null} if
846 * none is active
847 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700848 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700849 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700850 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700851 }
852
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700853 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700854 public LinkProperties getLinkProperties(int networkType) {
855 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700856 if (isNetworkTypeValid(networkType)) {
857 final NetworkStateTracker tracker = mNetTrackers[networkType];
858 if (tracker != null) {
859 return tracker.getLinkProperties();
860 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700861 }
862 return null;
863 }
864
Jeff Sharkey21062e72011-05-28 20:56:34 -0700865 @Override
866 public NetworkState[] getAllNetworkState() {
867 enforceAccessPermission();
868 final int uid = Binder.getCallingUid();
869 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700870 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700871 for (NetworkStateTracker tracker : mNetTrackers) {
872 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700873 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700874 result.add(new NetworkState(
875 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
876 }
877 }
878 }
879 return result.toArray(new NetworkState[result.size()]);
880 }
881
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700882 private NetworkState getNetworkStateUnchecked(int networkType) {
883 if (isNetworkTypeValid(networkType)) {
884 final NetworkStateTracker tracker = mNetTrackers[networkType];
885 if (tracker != null) {
886 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
887 tracker.getLinkCapabilities());
888 }
889 }
890 return null;
891 }
892
893 @Override
894 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
895 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700896
897 final long token = Binder.clearCallingIdentity();
898 try {
899 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
900 if (state != null) {
901 try {
902 return mPolicyManager.getNetworkQuotaInfo(state);
903 } catch (RemoteException e) {
904 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700905 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700906 return null;
907 } finally {
908 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700909 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700910 }
911
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700912 @Override
913 public boolean isActiveNetworkMetered() {
914 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700915 final long token = Binder.clearCallingIdentity();
916 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700917 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700918 } finally {
919 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700920 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700921 }
922
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700923 private boolean isNetworkMeteredUnchecked(int networkType) {
924 final NetworkState state = getNetworkStateUnchecked(networkType);
925 if (state != null) {
926 try {
927 return mPolicyManager.isNetworkMetered(state);
928 } catch (RemoteException e) {
929 }
930 }
931 return false;
932 }
933
The Android Open Source Project28527d22009-03-03 19:31:44 -0800934 public boolean setRadios(boolean turnOn) {
935 boolean result = true;
936 enforceChangePermission();
937 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700938 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800939 }
940 return result;
941 }
942
943 public boolean setRadio(int netType, boolean turnOn) {
944 enforceChangePermission();
945 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
946 return false;
947 }
948 NetworkStateTracker tracker = mNetTrackers[netType];
949 return tracker != null && tracker.setRadio(turnOn);
950 }
951
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700952 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
953 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -0700954 public void interfaceClassDataActivityChanged(String label, boolean active) {
955 int deviceType = Integer.parseInt(label);
956 sendDataActivityBroadcast(deviceType, active);
957 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700958 };
Haoyu Baib5da5752012-06-20 14:29:57 -0700959
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700960 /**
961 * Used to notice when the calling process dies so we can self-expire
962 *
963 * Also used to know if the process has cleaned up after itself when
964 * our auto-expire timer goes off. The timer has a link to an object.
965 *
966 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700967 private class FeatureUser implements IBinder.DeathRecipient {
968 int mNetworkType;
969 String mFeature;
970 IBinder mBinder;
971 int mPid;
972 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800973 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700974
975 FeatureUser(int type, String feature, IBinder binder) {
976 super();
977 mNetworkType = type;
978 mFeature = feature;
979 mBinder = binder;
980 mPid = getCallingPid();
981 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800982 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700983
Robert Greenwalt2034b912009-08-12 16:08:25 -0700984 try {
985 mBinder.linkToDeath(this, 0);
986 } catch (RemoteException e) {
987 binderDied();
988 }
989 }
990
991 void unlinkDeathRecipient() {
992 mBinder.unlinkToDeath(this, 0);
993 }
994
995 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800996 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800997 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
998 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700999 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001000 }
1001
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001002 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001003 if (VDBG) {
1004 log("ConnectivityService FeatureUser expire(" +
1005 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1006 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1007 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001008 stopUsingNetworkFeature(this, false);
1009 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001010
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001011 public boolean isSameUser(FeatureUser u) {
1012 if (u == null) return false;
1013
1014 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1015 }
1016
1017 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1018 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1019 TextUtils.equals(mFeature, feature)) {
1020 return true;
1021 }
1022 return false;
1023 }
1024
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001025 public String toString() {
1026 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1027 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1028 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001029 }
1030
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001031 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001032 public int startUsingNetworkFeature(int networkType, String feature,
1033 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001034 long startTime = 0;
1035 if (DBG) {
1036 startTime = SystemClock.elapsedRealtime();
1037 }
Wink Savillea7d56572011-09-21 11:05:43 -07001038 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001039 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1040 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001041 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001042 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001043 try {
1044 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1045 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001046 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001047 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001048
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001049 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001050
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001051 // TODO - move this into individual networktrackers
1052 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001053
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001054 if (mProtectedNetworks.contains(usedNetworkType)) {
1055 enforceConnectivityInternalPermission();
1056 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001057
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001058 // if UID is restricted, don't allow them to bring up metered APNs
1059 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1060 final int uidRules;
1061 synchronized (mRulesLock) {
1062 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1063 }
1064 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001065 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001066 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001067
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001068 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1069 if (network != null) {
1070 Integer currentPid = new Integer(getCallingPid());
1071 if (usedNetworkType != networkType) {
1072 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001073
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001074 if (ni.isAvailable() == false) {
1075 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1076 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001077 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001078 } else {
1079 // else make the attempt anyway - probably giving REQUEST_STARTED below
1080 if (DBG) {
1081 log("special network not available, but try anyway ni=" +
1082 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001083 }
1084 }
1085 }
1086
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001087 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001088
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001089 synchronized(this) {
1090 boolean addToList = true;
1091 if (restoreTimer < 0) {
1092 // In case there is no timer is specified for the feature,
1093 // make sure we don't add duplicate entry with the same request.
1094 for (FeatureUser u : mFeatureUsers) {
1095 if (u.isSameUser(f)) {
1096 // Duplicate user is found. Do not add.
1097 addToList = false;
1098 break;
1099 }
1100 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001101 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001102
1103 if (addToList) mFeatureUsers.add(f);
1104 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1105 // this gets used for per-pid dns when connected
1106 mNetRequestersPids[usedNetworkType].add(currentPid);
1107 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001108 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001109
1110 if (restoreTimer >= 0) {
1111 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1112 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1113 }
1114
1115 if ((ni.isConnectedOrConnecting() == true) &&
1116 !network.isTeardownRequested()) {
1117 if (ni.isConnected() == true) {
1118 final long token = Binder.clearCallingIdentity();
1119 try {
1120 // add the pid-specific dns
1121 handleDnsConfigurationChange(usedNetworkType);
1122 if (VDBG) log("special network already active");
1123 } finally {
1124 Binder.restoreCallingIdentity(token);
1125 }
Wink Saville64e3f782012-07-10 12:37:54 -07001126 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001127 }
1128 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001129 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001130 }
1131
1132 // check if the radio in play can make another contact
1133 // assume if cannot for now
1134
1135 if (DBG) {
1136 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1137 feature);
1138 }
1139 network.reconnect();
Wink Saville64e3f782012-07-10 12:37:54 -07001140 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001141 } else {
1142 // need to remember this unsupported request so we respond appropriately on stop
1143 synchronized(this) {
1144 mFeatureUsers.add(f);
1145 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1146 // this gets used for per-pid dns when connected
1147 mNetRequestersPids[usedNetworkType].add(currentPid);
1148 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001149 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001150 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001151 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001152 }
Wink Saville64e3f782012-07-10 12:37:54 -07001153 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001154 } finally {
1155 if (DBG) {
1156 final long execTime = SystemClock.elapsedRealtime() - startTime;
1157 if (execTime > 250) {
1158 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1159 } else {
1160 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1161 }
1162 }
1163 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001164 }
1165
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001166 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001167 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001168 enforceChangePermission();
1169
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001170 int pid = getCallingPid();
1171 int uid = getCallingUid();
1172
1173 FeatureUser u = null;
1174 boolean found = false;
1175
1176 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001177 for (FeatureUser x : mFeatureUsers) {
1178 if (x.isSameUser(pid, uid, networkType, feature)) {
1179 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001180 found = true;
1181 break;
1182 }
1183 }
1184 }
1185 if (found && u != null) {
1186 // stop regardless of how many other time this proc had called start
1187 return stopUsingNetworkFeature(u, true);
1188 } else {
1189 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001190 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001191 return 1;
1192 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001193 }
1194
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001195 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1196 int networkType = u.mNetworkType;
1197 String feature = u.mFeature;
1198 int pid = u.mPid;
1199 int uid = u.mUid;
1200
1201 NetworkStateTracker tracker = null;
1202 boolean callTeardown = false; // used to carry our decision outside of sync block
1203
Wink Savillea7d56572011-09-21 11:05:43 -07001204 if (VDBG) {
1205 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001206 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001207
The Android Open Source Project28527d22009-03-03 19:31:44 -08001208 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001209 if (DBG) {
1210 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1211 ", net is invalid");
1212 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001213 return -1;
1214 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001215
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001216 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1217 // sync block
1218 synchronized(this) {
1219 // check if this process still has an outstanding start request
1220 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001221 if (VDBG) {
1222 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1223 ", ignoring");
1224 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001225 return 1;
1226 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001227 u.unlinkDeathRecipient();
1228 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1229 // If we care about duplicate requests, check for that here.
1230 //
1231 // This is done to support the extension of a request - the app
1232 // can request we start the network feature again and renew the
1233 // auto-shutoff delay. Normal "stop" calls from the app though
1234 // do not pay attention to duplicate requests - in effect the
1235 // API does not refcount and a single stop will counter multiple starts.
1236 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001237 for (FeatureUser x : mFeatureUsers) {
1238 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001239 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001240 return 1;
1241 }
1242 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001243 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001244
repo syncf5de5572011-07-29 23:55:49 -07001245 // TODO - move to individual network trackers
1246 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1247
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001248 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001249 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001250 if (DBG) {
1251 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1252 " no known tracker for used net type " + usedNetworkType);
1253 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001254 return -1;
1255 }
1256 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001257 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001258 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001259 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001260 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001261 if (VDBG) {
1262 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1263 " others still using it");
1264 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001265 return 1;
1266 }
1267 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001268 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001269 if (DBG) {
1270 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1271 " not a known feature - dropping");
1272 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001273 }
1274 }
Wink Savillea7d56572011-09-21 11:05:43 -07001275
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001276 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001277 if (DBG) {
1278 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1279 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001280 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001281 return 1;
1282 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001283 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001284 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001285 }
1286
1287 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001288 * @deprecated use requestRouteToHostAddress instead
1289 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001290 * Ensure that a network route exists to deliver traffic to the specified
1291 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001292 * @param networkType the type of the network over which traffic to the
1293 * specified host is to be routed
1294 * @param hostAddress the IP address of the host to which the route is
1295 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001296 * @return {@code true} on success, {@code false} on failure
1297 */
1298 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001299 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1300
1301 if (inetAddress == null) {
1302 return false;
1303 }
1304
1305 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1306 }
1307
1308 /**
1309 * Ensure that a network route exists to deliver traffic to the specified
1310 * host via the specified network interface.
1311 * @param networkType the type of the network over which traffic to the
1312 * specified host is to be routed
1313 * @param hostAddress the IP address of the host to which the route is
1314 * desired
1315 * @return {@code true} on success, {@code false} on failure
1316 */
1317 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001318 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001319 if (mProtectedNetworks.contains(networkType)) {
1320 enforceConnectivityInternalPermission();
1321 }
1322
The Android Open Source Project28527d22009-03-03 19:31:44 -08001323 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001324 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001325 return false;
1326 }
1327 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001328
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001329 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1330 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001331 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001332 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001333 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001334 }
1335 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001336 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001337 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001338 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001339 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001340 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001341 return addRouteToAddress(lp, addr);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001342 } catch (UnknownHostException e) {
1343 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1344 } finally {
1345 Binder.restoreCallingIdentity(token);
1346 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001347 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001348 }
1349
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001350 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1351 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001352 }
1353
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001354 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1355 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001356 }
1357
Robert Greenwalt98107422011-07-22 11:55:33 -07001358 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001359 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001360 }
1361
1362 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001363 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001364 }
1365
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001366 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1367 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001368 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1369 if (bestRoute == null) {
1370 bestRoute = RouteInfo.makeHostRoute(addr);
1371 } else {
1372 if (bestRoute.getGateway().equals(addr)) {
1373 // if there is no better route, add the implied hostroute for our gateway
1374 bestRoute = RouteInfo.makeHostRoute(addr);
1375 } else {
1376 // if we will connect to this through another route, add a direct route
1377 // to it's gateway
1378 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1379 }
1380 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001381 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001382 }
1383
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001384 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001385 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001386 if ((ifaceName == null) || (lp == null) || (r == null)) {
1387 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1388 return false;
1389 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001390
1391 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001392 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001393 return false;
1394 }
1395
1396 if (r.isHostRoute() == false) {
1397 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1398 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001399 if (bestRoute.getGateway().equals(r.getGateway())) {
1400 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001401 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001402 } else {
1403 // if we will connect to our gateway through another route, add a direct
1404 // route to it's gateway
1405 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001406 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001407 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001408 }
1409 }
1410 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001411 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001412 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001413 if (toDefaultTable) {
1414 mAddedRoutes.add(r); // only track default table - only one apps can effect
1415 mNetd.addRoute(ifaceName, r);
1416 } else {
1417 mNetd.addSecondaryRoute(ifaceName, r);
1418 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001419 } catch (Exception e) {
1420 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001421 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001422 return false;
1423 }
1424 } else {
1425 // if we remove this one and there are no more like it, then refcount==0 and
1426 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001427 if (toDefaultTable) {
1428 mAddedRoutes.remove(r);
1429 if (mAddedRoutes.contains(r) == false) {
1430 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1431 try {
1432 mNetd.removeRoute(ifaceName, r);
1433 } catch (Exception e) {
1434 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001435 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001436 return false;
1437 }
1438 } else {
1439 if (VDBG) log("not removing " + r + " as it's still in use");
1440 }
1441 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001442 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001443 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001444 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001445 } catch (Exception e) {
1446 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001447 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001448 return false;
1449 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001450 }
1451 }
1452 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001453 }
1454
1455 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001456 * @see ConnectivityManager#getMobileDataEnabled()
1457 */
1458 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001459 // TODO: This detail should probably be in DataConnectionTracker's
1460 // which is where we store the value and maybe make this
1461 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001462 enforceAccessPermission();
1463 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1464 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001465 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001466 return retVal;
1467 }
1468
Robert Greenwalt34848c02011-03-25 13:09:25 -07001469 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001470 enforceConnectivityInternalPermission();
1471
Robert Greenwalt34848c02011-03-25 13:09:25 -07001472 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1473 (met ? ENABLED : DISABLED), networkType));
1474 }
1475
1476 private void handleSetDependencyMet(int networkType, boolean met) {
1477 if (mNetTrackers[networkType] != null) {
1478 if (DBG) {
1479 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1480 }
1481 mNetTrackers[networkType].setDependencyMet(met);
1482 }
1483 }
1484
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001485 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1486 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001487 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001488 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001489 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001490 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001491 }
1492
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001493 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001494 // skip update when we've already applied rules
1495 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1496 if (oldRules == uidRules) return;
1497
1498 mUidRules.put(uid, uidRules);
1499 }
1500
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001501 // TODO: notify UID when it has requested targeted updates
1502 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001503
1504 @Override
1505 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001506 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001507 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001508 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001509 }
1510
1511 synchronized (mRulesLock) {
1512 mMeteredIfaces.clear();
1513 for (String iface : meteredIfaces) {
1514 mMeteredIfaces.add(iface);
1515 }
1516 }
1517 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001518
1519 @Override
1520 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1521 // caller is NPMS, since we only register with them
1522 if (LOGD_RULES) {
1523 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1524 }
1525
1526 // kick off connectivity change broadcast for active network, since
1527 // global background policy change is radical.
1528 final int networkType = mActiveDefaultNetwork;
1529 if (isNetworkTypeValid(networkType)) {
1530 final NetworkStateTracker tracker = mNetTrackers[networkType];
1531 if (tracker != null) {
1532 final NetworkInfo info = tracker.getNetworkInfo();
1533 if (info != null && info.isConnected()) {
1534 sendConnectedBroadcast(info);
1535 }
1536 }
1537 }
1538 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001539 };
1540
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001541 /**
1542 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1543 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001544 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001545 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001546 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001547
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001548 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001549 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001550 }
1551
1552 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001553 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001554 if (VDBG) {
1555 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001556 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001557 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1558 }
tk.mun5eee1042012-01-06 10:43:52 +09001559 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1560 if (VDBG) {
1561 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1562 }
1563 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1564 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001565 }
1566
1567 @Override
1568 public void setPolicyDataEnable(int networkType, boolean enabled) {
1569 // only someone like NPMS should only be calling us
1570 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1571
1572 mHandler.sendMessage(mHandler.obtainMessage(
1573 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1574 }
1575
1576 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1577 if (isNetworkTypeValid(networkType)) {
1578 final NetworkStateTracker tracker = mNetTrackers[networkType];
1579 if (tracker != null) {
1580 tracker.setPolicyDataEnable(enabled);
1581 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001582 }
1583 }
1584
The Android Open Source Project28527d22009-03-03 19:31:44 -08001585 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.ACCESS_NETWORK_STATE,
1588 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001589 }
1590
1591 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.CHANGE_NETWORK_STATE,
1594 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001595 }
1596
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001597 // TODO Make this a special check when it goes public
1598 private void enforceTetherChangePermission() {
1599 mContext.enforceCallingOrSelfPermission(
1600 android.Manifest.permission.CHANGE_NETWORK_STATE,
1601 "ConnectivityService");
1602 }
1603
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001604 private void enforceTetherAccessPermission() {
1605 mContext.enforceCallingOrSelfPermission(
1606 android.Manifest.permission.ACCESS_NETWORK_STATE,
1607 "ConnectivityService");
1608 }
1609
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001610 private void enforceConnectivityInternalPermission() {
1611 mContext.enforceCallingOrSelfPermission(
1612 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1613 "ConnectivityService");
1614 }
1615
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001617 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1618 * network, we ignore it. If it is for the active network, we send out a
1619 * broadcast. But first, we check whether it might be possible to connect
1620 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001621 * @param info the {@code NetworkInfo} for the network
1622 */
1623 private void handleDisconnect(NetworkInfo info) {
1624
Robert Greenwalt2034b912009-08-12 16:08:25 -07001625 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001626
Robert Greenwalt2034b912009-08-12 16:08:25 -07001627 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001628 /*
1629 * If the disconnected network is not the active one, then don't report
1630 * this as a loss of connectivity. What probably happened is that we're
1631 * getting the disconnect for a network that we explicitly disabled
1632 * in accordance with network preference policies.
1633 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001634 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001635 List pids = mNetRequestersPids[prevNetType];
1636 for (int i = 0; i<pids.size(); i++) {
1637 Integer pid = (Integer)pids.get(i);
1638 // will remove them because the net's no longer connected
1639 // need to do this now as only now do we know the pids and
1640 // can properly null things that are no longer referenced.
1641 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001642 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001643 }
1644
The Android Open Source Project28527d22009-03-03 19:31:44 -08001645 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1646 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1647 if (info.isFailover()) {
1648 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1649 info.setFailover(false);
1650 }
1651 if (info.getReason() != null) {
1652 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1653 }
1654 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001655 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1656 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001657 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001658
Robert Greenwalt34848c02011-03-25 13:09:25 -07001659 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001660 tryFailover(prevNetType);
1661 if (mActiveDefaultNetwork != -1) {
1662 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001663 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1664 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001665 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001666 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1667 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001668 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001669 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001670
1671 // Reset interface if no other connections are using the same interface
1672 boolean doReset = true;
1673 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1674 if (linkProperties != null) {
1675 String oldIface = linkProperties.getInterfaceName();
1676 if (TextUtils.isEmpty(oldIface) == false) {
1677 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1678 if (networkStateTracker == null) continue;
1679 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1680 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1681 LinkProperties l = networkStateTracker.getLinkProperties();
1682 if (l == null) continue;
1683 if (oldIface.equals(l.getInterfaceName())) {
1684 doReset = false;
1685 break;
1686 }
1687 }
1688 }
1689 }
1690 }
1691
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001692 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001693 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001694
Jeff Sharkey971cd162011-08-29 16:02:57 -07001695 final Intent immediateIntent = new Intent(intent);
1696 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1697 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001698 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001699 /*
1700 * If the failover network is already connected, then immediately send
1701 * out a followup broadcast indicating successful failover
1702 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001703 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001704 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1705 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001706 }
1707 }
1708
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001709 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001710 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001711 * If this is a default network, check if other defaults are available.
1712 * Try to reconnect on all available and let them hash it out when
1713 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001714 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001715 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001716 if (mActiveDefaultNetwork == prevNetType) {
1717 mActiveDefaultNetwork = -1;
1718 }
1719
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001720 // don't signal a reconnect for anything lower or equal priority than our
1721 // current connected default
1722 // TODO - don't filter by priority now - nice optimization but risky
1723// int currentPriority = -1;
1724// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001725// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001726// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001727 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001728 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001729 if (mNetConfigs[checkType] == null) continue;
1730 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001731 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001732
1733// Enabling the isAvailable() optimization caused mobile to not get
1734// selected if it was in the middle of error handling. Specifically
1735// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1736// would not be available and we wouldn't get connected to anything.
1737// So removing the isAvailable() optimization below for now. TODO: This
1738// optimization should work and we need to investigate why it doesn't work.
1739// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1740// complete before it is really complete.
1741// if (!mNetTrackers[checkType].isAvailable()) continue;
1742
Robert Greenwalt34848c02011-03-25 13:09:25 -07001743// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001744
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001745 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1746 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1747 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1748 checkInfo.setFailover(true);
1749 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001750 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001751 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001752 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001753 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001754 }
1755
1756 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001757 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1758 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001759 }
1760
Wink Saville4f0de1e2011-08-04 15:01:58 -07001761 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001762 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1763 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001764 }
1765
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001766 private void sendInetConditionBroadcast(NetworkInfo info) {
1767 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1768 }
1769
Wink Saville4f0de1e2011-08-04 15:01:58 -07001770 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001771 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001772 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1773 if (info.isFailover()) {
1774 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1775 info.setFailover(false);
1776 }
1777 if (info.getReason() != null) {
1778 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1779 }
1780 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001781 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1782 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001783 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001784 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001785 return intent;
1786 }
1787
1788 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1789 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1790 }
1791
1792 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1793 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001794 }
1795
Haoyu Baib5da5752012-06-20 14:29:57 -07001796 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1797 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1798 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1799 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1800 mContext.sendOrderedBroadcast(intent, RECEIVE_DATA_ACTIVITY_CHANGE);
1801 }
1802
The Android Open Source Project28527d22009-03-03 19:31:44 -08001803 /**
1804 * Called when an attempt to fail over to another network has failed.
1805 * @param info the {@link NetworkInfo} for the failed network
1806 */
1807 private void handleConnectionFailure(NetworkInfo info) {
1808 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001809
Robert Greenwalt2034b912009-08-12 16:08:25 -07001810 String reason = info.getReason();
1811 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001812
Robert Greenwalte981bc52010-10-08 16:35:52 -07001813 String reasonText;
1814 if (reason == null) {
1815 reasonText = ".";
1816 } else {
1817 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001818 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001819 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001820
1821 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1822 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1823 if (getActiveNetworkInfo() == null) {
1824 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1825 }
1826 if (reason != null) {
1827 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1828 }
1829 if (extraInfo != null) {
1830 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1831 }
1832 if (info.isFailover()) {
1833 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1834 info.setFailover(false);
1835 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001836
Robert Greenwalt34848c02011-03-25 13:09:25 -07001837 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001838 tryFailover(info.getType());
1839 if (mActiveDefaultNetwork != -1) {
1840 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001841 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1842 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001843 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001844 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1845 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001846 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001847
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001848 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001849
1850 final Intent immediateIntent = new Intent(intent);
1851 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1852 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001853 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001854 /*
1855 * If the failover network is already connected, then immediately send
1856 * out a followup broadcast indicating successful failover
1857 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001858 if (mActiveDefaultNetwork != -1) {
1859 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001860 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001861 }
1862
1863 private void sendStickyBroadcast(Intent intent) {
1864 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001865 if (!mSystemReady) {
1866 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001867 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001868 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001869 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001870 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001871 }
1872
Dianne Hackborna417ff82009-12-08 19:45:14 -08001873 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001874 }
1875 }
1876
Wink Saville4f0de1e2011-08-04 15:01:58 -07001877 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1878 if (delayMs <= 0) {
1879 sendStickyBroadcast(intent);
1880 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001881 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001882 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1883 + intent.getAction());
1884 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001885 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1886 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1887 }
1888 }
1889
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001890 void systemReady() {
1891 synchronized(this) {
1892 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001893 if (mInitialBroadcast != null) {
1894 mContext.sendStickyBroadcast(mInitialBroadcast);
1895 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001896 }
1897 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001898 // load the global proxy at startup
1899 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001900 }
1901
1902 private void handleConnect(NetworkInfo info) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001903 final int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001904
1905 // snapshot isFailover, because sendConnectedBroadcast() resets it
1906 boolean isFailover = info.isFailover();
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001907 final NetworkStateTracker thisNet = mNetTrackers[type];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07001908 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001909
Robert Greenwalt2034b912009-08-12 16:08:25 -07001910 // if this is a default net and other default is running
1911 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001912 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001913 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1914 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001915 mNetConfigs[mActiveDefaultNetwork].priority >
1916 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001917 mNetworkPreference == mActiveDefaultNetwork) {
1918 // don't accept this one
Robert Greenwalt78f28112011-08-02 17:18:41 -07001919 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001920 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001921 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001922 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001923 teardown(thisNet);
1924 return;
1925 } else {
1926 // tear down the other
1927 NetworkStateTracker otherNet =
1928 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001929 if (DBG) {
1930 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001931 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001932 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001933 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001934 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001935 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001936 return;
1937 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001938 }
1939 }
1940 synchronized (ConnectivityService.this) {
1941 // have a new default network, release the transition wakelock in a second
1942 // if it's held. The second pause is to allow apps to reconnect over the
1943 // new network
1944 if (mNetTransitionWakeLock.isHeld()) {
1945 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001946 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001947 mNetTransitionWakeLockSerialNumber, 0),
1948 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001949 }
1950 }
1951 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001952 // this will cause us to come up initially as unconnected and switching
1953 // to connected after our normal pause unless somebody reports us as reall
1954 // disconnected
1955 mDefaultInetConditionPublished = 0;
1956 mDefaultConnectionSequence++;
1957 mInetConditionChangeInFlight = false;
1958 // Don't do this - if we never sign in stay, grey
1959 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001960 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001961 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001962 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001963 handleConnectivityChange(type, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001964 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001965
1966 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07001967 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001968 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07001969 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, type);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07001970 } catch (RemoteException e) {
1971 // ignored; service lives in system_server
1972 }
1973 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001974 }
1975
The Android Open Source Project28527d22009-03-03 19:31:44 -08001976 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001977 * After a change in the connectivity state of a network. We're mainly
1978 * concerned with making sure that the list of DNS servers is set up
1979 * according to which networks are connected, and ensuring that the
1980 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001981 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001982 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001983 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1984
The Android Open Source Project28527d22009-03-03 19:31:44 -08001985 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001986 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001987 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001988 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001989 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001990
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001991 LinkProperties curLp = mCurrentLinkProperties[netType];
1992 LinkProperties newLp = null;
1993
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001994 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001995 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001996 if (VDBG) {
1997 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1998 " doReset=" + doReset + " resetMask=" + resetMask +
1999 "\n curLp=" + curLp +
2000 "\n newLp=" + newLp);
2001 }
2002
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002003 if (curLp != null) {
2004 if (curLp.isIdenticalInterfaceName(newLp)) {
2005 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2006 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2007 for (LinkAddress linkAddr : car.removed) {
2008 if (linkAddr.getAddress() instanceof Inet4Address) {
2009 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2010 }
2011 if (linkAddr.getAddress() instanceof Inet6Address) {
2012 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2013 }
Wink Saville051a6642011-07-13 13:44:13 -07002014 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002015 if (DBG) {
2016 log("handleConnectivityChange: addresses changed" +
2017 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2018 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002019 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002020 } else {
2021 if (DBG) {
2022 log("handleConnectivityChange: address are the same reset per doReset" +
2023 " linkProperty[" + netType + "]:" +
2024 " resetMask=" + resetMask);
2025 }
Wink Saville051a6642011-07-13 13:44:13 -07002026 }
2027 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002028 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002029 if (DBG) {
2030 log("handleConnectivityChange: interface not not equivalent reset both" +
2031 " linkProperty[" + netType + "]:" +
2032 " resetMask=" + resetMask);
2033 }
Wink Saville051a6642011-07-13 13:44:13 -07002034 }
Wink Saville051a6642011-07-13 13:44:13 -07002035 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002036 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002037 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002038 }
2039 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002040 if (VDBG) {
2041 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2042 " doReset=" + doReset + " resetMask=" + resetMask +
2043 "\n curLp=" + curLp +
2044 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002045 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002046 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002047 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002048 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002049
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002050 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002051 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2052 if (linkProperties != null) {
2053 String iface = linkProperties.getInterfaceName();
2054 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002055 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07002056 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2057 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002058
2059 // Tell VPN the interface is down. It is a temporary
2060 // but effective fix to make VPN aware of the change.
2061 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2062 mVpn.interfaceStatusChanged(iface, false);
2063 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002064 }
2065 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07002066 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002067 try {
2068 mNetd.flushInterfaceDnsCache(iface);
2069 } catch (Exception e) {
2070 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07002071 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002072 }
2073 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002074 }
2075 }
2076 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002077
2078 // TODO: Temporary notifying upstread change to Tethering.
2079 // @see bug/4455071
2080 /** Notify TetheringService if interface name has been changed. */
2081 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002082 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002083 if (isTetheringSupported()) {
2084 mTethering.handleTetherIfaceChange();
2085 }
2086 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002087 }
2088
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002089 /**
2090 * Add and remove routes using the old properties (null if not previously connected),
2091 * new properties (null if becoming disconnected). May even be double null, which
2092 * is a noop.
2093 * Uses isLinkDefault to determine if default routes should be set or conversely if
2094 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002095 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002096 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002097 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2098 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002099 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002100 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2101 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002102 if (curLp != null) {
2103 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002104 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002105 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002106 } else if (newLp != null) {
2107 routeDiff.added = newLp.getRoutes();
2108 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002109 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002110
Robert Greenwalt8d777252011-08-15 12:31:55 -07002111 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2112
Robert Greenwalt98107422011-07-22 11:55:33 -07002113 for (RouteInfo r : routeDiff.removed) {
2114 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002115 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2116 }
2117 if (isLinkDefault == false) {
2118 // remove from a secondary route table
2119 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002120 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002121 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002122
Robert Greenwalt98107422011-07-22 11:55:33 -07002123 for (RouteInfo r : routeDiff.added) {
2124 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002125 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002126 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002127 // add to a secondary route table
2128 addRoute(newLp, r, TO_SECONDARY_TABLE);
2129
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002130 // many radios add a default route even when we don't want one.
2131 // remove the default route unless somebody else has asked for it
2132 String ifaceName = newLp.getInterfaceName();
2133 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002134 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002135 try {
2136 mNetd.removeRoute(ifaceName, r);
2137 } catch (Exception e) {
2138 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002139 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002140 }
2141 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002142 }
2143 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002144
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002145 if (!isLinkDefault) {
2146 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002147 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002148 // routes changed - remove all old dns entries and add new
2149 if (curLp != null) {
2150 for (InetAddress oldDns : curLp.getDnses()) {
2151 removeRouteToAddress(curLp, oldDns);
2152 }
2153 }
2154 if (newLp != null) {
2155 for (InetAddress newDns : newLp.getDnses()) {
2156 addRouteToAddress(newLp, newDns);
2157 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002158 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002159 } else {
2160 // no change in routes, check for change in dns themselves
2161 for (InetAddress oldDns : dnsDiff.removed) {
2162 removeRouteToAddress(curLp, oldDns);
2163 }
2164 for (InetAddress newDns : dnsDiff.added) {
2165 addRouteToAddress(newLp, newDns);
2166 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002167 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002168 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002169 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002170 }
2171
2172
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002173 /**
2174 * Reads the network specific TCP buffer sizes from SystemProperties
2175 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2176 * wide use
2177 */
2178 public void updateNetworkSettings(NetworkStateTracker nt) {
2179 String key = nt.getTcpBufferSizesPropName();
2180 String bufferSizes = SystemProperties.get(key);
2181
2182 if (bufferSizes.length() == 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002183 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002184
2185 // Setting to default values so we won't be stuck to previous values
2186 key = "net.tcp.buffersize.default";
2187 bufferSizes = SystemProperties.get(key);
2188 }
2189
2190 // Set values in kernel
2191 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002192 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002193 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002194 + "] which comes from [" + key + "]");
2195 }
2196 setBufferSize(bufferSizes);
2197 }
2198 }
2199
2200 /**
2201 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2202 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2203 *
2204 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2205 * writeMin, writeInitial, writeMax"
2206 */
2207 private void setBufferSize(String bufferSizes) {
2208 try {
2209 String[] values = bufferSizes.split(",");
2210
2211 if (values.length == 6) {
2212 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002213 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2214 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2215 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2216 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2217 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2218 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002219 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002220 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002221 }
2222 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002223 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002224 }
2225 }
2226
Robert Greenwalt2034b912009-08-12 16:08:25 -07002227 /**
2228 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2229 * on the highest priority active net which this process requested.
2230 * If there aren't any, clear it out
2231 */
2232 private void reassessPidDns(int myPid, boolean doBump)
2233 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002234 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002235 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002236 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002237 continue;
2238 }
2239 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002240 if (nt.getNetworkInfo().isConnected() &&
2241 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002242 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002243 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002244 List pids = mNetRequestersPids[i];
2245 for (int j=0; j<pids.size(); j++) {
2246 Integer pid = (Integer)pids.get(j);
2247 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002248 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002249 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002250 if (doBump) {
2251 bumpDns();
2252 }
2253 return;
2254 }
2255 }
2256 }
2257 }
2258 // nothing found - delete
2259 for (int i = 1; ; i++) {
2260 String prop = "net.dns" + i + "." + myPid;
2261 if (SystemProperties.get(prop).length() == 0) {
2262 if (doBump) {
2263 bumpDns();
2264 }
2265 return;
2266 }
2267 SystemProperties.set(prop, "");
2268 }
2269 }
2270
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002271 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002272 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002273 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002274 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002275 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002276 String dnsString = dns.getHostAddress();
2277 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2278 changed = true;
yoonsung.nam48d18332012-03-02 19:56:16 +09002279 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002280 }
yoonsung.nam48d18332012-03-02 19:56:16 +09002281 j++;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002282 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002283 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002284 }
2285
2286 private void bumpDns() {
2287 /*
2288 * Bump the property that tells the name resolver library to reread
2289 * the DNS server list from the properties.
2290 */
2291 String propVal = SystemProperties.get("net.dnschange");
2292 int n = 0;
2293 if (propVal.length() != 0) {
2294 try {
2295 n = Integer.parseInt(propVal);
2296 } catch (NumberFormatException e) {}
2297 }
2298 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002299 /*
2300 * Tell the VMs to toss their DNS caches
2301 */
2302 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2303 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002304 /*
2305 * Connectivity events can happen before boot has completed ...
2306 */
2307 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07002308 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002309 }
2310
Chia-chi Yehcc844502011-07-14 18:01:57 -07002311 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002312 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002313 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002314 boolean changed = false;
2315 int last = 0;
2316 if (dnses.size() == 0 && mDefaultDns != null) {
2317 ++last;
2318 String value = mDefaultDns.getHostAddress();
2319 if (!value.equals(SystemProperties.get("net.dns1"))) {
2320 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002321 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002322 }
2323 changed = true;
2324 SystemProperties.set("net.dns1", value);
2325 }
2326 } else {
2327 for (InetAddress dns : dnses) {
2328 ++last;
2329 String key = "net.dns" + last;
2330 String value = dns.getHostAddress();
2331 if (!changed && value.equals(SystemProperties.get(key))) {
2332 continue;
2333 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002334 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002335 log("adding dns " + value + " for " + network);
2336 }
2337 changed = true;
2338 SystemProperties.set(key, value);
2339 }
2340 }
2341 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2342 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002343 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002344 changed = true;
2345 SystemProperties.set(key, "");
2346 }
2347 mNumDnsEntries = last;
2348
Robert Greenwaltfce71862011-07-25 16:06:25 -07002349 if (changed) {
2350 try {
2351 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2352 mNetd.setDefaultInterfaceForDns(iface);
2353 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002354 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002355 }
2356 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002357 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2358 SystemProperties.set("net.dns.search", domains);
2359 changed = true;
2360 }
2361 return changed;
2362 }
2363
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002364 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002365 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002366 NetworkStateTracker nt = mNetTrackers[netType];
2367 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002368 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002369 if (p == null) return;
2370 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002371 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002372 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002373 String network = nt.getNetworkInfo().getTypeName();
2374 synchronized (mDnsLock) {
2375 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002376 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002377 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002378 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002379 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002380 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002381 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002382 NetworkUtils.makeStrings(dnses));
2383 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002384 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002385 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002386 // set per-pid dns for attached secondary nets
2387 List pids = mNetRequestersPids[netType];
2388 for (int y=0; y< pids.size(); y++) {
2389 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002390 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002391 }
2392 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002393 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002394 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002395 }
2396
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002397 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002398 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2399 NETWORK_RESTORE_DELAY_PROP_NAME);
2400 if(restoreDefaultNetworkDelayStr != null &&
2401 restoreDefaultNetworkDelayStr.length() != 0) {
2402 try {
2403 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2404 } catch (NumberFormatException e) {
2405 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002406 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002407 // if the system property isn't set, use the value for the apn type
2408 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2409
2410 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2411 (mNetConfigs[networkType] != null)) {
2412 ret = mNetConfigs[networkType].restoreTime;
2413 }
2414 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002415 }
2416
2417 @Override
2418 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002419 if (mContext.checkCallingOrSelfPermission(
2420 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002421 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002422 pw.println("Permission Denial: can't dump ConnectivityService " +
2423 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2424 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002425 return;
2426 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002427 pw.println();
2428 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002429 if (nst != null) {
2430 if (nst.getNetworkInfo().isConnected()) {
2431 pw.println("Active network: " + nst.getNetworkInfo().
2432 getTypeName());
2433 }
2434 pw.println(nst.getNetworkInfo());
2435 pw.println(nst);
2436 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002437 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002438 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002439
2440 pw.println("Network Requester Pids:");
2441 for (int net : mPriorityList) {
2442 String pidString = net + ": ";
2443 for (Object pid : mNetRequestersPids[net]) {
2444 pidString = pidString + pid.toString() + ", ";
2445 }
2446 pw.println(pidString);
2447 }
2448 pw.println();
2449
2450 pw.println("FeatureUsers:");
2451 for (Object requester : mFeatureUsers) {
2452 pw.println(requester.toString());
2453 }
2454 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002455
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002456 synchronized (this) {
2457 pw.println("NetworkTranstionWakeLock is currently " +
2458 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2459 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2460 }
2461 pw.println();
2462
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002463 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002464
2465 if (mInetLog != null) {
2466 pw.println();
2467 pw.println("Inet condition reports:");
2468 for(int i = 0; i < mInetLog.size(); i++) {
2469 pw.println(mInetLog.get(i));
2470 }
2471 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002472 }
2473
Robert Greenwalt2034b912009-08-12 16:08:25 -07002474 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002475 private class NetworkStateTrackerHandler extends Handler {
2476 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002477 super(looper);
2478 }
2479
The Android Open Source Project28527d22009-03-03 19:31:44 -08002480 @Override
2481 public void handleMessage(Message msg) {
2482 NetworkInfo info;
2483 switch (msg.what) {
2484 case NetworkStateTracker.EVENT_STATE_CHANGED:
2485 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002486 int type = info.getType();
2487 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002488
Wink Savillea7d56572011-09-21 11:05:43 -07002489 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2490 (state == NetworkInfo.State.DISCONNECTED)) {
2491 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002492 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002493 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002494 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002495
2496 // Connectivity state changed:
Robert Greenwalt310fa082012-04-25 13:45:02 -07002497 // [31-14] Reserved for future use
2498 // [13-10] Network subtype (for mobile network, as defined
Robert Greenwalt0659da32009-07-16 17:21:39 -07002499 // by TelephonyManager)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002500 // [9-4] Detailed state ordinal (as defined by
Robert Greenwalt0659da32009-07-16 17:21:39 -07002501 // NetworkInfo.DetailedState)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002502 // [3-0] Network type (as defined by ConnectivityManager)
2503 int eventLogParam = (info.getType() & 0xf) |
2504 ((info.getDetailedState().ordinal() & 0x3f) << 4) |
2505 (info.getSubtype() << 10);
Doug Zongker2fc96232009-12-04 10:31:43 -08002506 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002507 eventLogParam);
2508
2509 if (info.getDetailedState() ==
2510 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002511 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002512 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002513 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002514 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002515 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002516 // the logic here is, handle SUSPENDED the same as
2517 // DISCONNECTED. The only difference being we are
2518 // broadcasting an intent with NetworkInfo that's
2519 // suspended. This allows the applications an
2520 // opportunity to handle DISCONNECTED and SUSPENDED
2521 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002522 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002523 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002524 handleConnect(info);
2525 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002526 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002527 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002528 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002529 // TODO: Temporary allowing network configuration
2530 // change not resetting sockets.
2531 // @see bug/4455071
2532 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002533 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002534 }
2535 }
2536 }
2537
2538 private class InternalHandler extends Handler {
2539 public InternalHandler(Looper looper) {
2540 super(looper);
2541 }
2542
2543 @Override
2544 public void handleMessage(Message msg) {
2545 NetworkInfo info;
2546 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002547 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002548 String causedBy = null;
2549 synchronized (ConnectivityService.this) {
2550 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2551 mNetTransitionWakeLock.isHeld()) {
2552 mNetTransitionWakeLock.release();
2553 causedBy = mNetTransitionWakeLockCausedBy;
2554 }
2555 }
2556 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002557 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002558 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002559 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002560 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002561 FeatureUser u = (FeatureUser)msg.obj;
2562 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002563 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002564 case EVENT_INET_CONDITION_CHANGE:
2565 {
2566 int netType = msg.arg1;
2567 int condition = msg.arg2;
2568 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002569 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002570 }
2571 case EVENT_INET_CONDITION_HOLD_END:
2572 {
2573 int netType = msg.arg1;
2574 int sequence = msg.arg2;
2575 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002576 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002577 }
2578 case EVENT_SET_NETWORK_PREFERENCE:
2579 {
2580 int preference = msg.arg1;
2581 handleSetNetworkPreference(preference);
2582 break;
2583 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002584 case EVENT_SET_MOBILE_DATA:
2585 {
2586 boolean enabled = (msg.arg1 == ENABLED);
2587 handleSetMobileData(enabled);
2588 break;
2589 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002590 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2591 {
2592 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002593 break;
2594 }
2595 case EVENT_SET_DEPENDENCY_MET:
2596 {
2597 boolean met = (msg.arg1 == ENABLED);
2598 handleSetDependencyMet(msg.arg2, met);
2599 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002600 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002601 case EVENT_RESTORE_DNS:
2602 {
2603 if (mActiveDefaultNetwork != -1) {
2604 handleDnsConfigurationChange(mActiveDefaultNetwork);
2605 }
2606 break;
2607 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002608 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2609 {
2610 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002611 sendStickyBroadcast(intent);
2612 break;
2613 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002614 case EVENT_SET_POLICY_DATA_ENABLE: {
2615 final int networkType = msg.arg1;
2616 final boolean enabled = msg.arg2 == ENABLED;
2617 handleSetPolicyDataEnable(networkType, enabled);
2618 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002619 }
2620 }
2621 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002622
2623 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002624 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002625 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002626
2627 if (isTetheringSupported()) {
2628 return mTethering.tether(iface);
2629 } else {
2630 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2631 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002632 }
2633
2634 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002635 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002636 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002637
2638 if (isTetheringSupported()) {
2639 return mTethering.untether(iface);
2640 } else {
2641 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2642 }
2643 }
2644
2645 // javadoc from interface
2646 public int getLastTetherError(String iface) {
2647 enforceTetherAccessPermission();
2648
2649 if (isTetheringSupported()) {
2650 return mTethering.getLastTetherError(iface);
2651 } else {
2652 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2653 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002654 }
2655
2656 // TODO - proper iface API for selection by property, inspection, etc
2657 public String[] getTetherableUsbRegexs() {
2658 enforceTetherAccessPermission();
2659 if (isTetheringSupported()) {
2660 return mTethering.getTetherableUsbRegexs();
2661 } else {
2662 return new String[0];
2663 }
2664 }
2665
2666 public String[] getTetherableWifiRegexs() {
2667 enforceTetherAccessPermission();
2668 if (isTetheringSupported()) {
2669 return mTethering.getTetherableWifiRegexs();
2670 } else {
2671 return new String[0];
2672 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002673 }
2674
Danica Chang96567052010-08-11 14:54:43 -07002675 public String[] getTetherableBluetoothRegexs() {
2676 enforceTetherAccessPermission();
2677 if (isTetheringSupported()) {
2678 return mTethering.getTetherableBluetoothRegexs();
2679 } else {
2680 return new String[0];
2681 }
2682 }
2683
Mike Lockwooded4a1742011-07-19 13:04:47 -07002684 public int setUsbTethering(boolean enable) {
2685 enforceTetherAccessPermission();
2686 if (isTetheringSupported()) {
2687 return mTethering.setUsbTethering(enable);
2688 } else {
2689 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2690 }
2691 }
2692
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002693 // TODO - move iface listing, queries, etc to new module
2694 // javadoc from interface
2695 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002696 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002697 return mTethering.getTetherableIfaces();
2698 }
2699
2700 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002701 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002702 return mTethering.getTetheredIfaces();
2703 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002704
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002705 @Override
2706 public String[] getTetheredIfacePairs() {
2707 enforceTetherAccessPermission();
2708 return mTethering.getTetheredIfacePairs();
2709 }
2710
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002711 public String[] getTetheringErroredIfaces() {
2712 enforceTetherAccessPermission();
2713 return mTethering.getErroredIfaces();
2714 }
2715
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002716 // if ro.tether.denied = true we default to no tethering
2717 // gservices could set the secure setting to 1 though to enable it on a build where it
2718 // had previously been turned off.
2719 public boolean isTetheringSupported() {
2720 enforceTetherAccessPermission();
2721 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002722 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2723 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2724 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002725 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002726
2727 // An API NetworkStateTrackers can call when they lose their network.
2728 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2729 // whichever happens first. The timer is started by the first caller and not
2730 // restarted by subsequent callers.
2731 public void requestNetworkTransitionWakelock(String forWhom) {
2732 enforceConnectivityInternalPermission();
2733 synchronized (this) {
2734 if (mNetTransitionWakeLock.isHeld()) return;
2735 mNetTransitionWakeLockSerialNumber++;
2736 mNetTransitionWakeLock.acquire();
2737 mNetTransitionWakeLockCausedBy = forWhom;
2738 }
2739 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002740 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002741 mNetTransitionWakeLockSerialNumber, 0),
2742 mNetTransitionWakeLockTimeout);
2743 return;
2744 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002745
Robert Greenwalt986c7412010-09-08 15:24:47 -07002746 // 100 percent is full good, 0 is full bad.
2747 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002748 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002749 mContext.enforceCallingOrSelfPermission(
2750 android.Manifest.permission.STATUS_BAR,
2751 "ConnectivityService");
2752
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002753 if (DBG) {
2754 int pid = getCallingPid();
2755 int uid = getCallingUid();
2756 String s = pid + "(" + uid + ") reports inet is " +
2757 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2758 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2759 mInetLog.add(s);
2760 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2761 mInetLog.remove(0);
2762 }
2763 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002764 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002765 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2766 }
2767
2768 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002769 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002770 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002771 return;
2772 }
2773 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002774 if (DBG) log("handleInetConditionChange: net=" + netType +
2775 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002776 return;
2777 }
Wink Savillea7d56572011-09-21 11:05:43 -07002778 if (VDBG) {
2779 log("handleInetConditionChange: net=" +
2780 netType + ", condition=" + condition +
2781 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2782 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002783 mDefaultInetCondition = condition;
2784 int delay;
2785 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002786 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002787 // setup a new hold to debounce this
2788 if (mDefaultInetCondition > 50) {
2789 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2790 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2791 } else {
2792 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2793 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2794 }
2795 mInetConditionChangeInFlight = true;
2796 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2797 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2798 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002799 // we've set the new condition, when this hold ends that will get picked up
2800 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002801 }
2802 }
2803
2804 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002805 if (DBG) {
2806 log("handleInetConditionHoldEnd: net=" + netType +
2807 ", condition=" + mDefaultInetCondition +
2808 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002809 }
2810 mInetConditionChangeInFlight = false;
2811
2812 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002813 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002814 return;
2815 }
2816 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07002817 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002818 return;
2819 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002820 // TODO: Figure out why this optimization sometimes causes a
2821 // change in mDefaultInetCondition to be missed and the
2822 // UI to not be updated.
2823 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2824 // if (DBG) log("no change in condition - aborting");
2825 // return;
2826 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002827 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2828 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002829 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002830 return;
2831 }
2832 mDefaultInetConditionPublished = mDefaultInetCondition;
2833 sendInetConditionBroadcast(networkInfo);
2834 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002835 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002836
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002837 public ProxyProperties getProxy() {
2838 synchronized (mDefaultProxyLock) {
2839 return mDefaultProxyDisabled ? null : mDefaultProxy;
2840 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002841 }
2842
2843 public void setGlobalProxy(ProxyProperties proxyProperties) {
2844 enforceChangePermission();
2845 synchronized (mGlobalProxyLock) {
2846 if (proxyProperties == mGlobalProxy) return;
2847 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2848 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2849
2850 String host = "";
2851 int port = 0;
2852 String exclList = "";
2853 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2854 mGlobalProxy = new ProxyProperties(proxyProperties);
2855 host = mGlobalProxy.getHost();
2856 port = mGlobalProxy.getPort();
2857 exclList = mGlobalProxy.getExclusionList();
2858 } else {
2859 mGlobalProxy = null;
2860 }
2861 ContentResolver res = mContext.getContentResolver();
2862 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2863 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002864 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002865 exclList);
2866 }
2867
2868 if (mGlobalProxy == null) {
2869 proxyProperties = mDefaultProxy;
2870 }
Chia-chi Yehae166612011-09-28 16:38:18 -07002871 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002872 }
2873
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002874 private void loadGlobalProxy() {
2875 ContentResolver res = mContext.getContentResolver();
2876 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2877 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2878 String exclList = Settings.Secure.getString(res,
2879 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2880 if (!TextUtils.isEmpty(host)) {
2881 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2882 synchronized (mGlobalProxyLock) {
2883 mGlobalProxy = proxyProperties;
2884 }
2885 }
2886 }
2887
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002888 public ProxyProperties getGlobalProxy() {
2889 synchronized (mGlobalProxyLock) {
2890 return mGlobalProxy;
2891 }
2892 }
2893
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002894 private void handleApplyDefaultProxy(ProxyProperties proxy) {
2895 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
2896 proxy = null;
2897 }
2898 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002899 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2900 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002901 mDefaultProxy = proxy;
2902
2903 if (!mDefaultProxyDisabled) {
2904 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002905 }
2906 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002907 }
2908
2909 private void handleDeprecatedGlobalHttpProxy() {
2910 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2911 Settings.Secure.HTTP_PROXY);
2912 if (!TextUtils.isEmpty(proxy)) {
2913 String data[] = proxy.split(":");
2914 String proxyHost = data[0];
2915 int proxyPort = 8080;
2916 if (data.length > 1) {
2917 try {
2918 proxyPort = Integer.parseInt(data[1]);
2919 } catch (NumberFormatException e) {
2920 return;
2921 }
2922 }
2923 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2924 setGlobalProxy(p);
2925 }
2926 }
2927
2928 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002929 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07002930 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002931 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002932 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2933 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002934 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002935 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002936 }
2937
2938 private static class SettingsObserver extends ContentObserver {
2939 private int mWhat;
2940 private Handler mHandler;
2941 SettingsObserver(Handler handler, int what) {
2942 super(handler);
2943 mHandler = handler;
2944 mWhat = what;
2945 }
2946
2947 void observe(Context context) {
2948 ContentResolver resolver = context.getContentResolver();
2949 resolver.registerContentObserver(Settings.Secure.getUriFor(
2950 Settings.Secure.HTTP_PROXY), false, this);
2951 }
2952
2953 @Override
2954 public void onChange(boolean selfChange) {
2955 mHandler.obtainMessage(mWhat).sendToTarget();
2956 }
2957 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002958
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002959 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002960 Slog.d(TAG, s);
2961 }
2962
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002963 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002964 Slog.e(TAG, s);
2965 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002966
repo syncf5de5572011-07-29 23:55:49 -07002967 int convertFeatureToNetworkType(int networkType, String feature) {
2968 int usedNetworkType = networkType;
2969
2970 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2971 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2972 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2973 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2974 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2975 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2976 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2977 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2978 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2979 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2980 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2981 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2982 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2983 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2984 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2985 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2986 } else {
2987 Slog.e(TAG, "Can't match any mobile netTracker!");
2988 }
2989 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2990 if (TextUtils.equals(feature, "p2p")) {
2991 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2992 } else {
2993 Slog.e(TAG, "Can't match any wifi netTracker!");
2994 }
2995 } else {
2996 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08002997 }
repo syncf5de5572011-07-29 23:55:49 -07002998 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08002999 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003000
3001 private static <T> T checkNotNull(T value, String message) {
3002 if (value == null) {
3003 throw new NullPointerException(message);
3004 }
3005 return value;
3006 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003007
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003008 /**
3009 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003010 * VpnBuilder and not available in ConnectivityManager. Permissions
3011 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003012 * @hide
3013 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003014 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003015 public boolean protectVpn(ParcelFileDescriptor socket) {
3016 try {
3017 int type = mActiveDefaultNetwork;
3018 if (ConnectivityManager.isNetworkTypeValid(type)) {
3019 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3020 return true;
3021 }
3022 } catch (Exception e) {
3023 // ignore
3024 } finally {
3025 try {
3026 socket.close();
3027 } catch (Exception e) {
3028 // ignore
3029 }
3030 }
3031 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003032 }
3033
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003034 /**
3035 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003036 * and not available in ConnectivityManager. Permissions are checked
3037 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003038 * @hide
3039 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003040 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003041 public boolean prepareVpn(String oldPackage, String newPackage) {
3042 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003043 }
3044
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003045 /**
3046 * Configure a TUN interface and return its file descriptor. Parameters
3047 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003048 * and not available in ConnectivityManager. Permissions are checked in
3049 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003050 * @hide
3051 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003052 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003053 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003054 return mVpn.establish(config);
3055 }
3056
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003057 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003058 * Start legacy VPN and return an intent to VpnDialogs. This method is
3059 * used by VpnSettings and not available in ConnectivityManager.
3060 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003061 * @hide
3062 */
3063 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003064 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
3065 mVpn.startLegacyVpn(config, racoon, mtpd);
3066 }
3067
3068 /**
3069 * Return the information of the ongoing legacy VPN. This method is used
3070 * by VpnSettings and not available in ConnectivityManager. Permissions
3071 * are checked in Vpn class.
3072 * @hide
3073 */
3074 @Override
3075 public LegacyVpnInfo getLegacyVpnInfo() {
3076 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003077 }
3078
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003079 /**
3080 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3081 * through NetworkStateTracker since it works differently. For example, it
3082 * needs to override DNS servers but never takes the default routes. It
3083 * relies on another data network, and it could keep existing connections
3084 * alive after reconnecting, switching between networks, or even resuming
3085 * from deep sleep. Calls from applications should be done synchronously
3086 * to avoid race conditions. As these are all hidden APIs, refactoring can
3087 * be done whenever a better abstraction is developed.
3088 */
3089 public class VpnCallback {
3090
3091 private VpnCallback() {
3092 }
3093
Chia-chi Yehcc844502011-07-14 18:01:57 -07003094 public void override(List<String> dnsServers, List<String> searchDomains) {
3095 if (dnsServers == null) {
3096 restore();
3097 return;
3098 }
3099
3100 // Convert DNS servers into addresses.
3101 List<InetAddress> addresses = new ArrayList<InetAddress>();
3102 for (String address : dnsServers) {
3103 // Double check the addresses and remove invalid ones.
3104 try {
3105 addresses.add(InetAddress.parseNumericAddress(address));
3106 } catch (Exception e) {
3107 // ignore
3108 }
3109 }
3110 if (addresses.isEmpty()) {
3111 restore();
3112 return;
3113 }
3114
3115 // Concatenate search domains into a string.
3116 StringBuilder buffer = new StringBuilder();
3117 if (searchDomains != null) {
3118 for (String domain : searchDomains) {
3119 buffer.append(domain).append(' ');
3120 }
3121 }
3122 String domains = buffer.toString().trim();
3123
3124 // Apply DNS changes.
3125 boolean changed = false;
3126 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07003127 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003128 mDnsOverridden = true;
3129 }
3130 if (changed) {
3131 bumpDns();
3132 }
3133
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003134 // Temporarily disable the default proxy.
3135 synchronized (mDefaultProxyLock) {
3136 mDefaultProxyDisabled = true;
3137 if (mDefaultProxy != null) {
3138 sendProxyBroadcast(null);
3139 }
3140 }
3141
3142 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003143 }
3144
Chia-chi Yehcc844502011-07-14 18:01:57 -07003145 public void restore() {
3146 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003147 if (mDnsOverridden) {
3148 mDnsOverridden = false;
3149 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003150 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003151 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003152 synchronized (mDefaultProxyLock) {
3153 mDefaultProxyDisabled = false;
3154 if (mDefaultProxy != null) {
3155 sendProxyBroadcast(mDefaultProxy);
3156 }
3157 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003158 }
3159 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003160}