blob: 6dcb4034e5007a4ecafef37898980fe38ac50e06 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyfb878b62012-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 Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080034import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070035import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.ContentResolver;
37import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090038import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.PackageManager;
tk.mun148c7d02011-10-13 22:51:57 +090042import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070043import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070044import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080046import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080047import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070049import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070050import android.net.INetworkPolicyListener;
51import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070052import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070053import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070057import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070059import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070060import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070061import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070063import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070064import android.net.Proxy;
65import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070066import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090068import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040070import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070072import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070073import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070074import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Looper;
76import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070077import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070078import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070079import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070080import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070082import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070084import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070086import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070087import android.security.KeyStore;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080089import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070090import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
Chia-chi Yeh2e467642011-07-04 03:23:12 -070092import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070093import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070094import com.android.internal.net.VpnProfile;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -070096import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -070097import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070098import com.android.server.am.BatteryStatsService;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +090099import com.android.server.connectivity.Nat464Xlat;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800100import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700101import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700102import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700104import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700105import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700106
tk.mun148c7d02011-10-13 22:51:57 +0900107import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700110import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900112import java.lang.reflect.Constructor;
Wink Savillec9822c52011-07-14 12:23:28 -0700113import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700114import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700115import java.net.InetAddress;
116import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700117import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700118import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700119import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700120import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700122import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
124/**
125 * @hide
126 */
127public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700128 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
Robert Greenwaltba175a52010-10-05 19:12:26 -0700130 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700131 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700133 private static final boolean LOGD_RULES = false;
134
Jeff Sharkey899223b2012-08-04 15:24:58 -0700135 // TODO: create better separation between radio types and network types
136
Robert Greenwalt42acef32009-08-12 16:08:25 -0700137 // how long to wait before switching back to a radio's default network
138 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
139 // system property that can override the above value
140 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
141 "android.telephony.apn-restore";
142
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700143 // used in recursive route setting to add gateways for the host for which
144 // a host route was requested.
145 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
146
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800147 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800148 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800149
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700150 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700151
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700152 private Vpn mVpn;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700153 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700154
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700155 private boolean mLockdownEnabled;
156 private LockdownVpnTracker mLockdownTracker;
157
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900158 private Nat464Xlat mClat;
159
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
161 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700162 /** Currently active network rules by UID. */
163 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164 /** Set of ifaces that are costly. */
165 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
168 * Sometimes we want to refer to the individual network state
169 * trackers separately, and sometimes we just want to treat them
170 * abstractly.
171 */
172 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700173
Irfan Sheriffda6da092012-08-16 12:49:23 -0700174 /* Handles captive portal check on a network */
175 private CaptivePortalTracker mCaptivePortalTracker;
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 /**
Wink Savillee8222252011-07-13 13:44:13 -0700178 * The link properties that define the current links
179 */
180 private LinkProperties mCurrentLinkProperties[];
181
182 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700183 * A per Net list of the PID's that requested access to the net
184 * used both as a refcount and for per-PID DNS selection
185 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200186 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700187
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188 // priority order of the nettrackers
189 // (excluding dynamically set mNetworkPreference)
190 // TODO - move mNetworkTypePreference into this
191 private int[] mPriorityList;
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
194 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700195 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700196 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000197 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700198 private int mDefaultInetConditionPublished = 0;
199 private boolean mInetConditionChangeInFlight = false;
200 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700202 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800203 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700204 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700207 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700209 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700211
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700212 private static final int ENABLED = 1;
213 private static final int DISABLED = 0;
214
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700215 private static final boolean ADD = true;
216 private static final boolean REMOVE = false;
217
218 private static final boolean TO_DEFAULT_TABLE = true;
219 private static final boolean TO_SECONDARY_TABLE = false;
220
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700221 /**
222 * used internally as a delayed event to make us switch back to the
223 * default network
224 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700225 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226
227 /**
228 * used internally to change our mobile data enabled flag
229 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700230 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700231
232 /**
233 * used internally to change our network preference setting
234 * arg1 = networkType to prefer
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
239 * used internally to synchronize inet condition reports
240 * arg1 = networkType
241 * arg2 = condition (0 bad, 100 good)
242 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700243 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244
245 /**
246 * used internally to mark the end of inet condition hold periods
247 * arg1 = networkType
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700250
251 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252 * used internally to set enable/disable cellular data
253 * arg1 = ENBALED or DISABLED
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256
Robert Greenwaltf3331232010-09-24 14:32:21 -0700257 /**
258 * used internally to clear a wakelock when transitioning
259 * from one net to another
260 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700261 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700262
Robert Greenwalt434203a2010-10-11 16:00:27 -0700263 /**
264 * used internally to reload global proxy settings
265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700267
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700268 /**
269 * used internally to set external dependency met/unmet
270 * arg1 = ENABLED (met) or DISABLED (unmet)
271 * arg2 = NetworkType
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700274
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700275 /**
276 * used internally to restore DNS properties back to the
277 * default network
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700280
Wink Saville2b30afd2011-08-05 11:40:22 -0700281 /**
Wink Saville628b0852011-08-04 15:01:58 -0700282 * used internally to send a sticky broadcast delayed.
283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700285
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700286 /**
287 * Used internally to
288 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700291
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700292 private static final int EVENT_VPN_STATE_CHANGED = 14;
293
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 /** Handler used for internal events. */
295 private InternalHandler mHandler;
296 /** Handler used for incoming {@link NetworkStateTracker} events. */
297 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700298
299 // list of DeathRecipients used to make sure features are turned off when
300 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500301 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700302
Mike Lockwood0f79b542009-08-14 14:18:49 -0400303 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800304 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400305
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700306 private PowerManager.WakeLock mNetTransitionWakeLock;
307 private String mNetTransitionWakeLockCausedBy = "";
308 private int mNetTransitionWakeLockSerialNumber;
309 private int mNetTransitionWakeLockTimeout;
310
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700311 private InetAddress mDefaultDns;
312
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700313 // this collection is used to refcount the added routes - if there are none left
314 // it's time to remove the route from the route table
315 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
316
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700317 // used in DBG mode to track inet condition reports
318 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
319 private ArrayList mInetLog;
320
Robert Greenwalt434203a2010-10-11 16:00:27 -0700321 // track the current default http proxy - tell the world if we get a new one (real change)
322 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700323 private Object mDefaultProxyLock = new Object();
324 private boolean mDefaultProxyDisabled = false;
325
Robert Greenwalt434203a2010-10-11 16:00:27 -0700326 // track the global proxy.
327 private ProxyProperties mGlobalProxy = null;
328 private final Object mGlobalProxyLock = new Object();
329
330 private SettingsObserver mSettingsObserver;
331
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700332 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700333 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700334
Robert Greenwalt511288a2009-12-07 11:33:18 -0800335 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700336 public int mSimultaneity;
337 public int mType;
338 public RadioAttributes(String init) {
339 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700340 mType = Integer.parseInt(fragments[0]);
341 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700342 }
343 }
344 RadioAttributes[] mRadioAttributes;
345
Robert Greenwalt50393202011-06-21 17:26:14 -0700346 // the set of network types that can only be enabled by system/sig apps
347 List mProtectedNetworks;
348
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700349 public ConnectivityService(Context context, INetworkManagementService netd,
350 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700351 // Currently, omitting a NetworkFactory will create one internally
352 // TODO: create here when we have cleaner WiMAX support
353 this(context, netd, statsService, policyManager, null);
354 }
355
Jeff Sharkey899223b2012-08-04 15:24:58 -0700356 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700357 INetworkStatsService statsService, INetworkPolicyManager policyManager,
358 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800359 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800360
Wink Savillebb08caf2010-09-02 19:23:52 -0700361 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
362 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700363 mHandler = new InternalHandler(handlerThread.getLooper());
364 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700365
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700366 if (netFactory == null) {
367 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
368 }
369
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800370 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800371 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
372 String id = Settings.Secure.getString(context.getContentResolver(),
373 Settings.Secure.ANDROID_ID);
374 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700375 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800376 SystemProperties.set("net.hostname", name);
377 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800378 }
379
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700380 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700381 String dns = Settings.Global.getString(context.getContentResolver(),
382 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700383 if (dns == null || dns.length() == 0) {
384 dns = context.getResources().getString(
385 com.android.internal.R.string.config_default_dns_server);
386 }
387 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800388 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
389 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800390 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700391 }
392
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700393 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700394 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700395 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700396 mKeyStore = KeyStore.getInstance();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700397
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700398 try {
399 mPolicyManager.registerListener(mPolicyListener);
400 } catch (RemoteException e) {
401 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700402 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700403 }
404
405 final PowerManager powerManager = (PowerManager) context.getSystemService(
406 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700407 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
408 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
409 com.android.internal.R.integer.config_networkTransitionTimeout);
410
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411 mNetTrackers = new NetworkStateTracker[
412 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700413 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700414
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700415 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700416 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700417
Robert Greenwalt42acef32009-08-12 16:08:25 -0700418 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700419 String[] raStrings = context.getResources().getStringArray(
420 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700421 for (String raString : raStrings) {
422 RadioAttributes r = new RadioAttributes(raString);
423 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800424 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700425 continue;
426 }
427 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800428 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 r.mType);
430 continue;
431 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700432 mRadioAttributes[r.mType] = r;
433 }
434
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 String[] naStrings = context.getResources().getStringArray(
436 com.android.internal.R.array.networkAttributes);
437 for (String naString : naStrings) {
438 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700439 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700440 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800441 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700442 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700443 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700444 }
Wink Saville975c8482011-04-07 14:23:45 -0700445 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800446 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700447 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700448 continue;
449 }
Wink Saville975c8482011-04-07 14:23:45 -0700450 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800451 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700452 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700453 continue;
454 }
Wink Saville975c8482011-04-07 14:23:45 -0700455 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700456 mNetworksDefined++;
457 } catch(Exception e) {
458 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700459 }
460 }
461
Robert Greenwalt50393202011-06-21 17:26:14 -0700462 mProtectedNetworks = new ArrayList<Integer>();
463 int[] protectedNetworks = context.getResources().getIntArray(
464 com.android.internal.R.array.config_protectedNetworks);
465 for (int p : protectedNetworks) {
466 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
467 mProtectedNetworks.add(p);
468 } else {
469 if (DBG) loge("Ignoring protectedNetwork " + p);
470 }
471 }
472
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700473 // high priority first
474 mPriorityList = new int[mNetworksDefined];
475 {
476 int insertionPoint = mNetworksDefined-1;
477 int currentLowest = 0;
478 int nextLowest = 0;
479 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700480 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700481 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700482 if (na.priority < currentLowest) continue;
483 if (na.priority > currentLowest) {
484 if (na.priority < nextLowest || nextLowest == 0) {
485 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700486 }
487 continue;
488 }
Wink Saville975c8482011-04-07 14:23:45 -0700489 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700490 }
491 currentLowest = nextLowest;
492 nextLowest = 0;
493 }
494 }
495
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800496 // Update mNetworkPreference according to user mannually first then overlay config.xml
497 mNetworkPreference = getPersistedNetworkPreference();
498 if (mNetworkPreference == -1) {
499 for (int n : mPriorityList) {
500 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
501 mNetworkPreference = n;
502 break;
503 }
504 }
505 if (mNetworkPreference == -1) {
506 throw new IllegalStateException(
507 "You should set at least one default Network in config.xml!");
508 }
509 }
510
Mattias Falk8b47b362011-08-23 14:15:13 +0200511 mNetRequestersPids =
512 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700513 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200514 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700515 }
516
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500517 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700518
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700519 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
520 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700521
522 // Create and start trackers for hard-coded networks
523 for (int targetNetworkType : mPriorityList) {
524 final NetworkConfig config = mNetConfigs[targetNetworkType];
525 final NetworkStateTracker tracker;
526 try {
527 tracker = netFactory.createTracker(targetNetworkType, config);
528 mNetTrackers[targetNetworkType] = tracker;
529 } catch (IllegalArgumentException e) {
530 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
531 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700532 continue;
533 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700534
535 tracker.startMonitoring(context, mTrackerHandler);
536 if (config.isDefault()) {
537 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800538 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700539 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800540
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700541 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700542 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700543 mTethering.getTetherableWifiRegexs().length != 0 ||
544 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700545 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800546
Jeff Sharkey899223b2012-08-04 15:24:58 -0700547 mVpn = new Vpn(mContext, mVpnCallback, mNetd);
548 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700549
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900550 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
551
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700552 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700553 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700554 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900555 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700556 } catch (RemoteException e) {
557 loge("Error registering observer :" + e);
558 }
559
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700560 if (DBG) {
561 mInetLog = new ArrayList();
562 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700563
564 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
565 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800566
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700567 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800568 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700570
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700571 /**
572 * Factory that creates {@link NetworkStateTracker} instances using given
573 * {@link NetworkConfig}.
574 */
575 public interface NetworkFactory {
576 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
577 }
578
579 private static class DefaultNetworkFactory implements NetworkFactory {
580 private final Context mContext;
581 private final Handler mTrackerHandler;
582
583 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
584 mContext = context;
585 mTrackerHandler = trackerHandler;
586 }
587
588 @Override
589 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
590 switch (config.radio) {
591 case TYPE_WIFI:
592 return new WifiStateTracker(targetNetworkType, config.name);
593 case TYPE_MOBILE:
594 return new MobileDataStateTracker(targetNetworkType, config.name);
595 case TYPE_DUMMY:
596 return new DummyDataStateTracker(targetNetworkType, config.name);
597 case TYPE_BLUETOOTH:
598 return BluetoothTetheringDataTracker.getInstance();
599 case TYPE_WIMAX:
600 return makeWimaxStateTracker(mContext, mTrackerHandler);
601 case TYPE_ETHERNET:
602 return EthernetDataTracker.getInstance();
603 default:
604 throw new IllegalArgumentException(
605 "Trying to create a NetworkStateTracker for an unknown radio type: "
606 + config.radio);
607 }
608 }
609 }
610
611 /**
612 * Loads external WiMAX library and registers as system service, returning a
613 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
614 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
615 */
616 private static NetworkStateTracker makeWimaxStateTracker(
617 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700618 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900619 DexClassLoader wimaxClassLoader;
620 Class wimaxStateTrackerClass = null;
621 Class wimaxServiceClass = null;
622 Class wimaxManagerClass;
623 String wimaxJarLocation;
624 String wimaxLibLocation;
625 String wimaxManagerClassName;
626 String wimaxServiceClassName;
627 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628
tk.mun148c7d02011-10-13 22:51:57 +0900629 NetworkStateTracker wimaxStateTracker = null;
630
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700631 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900632 com.android.internal.R.bool.config_wimaxEnabled);
633
634 if (isWimaxEnabled) {
635 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700636 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900637 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700638 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900639 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700640 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900641 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700642 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900643 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700644 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900645 com.android.internal.R.string.config_wimaxStateTrackerClassname);
646
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800647 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900648 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700649 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900650 wimaxLibLocation, ClassLoader.getSystemClassLoader());
651
652 try {
653 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
654 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
655 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
656 } catch (ClassNotFoundException ex) {
657 loge("Exception finding Wimax classes: " + ex.toString());
658 return null;
659 }
660 } catch(Resources.NotFoundException ex) {
661 loge("Wimax Resources does not exist!!! ");
662 return null;
663 }
664
665 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800666 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900667
668 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
669 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700670 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
671 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900672
673 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
674 (new Class[] {Context.class, wimaxStateTrackerClass});
675 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700676 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900677 wmxSrvConst.setAccessible(false);
678
679 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
680
681 } catch(Exception ex) {
682 loge("Exception creating Wimax classes: " + ex.toString());
683 return null;
684 }
685 } else {
686 loge("Wimax is not enabled or not added to the network attributes!!! ");
687 return null;
688 }
689
690 return wimaxStateTracker;
691 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700694 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 * @param preference the new preference
696 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700697 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700699
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700700 mHandler.sendMessage(
701 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
703
704 public int getNetworkPreference() {
705 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700706 int preference;
707 synchronized(this) {
708 preference = mNetworkPreference;
709 }
710 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700713 private void handleSetNetworkPreference(int preference) {
714 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700715 mNetConfigs[preference] != null &&
716 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700717 if (mNetworkPreference != preference) {
718 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700719 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700720 synchronized(this) {
721 mNetworkPreference = preference;
722 }
723 enforcePreference();
724 }
725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700727
Wink Saville628b0852011-08-04 15:01:58 -0700728 private int getConnectivityChangeDelay() {
729 final ContentResolver cr = mContext.getContentResolver();
730
731 /** Check system properties for the default value then use secure settings value, if any. */
732 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700733 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
734 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
735 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700736 defaultDelay);
737 }
738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 private int getPersistedNetworkPreference() {
740 final ContentResolver cr = mContext.getContentResolver();
741
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700742 final int networkPrefSetting = Settings.Global
743 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800745 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700749 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 * In this method, we only tear down a non-preferred network. Establishing
751 * a connection to the preferred network is taken care of when we handle
752 * the disconnect event from the non-preferred network
753 * (see {@link #handleDisconnect(NetworkInfo)}).
754 */
755 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700756 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 return;
758
Robert Greenwalt42acef32009-08-12 16:08:25 -0700759 if (!mNetTrackers[mNetworkPreference].isAvailable())
760 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761
Robert Greenwalt42acef32009-08-12 16:08:25 -0700762 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700763 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700764 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700765 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800766 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700767 " in enforcePreference");
768 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700769 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
771 }
772 }
773
774 private boolean teardown(NetworkStateTracker netTracker) {
775 if (netTracker.teardown()) {
776 netTracker.setTeardownRequested(true);
777 return true;
778 } else {
779 return false;
780 }
781 }
782
783 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700784 * Check if UID should be blocked from using the network represented by the
785 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700786 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700787 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
788 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700789
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700790 final boolean networkCostly;
791 final int uidRules;
792 synchronized (mRulesLock) {
793 networkCostly = mMeteredIfaces.contains(iface);
794 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700795 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700796
797 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
798 return true;
799 }
800
801 // no restrictive rules; network is visible
802 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700803 }
804
805 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700806 * Return a filtered {@link NetworkInfo}, potentially marked
807 * {@link DetailedState#BLOCKED} based on
808 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700809 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700810 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
811 NetworkInfo info = tracker.getNetworkInfo();
812 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700813 // network is blocked; clone and override state
814 info = new NetworkInfo(info);
815 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700816 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700817 if (mLockdownTracker != null) {
818 info = mLockdownTracker.augmentNetworkInfo(info);
819 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700820 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700821 }
822
823 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 * Return NetworkInfo for the active (i.e., connected) network interface.
825 * It is assumed that at most one network is active at a time. If more
826 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700827 * @return the info for the active network, or {@code null} if none is
828 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700830 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700832 enforceAccessPermission();
833 final int uid = Binder.getCallingUid();
834 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700837 public NetworkInfo getActiveNetworkInfoUnfiltered() {
838 enforceAccessPermission();
839 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
840 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
841 if (tracker != null) {
842 return tracker.getNetworkInfo();
843 }
844 }
845 return null;
846 }
847
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700848 @Override
849 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
850 enforceConnectivityInternalPermission();
851 return getNetworkInfo(mActiveDefaultNetwork, uid);
852 }
853
854 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 public NetworkInfo getNetworkInfo(int networkType) {
856 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700857 final int uid = Binder.getCallingUid();
858 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 }
860
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700861 private NetworkInfo getNetworkInfo(int networkType, int uid) {
862 NetworkInfo info = null;
863 if (isNetworkTypeValid(networkType)) {
864 final NetworkStateTracker tracker = mNetTrackers[networkType];
865 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700866 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700867 }
868 }
869 return info;
870 }
871
872 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 public NetworkInfo[] getAllNetworkInfo() {
874 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700876 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700877 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700878 for (NetworkStateTracker tracker : mNetTrackers) {
879 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700880 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700881 }
882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700884 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700887 @Override
888 public boolean isNetworkSupported(int networkType) {
889 enforceAccessPermission();
890 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
891 }
892
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700893 /**
894 * Return LinkProperties for the active (i.e., connected) default
895 * network interface. It is assumed that at most one default network
896 * is active at a time. If more than one is active, it is indeterminate
897 * which will be returned.
898 * @return the ip properties for the active network, or {@code null} if
899 * none is active
900 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700901 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700902 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700903 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700904 }
905
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700906 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700907 public LinkProperties getLinkProperties(int networkType) {
908 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700909 if (isNetworkTypeValid(networkType)) {
910 final NetworkStateTracker tracker = mNetTrackers[networkType];
911 if (tracker != null) {
912 return tracker.getLinkProperties();
913 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700914 }
915 return null;
916 }
917
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700918 @Override
919 public NetworkState[] getAllNetworkState() {
920 enforceAccessPermission();
921 final int uid = Binder.getCallingUid();
922 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700923 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700924 for (NetworkStateTracker tracker : mNetTrackers) {
925 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700926 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700927 result.add(new NetworkState(
928 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
929 }
930 }
931 }
932 return result.toArray(new NetworkState[result.size()]);
933 }
934
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700935 private NetworkState getNetworkStateUnchecked(int networkType) {
936 if (isNetworkTypeValid(networkType)) {
937 final NetworkStateTracker tracker = mNetTrackers[networkType];
938 if (tracker != null) {
939 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
940 tracker.getLinkCapabilities());
941 }
942 }
943 return null;
944 }
945
946 @Override
947 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
948 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700949
950 final long token = Binder.clearCallingIdentity();
951 try {
952 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
953 if (state != null) {
954 try {
955 return mPolicyManager.getNetworkQuotaInfo(state);
956 } catch (RemoteException e) {
957 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700958 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700959 return null;
960 } finally {
961 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700962 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700963 }
964
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700965 @Override
966 public boolean isActiveNetworkMetered() {
967 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700968 final long token = Binder.clearCallingIdentity();
969 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700970 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700971 } finally {
972 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700973 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700974 }
975
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700976 private boolean isNetworkMeteredUnchecked(int networkType) {
977 final NetworkState state = getNetworkStateUnchecked(networkType);
978 if (state != null) {
979 try {
980 return mPolicyManager.isNetworkMetered(state);
981 } catch (RemoteException e) {
982 }
983 }
984 return false;
985 }
986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public boolean setRadios(boolean turnOn) {
988 boolean result = true;
989 enforceChangePermission();
990 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700991 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993 return result;
994 }
995
996 public boolean setRadio(int netType, boolean turnOn) {
997 enforceChangePermission();
998 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
999 return false;
1000 }
1001 NetworkStateTracker tracker = mNetTrackers[netType];
1002 return tracker != null && tracker.setRadio(turnOn);
1003 }
1004
Jeff Sharkey216c1812012-08-05 14:29:23 -07001005 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1006 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001007 public void interfaceClassDataActivityChanged(String label, boolean active) {
1008 int deviceType = Integer.parseInt(label);
1009 sendDataActivityBroadcast(deviceType, active);
1010 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001011 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001012
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001013 /**
1014 * Used to notice when the calling process dies so we can self-expire
1015 *
1016 * Also used to know if the process has cleaned up after itself when
1017 * our auto-expire timer goes off. The timer has a link to an object.
1018 *
1019 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001020 private class FeatureUser implements IBinder.DeathRecipient {
1021 int mNetworkType;
1022 String mFeature;
1023 IBinder mBinder;
1024 int mPid;
1025 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001026 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001027
1028 FeatureUser(int type, String feature, IBinder binder) {
1029 super();
1030 mNetworkType = type;
1031 mFeature = feature;
1032 mBinder = binder;
1033 mPid = getCallingPid();
1034 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001035 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001036
Robert Greenwalt42acef32009-08-12 16:08:25 -07001037 try {
1038 mBinder.linkToDeath(this, 0);
1039 } catch (RemoteException e) {
1040 binderDied();
1041 }
1042 }
1043
1044 void unlinkDeathRecipient() {
1045 mBinder.unlinkToDeath(this, 0);
1046 }
1047
1048 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001049 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001050 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1051 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001052 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001053 }
1054
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001055 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001056 if (VDBG) {
1057 log("ConnectivityService FeatureUser expire(" +
1058 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1059 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1060 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001061 stopUsingNetworkFeature(this, false);
1062 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001063
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001064 public boolean isSameUser(FeatureUser u) {
1065 if (u == null) return false;
1066
1067 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1068 }
1069
1070 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1071 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1072 TextUtils.equals(mFeature, feature)) {
1073 return true;
1074 }
1075 return false;
1076 }
1077
Robert Greenwaltb9285352009-12-21 18:24:07 -08001078 public String toString() {
1079 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1080 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1081 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001082 }
1083
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001084 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001085 public int startUsingNetworkFeature(int networkType, String feature,
1086 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001087 long startTime = 0;
1088 if (DBG) {
1089 startTime = SystemClock.elapsedRealtime();
1090 }
Wink Savillec9acde92011-09-21 11:05:43 -07001091 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001092 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1093 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001096 try {
1097 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1098 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001099 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001100 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001101
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001102 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001103
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001104 // TODO - move this into individual networktrackers
1105 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001106
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001107 if (mLockdownEnabled) {
1108 // Since carrier APNs usually aren't available from VPN
1109 // endpoint, mark them as unavailable.
1110 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1111 }
1112
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001113 if (mProtectedNetworks.contains(usedNetworkType)) {
1114 enforceConnectivityInternalPermission();
1115 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001116
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001117 // if UID is restricted, don't allow them to bring up metered APNs
1118 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1119 final int uidRules;
1120 synchronized (mRulesLock) {
1121 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1122 }
1123 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001124 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001125 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001126
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001127 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1128 if (network != null) {
1129 Integer currentPid = new Integer(getCallingPid());
1130 if (usedNetworkType != networkType) {
1131 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001132
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001133 if (ni.isAvailable() == false) {
1134 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1135 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001136 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001137 } else {
1138 // else make the attempt anyway - probably giving REQUEST_STARTED below
1139 if (DBG) {
1140 log("special network not available, but try anyway ni=" +
1141 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001142 }
1143 }
1144 }
1145
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001146 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001147
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001148 synchronized(this) {
1149 boolean addToList = true;
1150 if (restoreTimer < 0) {
1151 // In case there is no timer is specified for the feature,
1152 // make sure we don't add duplicate entry with the same request.
1153 for (FeatureUser u : mFeatureUsers) {
1154 if (u.isSameUser(f)) {
1155 // Duplicate user is found. Do not add.
1156 addToList = false;
1157 break;
1158 }
1159 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001160 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001161
1162 if (addToList) mFeatureUsers.add(f);
1163 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1164 // this gets used for per-pid dns when connected
1165 mNetRequestersPids[usedNetworkType].add(currentPid);
1166 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001167 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001168
1169 if (restoreTimer >= 0) {
1170 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1171 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1172 }
1173
1174 if ((ni.isConnectedOrConnecting() == true) &&
1175 !network.isTeardownRequested()) {
1176 if (ni.isConnected() == true) {
1177 final long token = Binder.clearCallingIdentity();
1178 try {
1179 // add the pid-specific dns
1180 handleDnsConfigurationChange(usedNetworkType);
1181 if (VDBG) log("special network already active");
1182 } finally {
1183 Binder.restoreCallingIdentity(token);
1184 }
Wink Savillea639b312012-07-10 12:37:54 -07001185 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001186 }
1187 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001188 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001189 }
1190
1191 // check if the radio in play can make another contact
1192 // assume if cannot for now
1193
1194 if (DBG) {
1195 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1196 feature);
1197 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001198 if (network.reconnect()) {
1199 return PhoneConstants.APN_REQUEST_STARTED;
1200 } else {
1201 return PhoneConstants.APN_REQUEST_FAILED;
1202 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001203 } else {
1204 // need to remember this unsupported request so we respond appropriately on stop
1205 synchronized(this) {
1206 mFeatureUsers.add(f);
1207 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1208 // this gets used for per-pid dns when connected
1209 mNetRequestersPids[usedNetworkType].add(currentPid);
1210 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001211 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001212 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001213 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001214 }
Wink Savillea639b312012-07-10 12:37:54 -07001215 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001216 } finally {
1217 if (DBG) {
1218 final long execTime = SystemClock.elapsedRealtime() - startTime;
1219 if (execTime > 250) {
1220 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1221 } else {
1222 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1223 }
1224 }
1225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
1227
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001228 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001230 enforceChangePermission();
1231
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001232 int pid = getCallingPid();
1233 int uid = getCallingUid();
1234
1235 FeatureUser u = null;
1236 boolean found = false;
1237
1238 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001239 for (FeatureUser x : mFeatureUsers) {
1240 if (x.isSameUser(pid, uid, networkType, feature)) {
1241 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001242 found = true;
1243 break;
1244 }
1245 }
1246 }
1247 if (found && u != null) {
1248 // stop regardless of how many other time this proc had called start
1249 return stopUsingNetworkFeature(u, true);
1250 } else {
1251 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001252 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001253 return 1;
1254 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001255 }
1256
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001257 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1258 int networkType = u.mNetworkType;
1259 String feature = u.mFeature;
1260 int pid = u.mPid;
1261 int uid = u.mUid;
1262
1263 NetworkStateTracker tracker = null;
1264 boolean callTeardown = false; // used to carry our decision outside of sync block
1265
Wink Savillec9acde92011-09-21 11:05:43 -07001266 if (VDBG) {
1267 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001268 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001271 if (DBG) {
1272 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1273 ", net is invalid");
1274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 return -1;
1276 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001277
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001278 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1279 // sync block
1280 synchronized(this) {
1281 // check if this process still has an outstanding start request
1282 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001283 if (VDBG) {
1284 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1285 ", ignoring");
1286 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001287 return 1;
1288 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001289 u.unlinkDeathRecipient();
1290 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1291 // If we care about duplicate requests, check for that here.
1292 //
1293 // This is done to support the extension of a request - the app
1294 // can request we start the network feature again and renew the
1295 // auto-shutoff delay. Normal "stop" calls from the app though
1296 // do not pay attention to duplicate requests - in effect the
1297 // API does not refcount and a single stop will counter multiple starts.
1298 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001299 for (FeatureUser x : mFeatureUsers) {
1300 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001301 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001302 return 1;
1303 }
1304 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001305 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001306
repo syncaea743a2011-07-29 23:55:49 -07001307 // TODO - move to individual network trackers
1308 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1309
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001310 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001311 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001312 if (DBG) {
1313 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1314 " no known tracker for used net type " + usedNetworkType);
1315 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001316 return -1;
1317 }
1318 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001319 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001320 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001321
1322 final long token = Binder.clearCallingIdentity();
1323 try {
1324 reassessPidDns(pid, true);
1325 } finally {
1326 Binder.restoreCallingIdentity(token);
1327 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001328 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001329 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001330 if (VDBG) {
1331 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1332 " others still using it");
1333 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001334 return 1;
1335 }
1336 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001337 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001338 if (DBG) {
1339 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1340 " not a known feature - dropping");
1341 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001342 }
1343 }
Wink Savillec9acde92011-09-21 11:05:43 -07001344
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001345 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001346 if (DBG) {
1347 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1348 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001349 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001350 return 1;
1351 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001352 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
1355
1356 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001357 * @deprecated use requestRouteToHostAddress instead
1358 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 * Ensure that a network route exists to deliver traffic to the specified
1360 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001361 * @param networkType the type of the network over which traffic to the
1362 * specified host is to be routed
1363 * @param hostAddress the IP address of the host to which the route is
1364 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 * @return {@code true} on success, {@code false} on failure
1366 */
1367 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001368 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1369
1370 if (inetAddress == null) {
1371 return false;
1372 }
1373
1374 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1375 }
1376
1377 /**
1378 * Ensure that a network route exists to deliver traffic to the specified
1379 * host via the specified network interface.
1380 * @param networkType the type of the network over which traffic to the
1381 * specified host is to be routed
1382 * @param hostAddress the IP address of the host to which the route is
1383 * desired
1384 * @return {@code true} on success, {@code false} on failure
1385 */
1386 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001388 if (mProtectedNetworks.contains(networkType)) {
1389 enforceConnectivityInternalPermission();
1390 }
1391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001393 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 return false;
1395 }
1396 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001397 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001398
Irfan Sheriffda6da092012-08-16 12:49:23 -07001399 if (tracker == null || (netState != DetailedState.CONNECTED &&
1400 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001401 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001402 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001403 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001404 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001405 }
1406 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001408 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001409 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001410 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001411 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001412 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001413 } catch (UnknownHostException e) {
1414 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1415 } finally {
1416 Binder.restoreCallingIdentity(token);
1417 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001418 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001419 }
1420
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001421 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001422 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001423 }
1424
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001425 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001426 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001427 }
1428
Robert Greenwaltad55d352011-07-22 11:55:33 -07001429 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001430 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001431 }
1432
1433 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001434 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001435 }
1436
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001437 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1438 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001439 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001440 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001441 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001442 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001443 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001444 if (bestRoute.getGateway().equals(addr)) {
1445 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001446 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001447 } else {
1448 // if we will connect to this through another route, add a direct route
1449 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001450 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001451 }
1452 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001453 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001454 }
1455
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001456 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1457 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001458 if ((lp == null) || (r == null)) {
1459 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001460 return false;
1461 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001462
1463 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001464 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001465 return false;
1466 }
1467
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001468 String ifaceName = r.getInterface();
1469 if(ifaceName == null) {
1470 loge("Error modifying route - no interface name");
1471 return false;
1472 }
1473
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001474 if (r.isHostRoute() == false) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001475 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001476 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001477 if (bestRoute.getGateway().equals(r.getGateway())) {
1478 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001479 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001480 } else {
1481 // if we will connect to our gateway through another route, add a direct
1482 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001483 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1484 bestRoute.getGateway(),
1485 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001486 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001487 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001488 }
1489 }
1490 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001491 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001492 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001493 if (toDefaultTable) {
1494 mAddedRoutes.add(r); // only track default table - only one apps can effect
1495 mNetd.addRoute(ifaceName, r);
1496 } else {
1497 mNetd.addSecondaryRoute(ifaceName, r);
1498 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001499 } catch (Exception e) {
1500 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001501 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001502 return false;
1503 }
1504 } else {
1505 // if we remove this one and there are no more like it, then refcount==0 and
1506 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001507 if (toDefaultTable) {
1508 mAddedRoutes.remove(r);
1509 if (mAddedRoutes.contains(r) == false) {
1510 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1511 try {
1512 mNetd.removeRoute(ifaceName, r);
1513 } catch (Exception e) {
1514 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001515 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001516 return false;
1517 }
1518 } else {
1519 if (VDBG) log("not removing " + r + " as it's still in use");
1520 }
1521 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001522 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001523 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001524 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001525 } catch (Exception e) {
1526 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001527 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001528 return false;
1529 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001530 }
1531 }
1532 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534
1535 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001536 * @see ConnectivityManager#getMobileDataEnabled()
1537 */
1538 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001539 // TODO: This detail should probably be in DataConnectionTracker's
1540 // which is where we store the value and maybe make this
1541 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001542 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001543 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1544 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001545 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001546 return retVal;
1547 }
1548
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001549 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001550 enforceConnectivityInternalPermission();
1551
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001552 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1553 (met ? ENABLED : DISABLED), networkType));
1554 }
1555
1556 private void handleSetDependencyMet(int networkType, boolean met) {
1557 if (mNetTrackers[networkType] != null) {
1558 if (DBG) {
1559 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1560 }
1561 mNetTrackers[networkType].setDependencyMet(met);
1562 }
1563 }
1564
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001565 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1566 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001567 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001568 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001569 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001570 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001571 }
1572
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001573 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001574 // skip update when we've already applied rules
1575 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1576 if (oldRules == uidRules) return;
1577
1578 mUidRules.put(uid, uidRules);
1579 }
1580
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001581 // TODO: notify UID when it has requested targeted updates
1582 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001583
1584 @Override
1585 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001586 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001587 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001588 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001589 }
1590
1591 synchronized (mRulesLock) {
1592 mMeteredIfaces.clear();
1593 for (String iface : meteredIfaces) {
1594 mMeteredIfaces.add(iface);
1595 }
1596 }
1597 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001598
1599 @Override
1600 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1601 // caller is NPMS, since we only register with them
1602 if (LOGD_RULES) {
1603 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1604 }
1605
1606 // kick off connectivity change broadcast for active network, since
1607 // global background policy change is radical.
1608 final int networkType = mActiveDefaultNetwork;
1609 if (isNetworkTypeValid(networkType)) {
1610 final NetworkStateTracker tracker = mNetTrackers[networkType];
1611 if (tracker != null) {
1612 final NetworkInfo info = tracker.getNetworkInfo();
1613 if (info != null && info.isConnected()) {
1614 sendConnectedBroadcast(info);
1615 }
1616 }
1617 }
1618 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001619 };
1620
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001621 /**
1622 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1623 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001624 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001625 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001626 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001627
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001628 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001629 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001630 }
1631
1632 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001633 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001634 if (VDBG) {
1635 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001636 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001637 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1638 }
tk.munb97d34c2012-01-06 10:43:52 +09001639 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1640 if (VDBG) {
1641 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1642 }
1643 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1644 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001645 }
1646
1647 @Override
1648 public void setPolicyDataEnable(int networkType, boolean enabled) {
1649 // only someone like NPMS should only be calling us
1650 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1651
1652 mHandler.sendMessage(mHandler.obtainMessage(
1653 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1654 }
1655
1656 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1657 if (isNetworkTypeValid(networkType)) {
1658 final NetworkStateTracker tracker = mNetTrackers[networkType];
1659 if (tracker != null) {
1660 tracker.setPolicyDataEnable(enabled);
1661 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001662 }
1663 }
1664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001666 mContext.enforceCallingOrSelfPermission(
1667 android.Manifest.permission.ACCESS_NETWORK_STATE,
1668 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670
1671 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001672 mContext.enforceCallingOrSelfPermission(
1673 android.Manifest.permission.CHANGE_NETWORK_STATE,
1674 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
1676
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001677 // TODO Make this a special check when it goes public
1678 private void enforceTetherChangePermission() {
1679 mContext.enforceCallingOrSelfPermission(
1680 android.Manifest.permission.CHANGE_NETWORK_STATE,
1681 "ConnectivityService");
1682 }
1683
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001684 private void enforceTetherAccessPermission() {
1685 mContext.enforceCallingOrSelfPermission(
1686 android.Manifest.permission.ACCESS_NETWORK_STATE,
1687 "ConnectivityService");
1688 }
1689
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001690 private void enforceConnectivityInternalPermission() {
1691 mContext.enforceCallingOrSelfPermission(
1692 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1693 "ConnectivityService");
1694 }
1695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001697 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1698 * network, we ignore it. If it is for the active network, we send out a
1699 * broadcast. But first, we check whether it might be possible to connect
1700 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 * @param info the {@code NetworkInfo} for the network
1702 */
1703 private void handleDisconnect(NetworkInfo info) {
1704
Robert Greenwalt42acef32009-08-12 16:08:25 -07001705 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706
Robert Greenwalt42acef32009-08-12 16:08:25 -07001707 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001708
1709 // Remove idletimer previously setup in {@code handleConnect}
1710 removeDataActivityTracking(prevNetType);
1711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 /*
1713 * If the disconnected network is not the active one, then don't report
1714 * this as a loss of connectivity. What probably happened is that we're
1715 * getting the disconnect for a network that we explicitly disabled
1716 * in accordance with network preference policies.
1717 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001718 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001719 List<Integer> pids = mNetRequestersPids[prevNetType];
1720 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001721 // will remove them because the net's no longer connected
1722 // need to do this now as only now do we know the pids and
1723 // can properly null things that are no longer referenced.
1724 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001729 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001730 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 if (info.isFailover()) {
1732 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1733 info.setFailover(false);
1734 }
1735 if (info.getReason() != null) {
1736 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1737 }
1738 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001739 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1740 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001742
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001743 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001744 tryFailover(prevNetType);
1745 if (mActiveDefaultNetwork != -1) {
1746 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001747 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1748 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001749 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001750 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1751 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001752 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001753 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001754
1755 // Reset interface if no other connections are using the same interface
1756 boolean doReset = true;
1757 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1758 if (linkProperties != null) {
1759 String oldIface = linkProperties.getInterfaceName();
1760 if (TextUtils.isEmpty(oldIface) == false) {
1761 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1762 if (networkStateTracker == null) continue;
1763 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1764 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1765 LinkProperties l = networkStateTracker.getLinkProperties();
1766 if (l == null) continue;
1767 if (oldIface.equals(l.getInterfaceName())) {
1768 doReset = false;
1769 break;
1770 }
1771 }
1772 }
1773 }
1774 }
1775
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001776 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001777 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001778
Jeff Sharkey961e3042011-08-29 16:02:57 -07001779 final Intent immediateIntent = new Intent(intent);
1780 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1781 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001782 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001783 /*
1784 * If the failover network is already connected, then immediately send
1785 * out a followup broadcast indicating successful failover
1786 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001787 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001788 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1789 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001790 }
1791 }
1792
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001793 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001794 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001795 * If this is a default network, check if other defaults are available.
1796 * Try to reconnect on all available and let them hash it out when
1797 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001799 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001800 if (mActiveDefaultNetwork == prevNetType) {
1801 mActiveDefaultNetwork = -1;
1802 }
1803
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001804 // don't signal a reconnect for anything lower or equal priority than our
1805 // current connected default
1806 // TODO - don't filter by priority now - nice optimization but risky
1807// int currentPriority = -1;
1808// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001809// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001810// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001811 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001812 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001813 if (mNetConfigs[checkType] == null) continue;
1814 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001815 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001816
1817// Enabling the isAvailable() optimization caused mobile to not get
1818// selected if it was in the middle of error handling. Specifically
1819// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1820// would not be available and we wouldn't get connected to anything.
1821// So removing the isAvailable() optimization below for now. TODO: This
1822// optimization should work and we need to investigate why it doesn't work.
1823// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1824// complete before it is really complete.
1825// if (!mNetTrackers[checkType].isAvailable()) continue;
1826
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001827// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001828
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001829 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1830 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1831 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1832 checkInfo.setFailover(true);
1833 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001834 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001835 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001840 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001841 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001842 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1843 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001844 }
1845
Wink Saville628b0852011-08-04 15:01:58 -07001846 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001847 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1848 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001849 }
1850
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001851 private void sendInetConditionBroadcast(NetworkInfo info) {
1852 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1853 }
1854
Wink Saville628b0852011-08-04 15:01:58 -07001855 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001856 if (mLockdownTracker != null) {
1857 info = mLockdownTracker.augmentNetworkInfo(info);
1858 }
1859
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001860 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001861 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001862 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 if (info.isFailover()) {
1864 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1865 info.setFailover(false);
1866 }
1867 if (info.getReason() != null) {
1868 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1869 }
1870 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001871 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1872 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001874 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001875 return intent;
1876 }
1877
1878 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1879 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1880 }
1881
1882 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1883 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885
Haoyu Baidb3c8672012-06-20 14:29:57 -07001886 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1887 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1888 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1889 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001890 final long ident = Binder.clearCallingIdentity();
1891 try {
1892 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1893 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1894 } finally {
1895 Binder.restoreCallingIdentity(ident);
1896 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001897 }
1898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 /**
1900 * Called when an attempt to fail over to another network has failed.
1901 * @param info the {@link NetworkInfo} for the failed network
1902 */
1903 private void handleConnectionFailure(NetworkInfo info) {
1904 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905
Robert Greenwalt42acef32009-08-12 16:08:25 -07001906 String reason = info.getReason();
1907 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001908
Robert Greenwalt572172b2010-10-08 16:35:52 -07001909 String reasonText;
1910 if (reason == null) {
1911 reasonText = ".";
1912 } else {
1913 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001915 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001916
1917 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001918 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001919 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001920 if (getActiveNetworkInfo() == null) {
1921 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1922 }
1923 if (reason != null) {
1924 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1925 }
1926 if (extraInfo != null) {
1927 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1928 }
1929 if (info.isFailover()) {
1930 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1931 info.setFailover(false);
1932 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001933
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001934 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001935 tryFailover(info.getType());
1936 if (mActiveDefaultNetwork != -1) {
1937 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001938 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1939 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001940 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001941 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1942 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001943 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001944
Robert Greenwalt029be812010-09-20 18:01:43 -07001945 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001946
1947 final Intent immediateIntent = new Intent(intent);
1948 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1949 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001950 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001951 /*
1952 * If the failover network is already connected, then immediately send
1953 * out a followup broadcast indicating successful failover
1954 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001955 if (mActiveDefaultNetwork != -1) {
1956 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001957 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001958 }
1959
1960 private void sendStickyBroadcast(Intent intent) {
1961 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001962 if (!mSystemReady) {
1963 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001964 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001965 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001966 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001967 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001968 }
1969
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001970 final long ident = Binder.clearCallingIdentity();
1971 try {
1972 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1973 } finally {
1974 Binder.restoreCallingIdentity(ident);
1975 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001976 }
1977 }
1978
Wink Saville628b0852011-08-04 15:01:58 -07001979 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1980 if (delayMs <= 0) {
1981 sendStickyBroadcast(intent);
1982 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001983 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001984 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1985 + intent.getAction());
1986 }
Wink Saville628b0852011-08-04 15:01:58 -07001987 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1988 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1989 }
1990 }
1991
Mike Lockwood0f79b542009-08-14 14:18:49 -04001992 void systemReady() {
1993 synchronized(this) {
1994 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001995 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001996 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001997 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001998 }
1999 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002000 // load the global proxy at startup
2001 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002002
2003 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2004 // for user to unlock device.
2005 if (!updateLockdownVpn()) {
2006 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2007 mContext.registerReceiver(mUserPresentReceiver, filter);
2008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002011 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2012 @Override
2013 public void onReceive(Context context, Intent intent) {
2014 // Try creating lockdown tracker, since user present usually means
2015 // unlocked keystore.
2016 if (updateLockdownVpn()) {
2017 mContext.unregisterReceiver(this);
2018 }
2019 }
2020 };
2021
Irfan Sheriffda6da092012-08-16 12:49:23 -07002022 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2023 if ((type != mNetworkPreference &&
2024 mNetConfigs[mActiveDefaultNetwork].priority >
2025 mNetConfigs[type].priority) ||
2026 mNetworkPreference == mActiveDefaultNetwork) return false;
2027 return true;
2028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029
Irfan Sheriffda6da092012-08-16 12:49:23 -07002030 private void handleConnect(NetworkInfo info) {
2031 final int newNetType = info.getType();
2032
2033 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 // snapshot isFailover, because sendConnectedBroadcast() resets it
2036 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002037 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002038 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039
Robert Greenwalt42acef32009-08-12 16:08:25 -07002040 // if this is a default net and other default is running
2041 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002042 if (mNetConfigs[newNetType].isDefault()) {
2043 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2044 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002045 // tear down the other
2046 NetworkStateTracker otherNet =
2047 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002048 if (DBG) {
2049 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002050 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002051 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002052 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002053 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002054 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002055 return;
2056 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002057 } else {
2058 // don't accept this one
2059 if (VDBG) {
2060 log("Not broadcasting CONNECT_ACTION " +
2061 "to torn down network " + info.getTypeName());
2062 }
2063 teardown(thisNet);
2064 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002065 }
2066 }
2067 synchronized (ConnectivityService.this) {
2068 // have a new default network, release the transition wakelock in a second
2069 // if it's held. The second pause is to allow apps to reconnect over the
2070 // new network
2071 if (mNetTransitionWakeLock.isHeld()) {
2072 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002073 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002074 mNetTransitionWakeLockSerialNumber, 0),
2075 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002076 }
2077 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002078 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002079 // this will cause us to come up initially as unconnected and switching
2080 // to connected after our normal pause unless somebody reports us as reall
2081 // disconnected
2082 mDefaultInetConditionPublished = 0;
2083 mDefaultConnectionSequence++;
2084 mInetConditionChangeInFlight = false;
2085 // Don't do this - if we never sign in stay, grey
2086 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002089 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002090 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002091 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002092
2093 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002094 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002095 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002096 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002097 } catch (RemoteException e) {
2098 // ignored; service lives in system_server
2099 }
2100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102
Irfan Sheriffda6da092012-08-16 12:49:23 -07002103 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2104 if (DBG) log("Captive portal check " + info);
2105 int type = info.getType();
2106 final NetworkStateTracker thisNet = mNetTrackers[type];
2107 if (mNetConfigs[type].isDefault()) {
2108 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2109 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2110 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002111 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002112 return;
2113 } else {
2114 if (DBG) log("Tear down low priority net " + info.getTypeName());
2115 teardown(thisNet);
2116 return;
2117 }
2118 }
2119 }
2120
2121 thisNet.captivePortalCheckComplete();
2122 }
2123
2124 /** @hide */
2125 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002126 enforceConnectivityInternalPermission();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002127 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002128 }
2129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002131 * Setup data activity tracking for the given network interface.
2132 *
2133 * Every {@code setupDataActivityTracking} should be paired with a
2134 * {@link removeDataActivityTracking} for cleanup.
2135 */
2136 private void setupDataActivityTracking(int type) {
2137 final NetworkStateTracker thisNet = mNetTrackers[type];
2138 final String iface = thisNet.getLinkProperties().getInterfaceName();
2139
2140 final int timeout;
2141
2142 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002143 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2144 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002145 0);
2146 // Canonicalize mobile network type
2147 type = ConnectivityManager.TYPE_MOBILE;
2148 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002149 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2150 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002151 0);
2152 } else {
2153 // do not track any other networks
2154 timeout = 0;
2155 }
2156
2157 if (timeout > 0 && iface != null) {
2158 try {
2159 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2160 } catch (RemoteException e) {
2161 }
2162 }
2163 }
2164
2165 /**
2166 * Remove data activity tracking when network disconnects.
2167 */
2168 private void removeDataActivityTracking(int type) {
2169 final NetworkStateTracker net = mNetTrackers[type];
2170 final String iface = net.getLinkProperties().getInterfaceName();
2171
2172 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2173 ConnectivityManager.TYPE_WIFI == type)) {
2174 try {
2175 // the call fails silently if no idletimer setup for this interface
2176 mNetd.removeIdleTimer(iface);
2177 } catch (RemoteException e) {
2178 }
2179 }
2180 }
2181
2182 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002183 * After a change in the connectivity state of a network. We're mainly
2184 * concerned with making sure that the list of DNS servers is set up
2185 * according to which networks are connected, and ensuring that the
2186 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002188 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002189 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002192 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002193 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002195 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002196
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002197 LinkProperties curLp = mCurrentLinkProperties[netType];
2198 LinkProperties newLp = null;
2199
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002200 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002201 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002202 if (VDBG) {
2203 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2204 " doReset=" + doReset + " resetMask=" + resetMask +
2205 "\n curLp=" + curLp +
2206 "\n newLp=" + newLp);
2207 }
2208
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002209 if (curLp != null) {
2210 if (curLp.isIdenticalInterfaceName(newLp)) {
2211 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2212 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2213 for (LinkAddress linkAddr : car.removed) {
2214 if (linkAddr.getAddress() instanceof Inet4Address) {
2215 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2216 }
2217 if (linkAddr.getAddress() instanceof Inet6Address) {
2218 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2219 }
Wink Savillee8222252011-07-13 13:44:13 -07002220 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002221 if (DBG) {
2222 log("handleConnectivityChange: addresses changed" +
2223 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2224 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002225 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002226 } else {
2227 if (DBG) {
2228 log("handleConnectivityChange: address are the same reset per doReset" +
2229 " linkProperty[" + netType + "]:" +
2230 " resetMask=" + resetMask);
2231 }
Wink Savillee8222252011-07-13 13:44:13 -07002232 }
2233 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002234 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002235 if (DBG) {
2236 log("handleConnectivityChange: interface not not equivalent reset both" +
2237 " linkProperty[" + netType + "]:" +
2238 " resetMask=" + resetMask);
2239 }
Wink Savillee8222252011-07-13 13:44:13 -07002240 }
Wink Savillee8222252011-07-13 13:44:13 -07002241 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002242 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002243 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002244 }
2245 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002246 if (VDBG) {
2247 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2248 " doReset=" + doReset + " resetMask=" + resetMask +
2249 "\n curLp=" + curLp +
2250 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002253 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002254 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002255
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002256 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07002257 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2258 if (linkProperties != null) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002259 for (String iface : linkProperties.getAllInterfaceNames()) {
2260 if (TextUtils.isEmpty(iface) == false) {
2261 if (resetMask != 0) {
2262 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2263 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002264
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002265 // Tell VPN the interface is down. It is a temporary
2266 // but effective fix to make VPN aware of the change.
2267 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2268 mVpn.interfaceStatusChanged(iface, false);
2269 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002270 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002271 if (resetDns) {
2272 flushVmDnsCache();
2273 if (VDBG) log("resetting DNS cache for " + iface);
2274 try {
2275 mNetd.flushInterfaceDnsCache(iface);
2276 } catch (Exception e) {
2277 // never crash - catch them all
2278 if (DBG) loge("Exception resetting dns cache: " + e);
2279 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002280 }
2281 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002282 }
2283 }
2284 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002285
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002286 // Update 464xlat state.
2287 // TODO: Move to handleConnect()
2288 NetworkStateTracker tracker = mNetTrackers[netType];
2289 if (mClat.requiresClat(netType, tracker)) {
2290 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2291 mClat.startClat(tracker);
2292 } else {
2293 mClat.stopClat();
2294 }
2295 }
2296
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002297 // TODO: Temporary notifying upstread change to Tethering.
2298 // @see bug/4455071
2299 /** Notify TetheringService if interface name has been changed. */
2300 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002301 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002302 if (isTetheringSupported()) {
2303 mTethering.handleTetherIfaceChange();
2304 }
2305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002308 /**
2309 * Add and remove routes using the old properties (null if not previously connected),
2310 * new properties (null if becoming disconnected). May even be double null, which
2311 * is a noop.
2312 * Uses isLinkDefault to determine if default routes should be set or conversely if
2313 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002314 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002315 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002316 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2317 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002318 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002319 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2320 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002321 if (curLp != null) {
2322 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002323 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002324 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002325 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002326 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002327 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002328 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002329
Robert Greenwaltf125a092011-08-15 12:31:55 -07002330 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2331
Robert Greenwaltad55d352011-07-22 11:55:33 -07002332 for (RouteInfo r : routeDiff.removed) {
2333 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002334 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2335 }
2336 if (isLinkDefault == false) {
2337 // remove from a secondary route table
2338 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002339 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002340 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002341
Robert Greenwaltad55d352011-07-22 11:55:33 -07002342 for (RouteInfo r : routeDiff.added) {
2343 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002344 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002345 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002346 // add to a secondary route table
2347 addRoute(newLp, r, TO_SECONDARY_TABLE);
2348
Robert Greenwalte6b24292011-08-09 16:52:58 -07002349 // many radios add a default route even when we don't want one.
2350 // remove the default route unless somebody else has asked for it
2351 String ifaceName = newLp.getInterfaceName();
2352 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002353 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002354 try {
2355 mNetd.removeRoute(ifaceName, r);
2356 } catch (Exception e) {
2357 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08002358 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002359 }
2360 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002361 }
2362 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002363
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002364 if (!isLinkDefault) {
2365 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002366 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002367 // routes changed - remove all old dns entries and add new
2368 if (curLp != null) {
2369 for (InetAddress oldDns : curLp.getDnses()) {
2370 removeRouteToAddress(curLp, oldDns);
2371 }
2372 }
2373 if (newLp != null) {
2374 for (InetAddress newDns : newLp.getDnses()) {
2375 addRouteToAddress(newLp, newDns);
2376 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002377 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002378 } else {
2379 // no change in routes, check for change in dns themselves
2380 for (InetAddress oldDns : dnsDiff.removed) {
2381 removeRouteToAddress(curLp, oldDns);
2382 }
2383 for (InetAddress newDns : dnsDiff.added) {
2384 addRouteToAddress(newLp, newDns);
2385 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002386 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002387 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002388 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002389 }
2390
2391
Irfan Sheriffd649c122010-06-09 15:39:36 -07002392 /**
2393 * Reads the network specific TCP buffer sizes from SystemProperties
2394 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2395 * wide use
2396 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002397 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002398 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002399 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002400
Jeff Sharkey899223b2012-08-04 15:24:58 -07002401 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002402 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002403
2404 // Setting to default values so we won't be stuck to previous values
2405 key = "net.tcp.buffersize.default";
2406 bufferSizes = SystemProperties.get(key);
2407 }
2408
2409 // Set values in kernel
2410 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002411 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002412 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002413 + "] which comes from [" + key + "]");
2414 }
2415 setBufferSize(bufferSizes);
2416 }
2417 }
2418
2419 /**
2420 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2421 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2422 *
2423 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2424 * writeMin, writeInitial, writeMax"
2425 */
2426 private void setBufferSize(String bufferSizes) {
2427 try {
2428 String[] values = bufferSizes.split(",");
2429
2430 if (values.length == 6) {
2431 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002432 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2433 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2434 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2435 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2436 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2437 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002438 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002439 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002440 }
2441 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002442 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002443 }
2444 }
2445
Robert Greenwalt42acef32009-08-12 16:08:25 -07002446 /**
2447 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2448 * on the highest priority active net which this process requested.
2449 * If there aren't any, clear it out
2450 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002451 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002452 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002453 if (VDBG) log("reassessPidDns for pid " + pid);
2454 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002455 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002456 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002457 continue;
2458 }
2459 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002460 if (nt.getNetworkInfo().isConnected() &&
2461 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002462 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002463 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002464 if (mNetRequestersPids[i].contains(myPid)) {
2465 try {
2466 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2467 } catch (Exception e) {
2468 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002469 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002470 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002471 }
2472 }
2473 }
2474 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002475 try {
2476 mNetd.clearDnsInterfaceForPid(pid);
2477 } catch (Exception e) {
2478 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002479 }
2480 }
2481
Mattias Falk8b47b362011-08-23 14:15:13 +02002482 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002483 /*
2484 * Tell the VMs to toss their DNS caches
2485 */
2486 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2487 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002488 /*
2489 * Connectivity events can happen before boot has completed ...
2490 */
2491 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002492 final long ident = Binder.clearCallingIdentity();
2493 try {
2494 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2495 } finally {
2496 Binder.restoreCallingIdentity(ident);
2497 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002498 }
2499
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002500 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002501 private void updateDnsLocked(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002502 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002503 int last = 0;
2504 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002505 dnses = new ArrayList();
2506 dnses.add(mDefaultDns);
2507 if (DBG) {
2508 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002509 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002510 }
2511
Mattias Falk8b47b362011-08-23 14:15:13 +02002512 try {
2513 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2514 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002515 for (InetAddress dns : dnses) {
2516 ++last;
2517 String key = "net.dns" + last;
2518 String value = dns.getHostAddress();
2519 SystemProperties.set(key, value);
2520 }
2521 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2522 String key = "net.dns" + i;
2523 SystemProperties.set(key, "");
2524 }
2525 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002526 } catch (Exception e) {
2527 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002528 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002529 }
2530
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002531 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002532 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002533 NetworkStateTracker nt = mNetTrackers[netType];
2534 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002535 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002536 if (p == null) return;
2537 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002538 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002539 String network = nt.getNetworkInfo().getTypeName();
2540 synchronized (mDnsLock) {
2541 if (!mDnsOverridden) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002542 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002543 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002544 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002545 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002546 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002547 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002548 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002549 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002550 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002551 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002552 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002553 List<Integer> pids = mNetRequestersPids[netType];
2554 for (Integer pid : pids) {
2555 try {
2556 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2557 } catch (Exception e) {
2558 Slog.e(TAG, "exception setting interface for pid: " + e);
2559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 }
2561 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002562 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002564 }
2565
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002566 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002567 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2568 NETWORK_RESTORE_DELAY_PROP_NAME);
2569 if(restoreDefaultNetworkDelayStr != null &&
2570 restoreDefaultNetworkDelayStr.length() != 0) {
2571 try {
2572 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2573 } catch (NumberFormatException e) {
2574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002576 // if the system property isn't set, use the value for the apn type
2577 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2578
2579 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2580 (mNetConfigs[networkType] != null)) {
2581 ret = mNetConfigs[networkType].restoreTime;
2582 }
2583 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585
2586 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002587 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2588 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002589 if (mContext.checkCallingOrSelfPermission(
2590 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002592 pw.println("Permission Denial: can't dump ConnectivityService " +
2593 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2594 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 return;
2596 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002597
2598 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002600 for (int i = 0; i < mNetTrackers.length; i++) {
2601 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002602 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002603 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2604 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002605 if (nst.getNetworkInfo().isConnected()) {
2606 pw.println("Active network: " + nst.getNetworkInfo().
2607 getTypeName());
2608 }
2609 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002610 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002611 pw.println(nst);
2612 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002613 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002616
2617 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002618 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002619 for (int net : mPriorityList) {
2620 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002621 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002622 pidString = pidString + pid.toString() + ", ";
2623 }
2624 pw.println(pidString);
2625 }
2626 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002627 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002628
2629 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002630 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002631 for (Object requester : mFeatureUsers) {
2632 pw.println(requester.toString());
2633 }
2634 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002635 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002636
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002637 synchronized (this) {
2638 pw.println("NetworkTranstionWakeLock is currently " +
2639 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2640 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2641 }
2642 pw.println();
2643
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002644 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002645
2646 if (mInetLog != null) {
2647 pw.println();
2648 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002649 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002650 for(int i = 0; i < mInetLog.size(); i++) {
2651 pw.println(mInetLog.get(i));
2652 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002653 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 }
2656
Robert Greenwalt42acef32009-08-12 16:08:25 -07002657 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002658 private class NetworkStateTrackerHandler extends Handler {
2659 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002660 super(looper);
2661 }
2662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 @Override
2664 public void handleMessage(Message msg) {
2665 NetworkInfo info;
2666 switch (msg.what) {
2667 case NetworkStateTracker.EVENT_STATE_CHANGED:
2668 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002669 int type = info.getType();
2670 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002671
Wink Savillec9acde92011-09-21 11:05:43 -07002672 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2673 (state == NetworkInfo.State.DISCONNECTED)) {
2674 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002675 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002676 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678
Jeff Sharkey2528b502012-11-09 15:57:02 -08002679 EventLogTags.writeConnectivityStateChanged(
2680 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002681
2682 if (info.getDetailedState() ==
2683 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002685 } else if (info.getDetailedState() ==
2686 DetailedState.CAPTIVE_PORTAL_CHECK) {
2687 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002688 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002690 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002692 // the logic here is, handle SUSPENDED the same as
2693 // DISCONNECTED. The only difference being we are
2694 // broadcasting an intent with NetworkInfo that's
2695 // suspended. This allows the applications an
2696 // opportunity to handle DISCONNECTED and SUSPENDED
2697 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002699 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 handleConnect(info);
2701 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002702 if (mLockdownTracker != null) {
2703 mLockdownTracker.onNetworkInfoChanged(info);
2704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002707 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002708 // TODO: Temporary allowing network configuration
2709 // change not resetting sockets.
2710 // @see bug/4455071
2711 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002713 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2714 info = (NetworkInfo) msg.obj;
2715 type = info.getType();
2716 updateNetworkSettings(mNetTrackers[type]);
2717 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002718 }
2719 }
2720 }
2721
2722 private class InternalHandler extends Handler {
2723 public InternalHandler(Looper looper) {
2724 super(looper);
2725 }
2726
2727 @Override
2728 public void handleMessage(Message msg) {
2729 NetworkInfo info;
2730 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002731 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002732 String causedBy = null;
2733 synchronized (ConnectivityService.this) {
2734 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2735 mNetTransitionWakeLock.isHeld()) {
2736 mNetTransitionWakeLock.release();
2737 causedBy = mNetTransitionWakeLockCausedBy;
2738 }
2739 }
2740 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002741 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002742 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002743 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002744 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002745 FeatureUser u = (FeatureUser)msg.obj;
2746 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002747 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002748 case EVENT_INET_CONDITION_CHANGE:
2749 {
2750 int netType = msg.arg1;
2751 int condition = msg.arg2;
2752 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002753 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002754 }
2755 case EVENT_INET_CONDITION_HOLD_END:
2756 {
2757 int netType = msg.arg1;
2758 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002759 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002760 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002761 }
2762 case EVENT_SET_NETWORK_PREFERENCE:
2763 {
2764 int preference = msg.arg1;
2765 handleSetNetworkPreference(preference);
2766 break;
2767 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002768 case EVENT_SET_MOBILE_DATA:
2769 {
2770 boolean enabled = (msg.arg1 == ENABLED);
2771 handleSetMobileData(enabled);
2772 break;
2773 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002774 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2775 {
2776 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002777 break;
2778 }
2779 case EVENT_SET_DEPENDENCY_MET:
2780 {
2781 boolean met = (msg.arg1 == ENABLED);
2782 handleSetDependencyMet(msg.arg2, met);
2783 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002784 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002785 case EVENT_RESTORE_DNS:
2786 {
2787 if (mActiveDefaultNetwork != -1) {
2788 handleDnsConfigurationChange(mActiveDefaultNetwork);
2789 }
2790 break;
2791 }
Wink Saville628b0852011-08-04 15:01:58 -07002792 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2793 {
2794 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002795 sendStickyBroadcast(intent);
2796 break;
2797 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002798 case EVENT_SET_POLICY_DATA_ENABLE: {
2799 final int networkType = msg.arg1;
2800 final boolean enabled = msg.arg2 == ENABLED;
2801 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002802 break;
2803 }
2804 case EVENT_VPN_STATE_CHANGED: {
2805 if (mLockdownTracker != null) {
2806 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2807 }
2808 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 }
2811 }
2812 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002813
2814 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002815 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002816 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002817
2818 if (isTetheringSupported()) {
2819 return mTethering.tether(iface);
2820 } else {
2821 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2822 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002823 }
2824
2825 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002826 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002827 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002828
2829 if (isTetheringSupported()) {
2830 return mTethering.untether(iface);
2831 } else {
2832 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2833 }
2834 }
2835
2836 // javadoc from interface
2837 public int getLastTetherError(String iface) {
2838 enforceTetherAccessPermission();
2839
2840 if (isTetheringSupported()) {
2841 return mTethering.getLastTetherError(iface);
2842 } else {
2843 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2844 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002845 }
2846
2847 // TODO - proper iface API for selection by property, inspection, etc
2848 public String[] getTetherableUsbRegexs() {
2849 enforceTetherAccessPermission();
2850 if (isTetheringSupported()) {
2851 return mTethering.getTetherableUsbRegexs();
2852 } else {
2853 return new String[0];
2854 }
2855 }
2856
2857 public String[] getTetherableWifiRegexs() {
2858 enforceTetherAccessPermission();
2859 if (isTetheringSupported()) {
2860 return mTethering.getTetherableWifiRegexs();
2861 } else {
2862 return new String[0];
2863 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002864 }
2865
Danica Chang6fdd0c62010-08-11 14:54:43 -07002866 public String[] getTetherableBluetoothRegexs() {
2867 enforceTetherAccessPermission();
2868 if (isTetheringSupported()) {
2869 return mTethering.getTetherableBluetoothRegexs();
2870 } else {
2871 return new String[0];
2872 }
2873 }
2874
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002875 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002876 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002877 if (isTetheringSupported()) {
2878 return mTethering.setUsbTethering(enable);
2879 } else {
2880 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2881 }
2882 }
2883
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002884 // TODO - move iface listing, queries, etc to new module
2885 // javadoc from interface
2886 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002887 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002888 return mTethering.getTetherableIfaces();
2889 }
2890
2891 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002892 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002893 return mTethering.getTetheredIfaces();
2894 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002895
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002896 @Override
2897 public String[] getTetheredIfacePairs() {
2898 enforceTetherAccessPermission();
2899 return mTethering.getTetheredIfacePairs();
2900 }
2901
Robert Greenwalt5a735062010-03-02 17:25:02 -08002902 public String[] getTetheringErroredIfaces() {
2903 enforceTetherAccessPermission();
2904 return mTethering.getErroredIfaces();
2905 }
2906
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002907 // if ro.tether.denied = true we default to no tethering
2908 // gservices could set the secure setting to 1 though to enable it on a build where it
2909 // had previously been turned off.
2910 public boolean isTetheringSupported() {
2911 enforceTetherAccessPermission();
2912 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002913 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2914 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002915 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002916 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002917
2918 // An API NetworkStateTrackers can call when they lose their network.
2919 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2920 // whichever happens first. The timer is started by the first caller and not
2921 // restarted by subsequent callers.
2922 public void requestNetworkTransitionWakelock(String forWhom) {
2923 enforceConnectivityInternalPermission();
2924 synchronized (this) {
2925 if (mNetTransitionWakeLock.isHeld()) return;
2926 mNetTransitionWakeLockSerialNumber++;
2927 mNetTransitionWakeLock.acquire();
2928 mNetTransitionWakeLockCausedBy = forWhom;
2929 }
2930 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002931 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002932 mNetTransitionWakeLockSerialNumber, 0),
2933 mNetTransitionWakeLockTimeout);
2934 return;
2935 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002936
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002937 // 100 percent is full good, 0 is full bad.
2938 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002939 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002940 mContext.enforceCallingOrSelfPermission(
2941 android.Manifest.permission.STATUS_BAR,
2942 "ConnectivityService");
2943
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002944 if (DBG) {
2945 int pid = getCallingPid();
2946 int uid = getCallingUid();
2947 String s = pid + "(" + uid + ") reports inet is " +
2948 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2949 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2950 mInetLog.add(s);
2951 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2952 mInetLog.remove(0);
2953 }
2954 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002955 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002956 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2957 }
2958
2959 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002960 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002961 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002962 return;
2963 }
2964 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002965 if (DBG) log("handleInetConditionChange: net=" + netType +
2966 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002967 return;
2968 }
Wink Savillec9acde92011-09-21 11:05:43 -07002969 if (VDBG) {
2970 log("handleInetConditionChange: net=" +
2971 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00002972 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07002973 }
Wink Saville5b7573e2013-01-31 00:30:13 +00002974 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002975 int delay;
2976 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002977 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002978 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00002979 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002980 delay = Settings.Global.getInt(mContext.getContentResolver(),
2981 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002982 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002983 delay = Settings.Global.getInt(mContext.getContentResolver(),
2984 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002985 }
2986 mInetConditionChangeInFlight = true;
2987 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00002988 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002989 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002990 // we've set the new condition, when this hold ends that will get picked up
2991 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002992 }
2993 }
2994
Wink Saville5b7573e2013-01-31 00:30:13 +00002995 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002996 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00002997 log("handleInetConditionHoldEnd: net=" + netType +
2998 ", condition=" + mDefaultInetCondition +
2999 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003000 }
3001 mInetConditionChangeInFlight = false;
3002
3003 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003004 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003005 return;
3006 }
3007 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003008 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003009 return;
3010 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003011 // TODO: Figure out why this optimization sometimes causes a
3012 // change in mDefaultInetCondition to be missed and the
3013 // UI to not be updated.
3014 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3015 // if (DBG) log("no change in condition - aborting");
3016 // return;
3017 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003018 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3019 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003020 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003021 return;
3022 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003023 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003024 sendInetConditionBroadcast(networkInfo);
3025 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003026 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003027
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003028 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003029 // this information is already available as a world read/writable jvm property
3030 // so this API change wouldn't have a benifit. It also breaks the passing
3031 // of proxy info to all the JVMs.
3032 // enforceAccessPermission();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003033 synchronized (mDefaultProxyLock) {
3034 return mDefaultProxyDisabled ? null : mDefaultProxy;
3035 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003036 }
3037
3038 public void setGlobalProxy(ProxyProperties proxyProperties) {
3039 enforceChangePermission();
3040 synchronized (mGlobalProxyLock) {
3041 if (proxyProperties == mGlobalProxy) return;
3042 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3043 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3044
3045 String host = "";
3046 int port = 0;
3047 String exclList = "";
3048 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3049 mGlobalProxy = new ProxyProperties(proxyProperties);
3050 host = mGlobalProxy.getHost();
3051 port = mGlobalProxy.getPort();
3052 exclList = mGlobalProxy.getExclusionList();
3053 } else {
3054 mGlobalProxy = null;
3055 }
3056 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003057 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3058 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3059 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07003060 exclList);
3061 }
3062
3063 if (mGlobalProxy == null) {
3064 proxyProperties = mDefaultProxy;
3065 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07003066 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003067 }
3068
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003069 private void loadGlobalProxy() {
3070 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003071 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3072 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3073 String exclList = Settings.Global.getString(res,
3074 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003075 if (!TextUtils.isEmpty(host)) {
3076 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3077 synchronized (mGlobalProxyLock) {
3078 mGlobalProxy = proxyProperties;
3079 }
3080 }
3081 }
3082
Robert Greenwalt434203a2010-10-11 16:00:27 -07003083 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003084 // this information is already available as a world read/writable jvm property
3085 // so this API change wouldn't have a benifit. It also breaks the passing
3086 // of proxy info to all the JVMs.
3087 // enforceAccessPermission();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003088 synchronized (mGlobalProxyLock) {
3089 return mGlobalProxy;
3090 }
3091 }
3092
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003093 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3094 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3095 proxy = null;
3096 }
3097 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003098 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3099 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003100 mDefaultProxy = proxy;
3101
3102 if (!mDefaultProxyDisabled) {
3103 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003104 }
3105 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003106 }
3107
3108 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003109 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3110 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003111 if (!TextUtils.isEmpty(proxy)) {
3112 String data[] = proxy.split(":");
3113 String proxyHost = data[0];
3114 int proxyPort = 8080;
3115 if (data.length > 1) {
3116 try {
3117 proxyPort = Integer.parseInt(data[1]);
3118 } catch (NumberFormatException e) {
3119 return;
3120 }
3121 }
3122 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3123 setGlobalProxy(p);
3124 }
3125 }
3126
3127 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003128 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003129 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003130 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003131 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3132 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003133 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003134 final long ident = Binder.clearCallingIdentity();
3135 try {
3136 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3137 } finally {
3138 Binder.restoreCallingIdentity(ident);
3139 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003140 }
3141
3142 private static class SettingsObserver extends ContentObserver {
3143 private int mWhat;
3144 private Handler mHandler;
3145 SettingsObserver(Handler handler, int what) {
3146 super(handler);
3147 mHandler = handler;
3148 mWhat = what;
3149 }
3150
3151 void observe(Context context) {
3152 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003153 resolver.registerContentObserver(Settings.Global.getUriFor(
3154 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003155 }
3156
3157 @Override
3158 public void onChange(boolean selfChange) {
3159 mHandler.obtainMessage(mWhat).sendToTarget();
3160 }
3161 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003162
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003163 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003164 Slog.d(TAG, s);
3165 }
3166
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003167 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003168 Slog.e(TAG, s);
3169 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003170
repo syncaea743a2011-07-29 23:55:49 -07003171 int convertFeatureToNetworkType(int networkType, String feature) {
3172 int usedNetworkType = networkType;
3173
3174 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3175 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3176 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3177 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3178 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3179 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3180 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3181 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3182 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3183 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3184 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3185 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3186 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3187 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3188 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3189 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3190 } else {
3191 Slog.e(TAG, "Can't match any mobile netTracker!");
3192 }
3193 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3194 if (TextUtils.equals(feature, "p2p")) {
3195 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3196 } else {
3197 Slog.e(TAG, "Can't match any wifi netTracker!");
3198 }
3199 } else {
3200 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003201 }
repo syncaea743a2011-07-29 23:55:49 -07003202 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003203 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003204
3205 private static <T> T checkNotNull(T value, String message) {
3206 if (value == null) {
3207 throw new NullPointerException(message);
3208 }
3209 return value;
3210 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003211
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003212 /**
3213 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003214 * VpnBuilder and not available in ConnectivityManager. Permissions
3215 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003216 * @hide
3217 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003218 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003219 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003220 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003221 try {
3222 int type = mActiveDefaultNetwork;
3223 if (ConnectivityManager.isNetworkTypeValid(type)) {
3224 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3225 return true;
3226 }
3227 } catch (Exception e) {
3228 // ignore
3229 } finally {
3230 try {
3231 socket.close();
3232 } catch (Exception e) {
3233 // ignore
3234 }
3235 }
3236 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003237 }
3238
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003239 /**
3240 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003241 * and not available in ConnectivityManager. Permissions are checked
3242 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003243 * @hide
3244 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003245 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003246 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003247 throwIfLockdownEnabled();
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003248 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003249 }
3250
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003251 /**
3252 * Configure a TUN interface and return its file descriptor. Parameters
3253 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003254 * and not available in ConnectivityManager. Permissions are checked in
3255 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003256 * @hide
3257 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003258 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003259 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003260 throwIfLockdownEnabled();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003261 return mVpn.establish(config);
3262 }
3263
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003264 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003265 * Start legacy VPN, controlling native daemons as needed. Creates a
3266 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003267 */
3268 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003269 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003270 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003271 final LinkProperties egress = getActiveLinkProperties();
3272 if (egress == null) {
3273 throw new IllegalStateException("Missing active network connection");
3274 }
3275 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003276 }
3277
3278 /**
3279 * Return the information of the ongoing legacy VPN. This method is used
3280 * by VpnSettings and not available in ConnectivityManager. Permissions
3281 * are checked in Vpn class.
3282 * @hide
3283 */
3284 @Override
3285 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003286 throwIfLockdownEnabled();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003287 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003288 }
3289
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003290 /**
3291 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3292 * through NetworkStateTracker since it works differently. For example, it
3293 * needs to override DNS servers but never takes the default routes. It
3294 * relies on another data network, and it could keep existing connections
3295 * alive after reconnecting, switching between networks, or even resuming
3296 * from deep sleep. Calls from applications should be done synchronously
3297 * to avoid race conditions. As these are all hidden APIs, refactoring can
3298 * be done whenever a better abstraction is developed.
3299 */
3300 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003301 private VpnCallback() {
3302 }
3303
Jeff Sharkey899223b2012-08-04 15:24:58 -07003304 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003305 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003306 }
3307
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003308 public void override(List<String> dnsServers, List<String> searchDomains) {
3309 if (dnsServers == null) {
3310 restore();
3311 return;
3312 }
3313
3314 // Convert DNS servers into addresses.
3315 List<InetAddress> addresses = new ArrayList<InetAddress>();
3316 for (String address : dnsServers) {
3317 // Double check the addresses and remove invalid ones.
3318 try {
3319 addresses.add(InetAddress.parseNumericAddress(address));
3320 } catch (Exception e) {
3321 // ignore
3322 }
3323 }
3324 if (addresses.isEmpty()) {
3325 restore();
3326 return;
3327 }
3328
3329 // Concatenate search domains into a string.
3330 StringBuilder buffer = new StringBuilder();
3331 if (searchDomains != null) {
3332 for (String domain : searchDomains) {
3333 buffer.append(domain).append(' ');
3334 }
3335 }
3336 String domains = buffer.toString().trim();
3337
3338 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003339 synchronized (mDnsLock) {
Mattias Falk8b47b362011-08-23 14:15:13 +02003340 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003341 mDnsOverridden = true;
3342 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003343
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003344 // Temporarily disable the default proxy.
3345 synchronized (mDefaultProxyLock) {
3346 mDefaultProxyDisabled = true;
3347 if (mDefaultProxy != null) {
3348 sendProxyBroadcast(null);
3349 }
3350 }
3351
3352 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003353 }
3354
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003355 public void restore() {
3356 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003357 if (mDnsOverridden) {
3358 mDnsOverridden = false;
3359 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003360 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003361 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003362 synchronized (mDefaultProxyLock) {
3363 mDefaultProxyDisabled = false;
3364 if (mDefaultProxy != null) {
3365 sendProxyBroadcast(mDefaultProxy);
3366 }
3367 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003368 }
3369 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003370
3371 @Override
3372 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003373 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3374 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3375 return false;
3376 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003377
3378 // Tear down existing lockdown if profile was removed
3379 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3380 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003381 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003382 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3383 return false;
3384 }
3385
3386 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3387 final VpnProfile profile = VpnProfile.decode(
3388 profileName, mKeyStore.get(Credentials.VPN + profileName));
3389 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3390 } else {
3391 setLockdownTracker(null);
3392 }
3393
3394 return true;
3395 }
3396
3397 /**
3398 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3399 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3400 */
3401 private void setLockdownTracker(LockdownVpnTracker tracker) {
3402 // Shutdown any existing tracker
3403 final LockdownVpnTracker existing = mLockdownTracker;
3404 mLockdownTracker = null;
3405 if (existing != null) {
3406 existing.shutdown();
3407 }
3408
3409 try {
3410 if (tracker != null) {
3411 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003412 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003413 mLockdownTracker = tracker;
3414 mLockdownTracker.init();
3415 } else {
3416 mNetd.setFirewallEnabled(false);
3417 }
3418 } catch (RemoteException e) {
3419 // ignored; NMS lives inside system_server
3420 }
3421 }
3422
3423 private void throwIfLockdownEnabled() {
3424 if (mLockdownEnabled) {
3425 throw new IllegalStateException("Unavailable in lockdown mode");
3426 }
3427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428}