blob: 3e19094bba71d056e8906982e4341113167046de [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;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070077import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070079import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070080import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070083import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070085import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070087import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070088import android.security.KeyStore;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080090import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Chia-chi Yeh2e467642011-07-04 03:23:12 -070093import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070094import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070095import com.android.internal.net.VpnProfile;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -070097import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -070098import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070099import com.android.server.am.BatteryStatsService;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900100import com.android.server.connectivity.Nat464Xlat;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800101import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700102import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700103import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700104import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700105import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700106import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700107
tk.mun148c7d02011-10-13 22:51:57 +0900108import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700111import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900113import java.lang.reflect.Constructor;
Wink Savillec9822c52011-07-14 12:23:28 -0700114import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700115import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700116import java.net.InetAddress;
117import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700118import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700119import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700120import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700121import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700122import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700123import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
125/**
126 * @hide
127 */
128public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700129 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130
Robert Greenwaltba175a52010-10-05 19:12:26 -0700131 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700132 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700134 private static final boolean LOGD_RULES = false;
135
Jeff Sharkey899223b2012-08-04 15:24:58 -0700136 // TODO: create better separation between radio types and network types
137
Robert Greenwalt42acef32009-08-12 16:08:25 -0700138 // how long to wait before switching back to a radio's default network
139 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
140 // system property that can override the above value
141 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
142 "android.telephony.apn-restore";
143
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700144 // used in recursive route setting to add gateways for the host for which
145 // a host route was requested.
146 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
147
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800148 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800149 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800150
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700151 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700152
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700153 private Vpn mVpn;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700154 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700155
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700156 private boolean mLockdownEnabled;
157 private LockdownVpnTracker mLockdownTracker;
158
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900159 private Nat464Xlat mClat;
160
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700161 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
162 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700163 /** Currently active network rules by UID. */
164 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700165 /** Set of ifaces that are costly. */
166 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 /**
169 * Sometimes we want to refer to the individual network state
170 * trackers separately, and sometimes we just want to treat them
171 * abstractly.
172 */
173 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700174
Irfan Sheriffda6da092012-08-16 12:49:23 -0700175 /* Handles captive portal check on a network */
176 private CaptivePortalTracker mCaptivePortalTracker;
177
Robert Greenwalt42acef32009-08-12 16:08:25 -0700178 /**
Wink Savillee8222252011-07-13 13:44:13 -0700179 * The link properties that define the current links
180 */
181 private LinkProperties mCurrentLinkProperties[];
182
183 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700184 * A per Net list of the PID's that requested access to the net
185 * used both as a refcount and for per-PID DNS selection
186 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200187 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188
Robert Greenwalt42acef32009-08-12 16:08:25 -0700189 // priority order of the nettrackers
190 // (excluding dynamically set mNetworkPreference)
191 // TODO - move mNetworkTypePreference into this
192 private int[] mPriorityList;
193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private Context mContext;
195 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700196 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700197 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000198 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700199 private int mDefaultInetConditionPublished = 0;
200 private boolean mInetConditionChangeInFlight = false;
201 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700203 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800204 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700205 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700208 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700210 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700211 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700212
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700213 private static final int ENABLED = 1;
214 private static final int DISABLED = 0;
215
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700216 private static final boolean ADD = true;
217 private static final boolean REMOVE = false;
218
219 private static final boolean TO_DEFAULT_TABLE = true;
220 private static final boolean TO_SECONDARY_TABLE = false;
221
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700222 /**
223 * used internally as a delayed event to make us switch back to the
224 * default network
225 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700226 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700227
228 /**
229 * used internally to change our mobile data enabled flag
230 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700231 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700232
233 /**
234 * used internally to change our network preference setting
235 * arg1 = networkType to prefer
236 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700237 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238
239 /**
240 * used internally to synchronize inet condition reports
241 * arg1 = networkType
242 * arg2 = condition (0 bad, 100 good)
243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245
246 /**
247 * used internally to mark the end of inet condition hold periods
248 * arg1 = networkType
249 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700250 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700251
252 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700253 * used internally to set enable/disable cellular data
254 * arg1 = ENBALED or DISABLED
255 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700256 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257
Robert Greenwaltf3331232010-09-24 14:32:21 -0700258 /**
259 * used internally to clear a wakelock when transitioning
260 * from one net to another
261 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700262 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700263
Robert Greenwalt434203a2010-10-11 16:00:27 -0700264 /**
265 * used internally to reload global proxy settings
266 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700267 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700268
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700269 /**
270 * used internally to set external dependency met/unmet
271 * arg1 = ENABLED (met) or DISABLED (unmet)
272 * arg2 = NetworkType
273 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700274 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700275
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700276 /**
277 * used internally to restore DNS properties back to the
278 * default network
279 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700280 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700281
Wink Saville2b30afd2011-08-05 11:40:22 -0700282 /**
Wink Saville628b0852011-08-04 15:01:58 -0700283 * used internally to send a sticky broadcast delayed.
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700286
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700287 /**
288 * Used internally to
289 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
290 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700291 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700292
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700293 private static final int EVENT_VPN_STATE_CHANGED = 14;
294
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700295 /** Handler used for internal events. */
296 private InternalHandler mHandler;
297 /** Handler used for incoming {@link NetworkStateTracker} events. */
298 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700299
300 // list of DeathRecipients used to make sure features are turned off when
301 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500302 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700303
Mike Lockwood0f79b542009-08-14 14:18:49 -0400304 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800305 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400306
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700307 private PowerManager.WakeLock mNetTransitionWakeLock;
308 private String mNetTransitionWakeLockCausedBy = "";
309 private int mNetTransitionWakeLockSerialNumber;
310 private int mNetTransitionWakeLockTimeout;
311
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700312 private InetAddress mDefaultDns;
313
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700314 // this collection is used to refcount the added routes - if there are none left
315 // it's time to remove the route from the route table
316 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
317
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700318 // used in DBG mode to track inet condition reports
319 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
320 private ArrayList mInetLog;
321
Robert Greenwalt434203a2010-10-11 16:00:27 -0700322 // track the current default http proxy - tell the world if we get a new one (real change)
323 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700324 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700325 private boolean mDefaultProxyDisabled = false;
326
Robert Greenwalt434203a2010-10-11 16:00:27 -0700327 // track the global proxy.
328 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700329
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
Wink Saville51f456f2013-04-23 14:26:51 -0700435 // TODO: What is the "correct" way to do determine if this is a wifi only device?
436 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
437 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700438 String[] naStrings = context.getResources().getStringArray(
439 com.android.internal.R.array.networkAttributes);
440 for (String naString : naStrings) {
441 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700442 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700443 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800444 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700445 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700446 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700447 }
Wink Saville51f456f2013-04-23 14:26:51 -0700448 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
449 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
450 n.type);
451 continue;
452 }
Wink Saville975c8482011-04-07 14:23:45 -0700453 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800454 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700455 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700456 continue;
457 }
Wink Saville975c8482011-04-07 14:23:45 -0700458 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800459 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700460 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700461 continue;
462 }
Wink Saville975c8482011-04-07 14:23:45 -0700463 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700464 mNetworksDefined++;
465 } catch(Exception e) {
466 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700467 }
468 }
469
Robert Greenwalt50393202011-06-21 17:26:14 -0700470 mProtectedNetworks = new ArrayList<Integer>();
471 int[] protectedNetworks = context.getResources().getIntArray(
472 com.android.internal.R.array.config_protectedNetworks);
473 for (int p : protectedNetworks) {
474 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
475 mProtectedNetworks.add(p);
476 } else {
477 if (DBG) loge("Ignoring protectedNetwork " + p);
478 }
479 }
480
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700481 // high priority first
482 mPriorityList = new int[mNetworksDefined];
483 {
484 int insertionPoint = mNetworksDefined-1;
485 int currentLowest = 0;
486 int nextLowest = 0;
487 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700488 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700489 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700490 if (na.priority < currentLowest) continue;
491 if (na.priority > currentLowest) {
492 if (na.priority < nextLowest || nextLowest == 0) {
493 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700494 }
495 continue;
496 }
Wink Saville975c8482011-04-07 14:23:45 -0700497 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700498 }
499 currentLowest = nextLowest;
500 nextLowest = 0;
501 }
502 }
503
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800504 // Update mNetworkPreference according to user mannually first then overlay config.xml
505 mNetworkPreference = getPersistedNetworkPreference();
506 if (mNetworkPreference == -1) {
507 for (int n : mPriorityList) {
508 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
509 mNetworkPreference = n;
510 break;
511 }
512 }
513 if (mNetworkPreference == -1) {
514 throw new IllegalStateException(
515 "You should set at least one default Network in config.xml!");
516 }
517 }
518
Mattias Falk8b47b362011-08-23 14:15:13 +0200519 mNetRequestersPids =
520 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700521 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200522 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700523 }
524
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500525 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700526
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700527 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
528 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700529
530 // Create and start trackers for hard-coded networks
531 for (int targetNetworkType : mPriorityList) {
532 final NetworkConfig config = mNetConfigs[targetNetworkType];
533 final NetworkStateTracker tracker;
534 try {
535 tracker = netFactory.createTracker(targetNetworkType, config);
536 mNetTrackers[targetNetworkType] = tracker;
537 } catch (IllegalArgumentException e) {
538 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
539 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700540 continue;
541 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700542
543 tracker.startMonitoring(context, mTrackerHandler);
544 if (config.isDefault()) {
545 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800546 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700547 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800548
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700549 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700550 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700551 mTethering.getTetherableWifiRegexs().length != 0 ||
552 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700553 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800554
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -0700555 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey899223b2012-08-04 15:24:58 -0700556 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700557
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900558 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
559
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700560 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700561 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700562 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900563 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700564 } catch (RemoteException e) {
565 loge("Error registering observer :" + e);
566 }
567
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700568 if (DBG) {
569 mInetLog = new ArrayList();
570 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700571
572 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
573 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800574
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700575 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800576 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700578
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700579 /**
580 * Factory that creates {@link NetworkStateTracker} instances using given
581 * {@link NetworkConfig}.
582 */
583 public interface NetworkFactory {
584 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
585 }
586
587 private static class DefaultNetworkFactory implements NetworkFactory {
588 private final Context mContext;
589 private final Handler mTrackerHandler;
590
591 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
592 mContext = context;
593 mTrackerHandler = trackerHandler;
594 }
595
596 @Override
597 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
598 switch (config.radio) {
599 case TYPE_WIFI:
600 return new WifiStateTracker(targetNetworkType, config.name);
601 case TYPE_MOBILE:
602 return new MobileDataStateTracker(targetNetworkType, config.name);
603 case TYPE_DUMMY:
604 return new DummyDataStateTracker(targetNetworkType, config.name);
605 case TYPE_BLUETOOTH:
606 return BluetoothTetheringDataTracker.getInstance();
607 case TYPE_WIMAX:
608 return makeWimaxStateTracker(mContext, mTrackerHandler);
609 case TYPE_ETHERNET:
610 return EthernetDataTracker.getInstance();
611 default:
612 throw new IllegalArgumentException(
613 "Trying to create a NetworkStateTracker for an unknown radio type: "
614 + config.radio);
615 }
616 }
617 }
618
619 /**
620 * Loads external WiMAX library and registers as system service, returning a
621 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
622 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
623 */
624 private static NetworkStateTracker makeWimaxStateTracker(
625 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700626 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900627 DexClassLoader wimaxClassLoader;
628 Class wimaxStateTrackerClass = null;
629 Class wimaxServiceClass = null;
630 Class wimaxManagerClass;
631 String wimaxJarLocation;
632 String wimaxLibLocation;
633 String wimaxManagerClassName;
634 String wimaxServiceClassName;
635 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636
tk.mun148c7d02011-10-13 22:51:57 +0900637 NetworkStateTracker wimaxStateTracker = null;
638
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700639 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900640 com.android.internal.R.bool.config_wimaxEnabled);
641
642 if (isWimaxEnabled) {
643 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700644 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900645 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700646 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900647 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700648 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900649 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700650 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900651 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700652 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900653 com.android.internal.R.string.config_wimaxStateTrackerClassname);
654
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800655 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900656 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700657 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900658 wimaxLibLocation, ClassLoader.getSystemClassLoader());
659
660 try {
661 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
662 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
663 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
664 } catch (ClassNotFoundException ex) {
665 loge("Exception finding Wimax classes: " + ex.toString());
666 return null;
667 }
668 } catch(Resources.NotFoundException ex) {
669 loge("Wimax Resources does not exist!!! ");
670 return null;
671 }
672
673 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800674 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900675
676 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
677 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700678 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
679 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900680
681 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
682 (new Class[] {Context.class, wimaxStateTrackerClass});
683 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700684 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900685 wmxSrvConst.setAccessible(false);
686
687 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
688
689 } catch(Exception ex) {
690 loge("Exception creating Wimax classes: " + ex.toString());
691 return null;
692 }
693 } else {
694 loge("Wimax is not enabled or not added to the network attributes!!! ");
695 return null;
696 }
697
698 return wimaxStateTracker;
699 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700702 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 * @param preference the new preference
704 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700705 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700707
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700708 mHandler.sendMessage(
709 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711
712 public int getNetworkPreference() {
713 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700714 int preference;
715 synchronized(this) {
716 preference = mNetworkPreference;
717 }
718 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
720
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700721 private void handleSetNetworkPreference(int preference) {
722 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700723 mNetConfigs[preference] != null &&
724 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700725 if (mNetworkPreference != preference) {
726 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700727 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700728 synchronized(this) {
729 mNetworkPreference = preference;
730 }
731 enforcePreference();
732 }
733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700735
Wink Saville628b0852011-08-04 15:01:58 -0700736 private int getConnectivityChangeDelay() {
737 final ContentResolver cr = mContext.getContentResolver();
738
739 /** Check system properties for the default value then use secure settings value, if any. */
740 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700741 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
742 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
743 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700744 defaultDelay);
745 }
746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 private int getPersistedNetworkPreference() {
748 final ContentResolver cr = mContext.getContentResolver();
749
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700750 final int networkPrefSetting = Settings.Global
751 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800753 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700757 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 * In this method, we only tear down a non-preferred network. Establishing
759 * a connection to the preferred network is taken care of when we handle
760 * the disconnect event from the non-preferred network
761 * (see {@link #handleDisconnect(NetworkInfo)}).
762 */
763 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700764 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 return;
766
Robert Greenwalt42acef32009-08-12 16:08:25 -0700767 if (!mNetTrackers[mNetworkPreference].isAvailable())
768 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
Robert Greenwalt42acef32009-08-12 16:08:25 -0700770 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700771 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700772 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700773 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800774 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700775 " in enforcePreference");
776 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700777 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 }
779 }
780 }
781
782 private boolean teardown(NetworkStateTracker netTracker) {
783 if (netTracker.teardown()) {
784 netTracker.setTeardownRequested(true);
785 return true;
786 } else {
787 return false;
788 }
789 }
790
791 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700792 * Check if UID should be blocked from using the network represented by the
793 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700794 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700795 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
796 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700797
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700798 final boolean networkCostly;
799 final int uidRules;
800 synchronized (mRulesLock) {
801 networkCostly = mMeteredIfaces.contains(iface);
802 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700803 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700804
805 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
806 return true;
807 }
808
809 // no restrictive rules; network is visible
810 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700811 }
812
813 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700814 * Return a filtered {@link NetworkInfo}, potentially marked
815 * {@link DetailedState#BLOCKED} based on
816 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700817 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700818 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
819 NetworkInfo info = tracker.getNetworkInfo();
820 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700821 // network is blocked; clone and override state
822 info = new NetworkInfo(info);
823 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700824 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700825 if (mLockdownTracker != null) {
826 info = mLockdownTracker.augmentNetworkInfo(info);
827 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700828 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700829 }
830
831 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 * Return NetworkInfo for the active (i.e., connected) network interface.
833 * It is assumed that at most one network is active at a time. If more
834 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700835 * @return the info for the active network, or {@code null} if none is
836 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700838 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700840 enforceAccessPermission();
841 final int uid = Binder.getCallingUid();
842 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700845 public NetworkInfo getActiveNetworkInfoUnfiltered() {
846 enforceAccessPermission();
847 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
848 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
849 if (tracker != null) {
850 return tracker.getNetworkInfo();
851 }
852 }
853 return null;
854 }
855
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700856 @Override
857 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
858 enforceConnectivityInternalPermission();
859 return getNetworkInfo(mActiveDefaultNetwork, uid);
860 }
861
862 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 public NetworkInfo getNetworkInfo(int networkType) {
864 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700865 final int uid = Binder.getCallingUid();
866 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700869 private NetworkInfo getNetworkInfo(int networkType, int uid) {
870 NetworkInfo info = null;
871 if (isNetworkTypeValid(networkType)) {
872 final NetworkStateTracker tracker = mNetTrackers[networkType];
873 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700874 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 }
876 }
877 return info;
878 }
879
880 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 public NetworkInfo[] getAllNetworkInfo() {
882 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700883 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700884 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700885 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700886 for (NetworkStateTracker tracker : mNetTrackers) {
887 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700888 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700889 }
890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700892 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700895 @Override
896 public boolean isNetworkSupported(int networkType) {
897 enforceAccessPermission();
898 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
899 }
900
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700901 /**
902 * Return LinkProperties for the active (i.e., connected) default
903 * network interface. It is assumed that at most one default network
904 * is active at a time. If more than one is active, it is indeterminate
905 * which will be returned.
906 * @return the ip properties for the active network, or {@code null} if
907 * none is active
908 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700909 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700910 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700911 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700912 }
913
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700914 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700915 public LinkProperties getLinkProperties(int networkType) {
916 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700917 if (isNetworkTypeValid(networkType)) {
918 final NetworkStateTracker tracker = mNetTrackers[networkType];
919 if (tracker != null) {
920 return tracker.getLinkProperties();
921 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700922 }
923 return null;
924 }
925
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700926 @Override
927 public NetworkState[] getAllNetworkState() {
928 enforceAccessPermission();
929 final int uid = Binder.getCallingUid();
930 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700931 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700932 for (NetworkStateTracker tracker : mNetTrackers) {
933 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700934 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700935 result.add(new NetworkState(
936 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
937 }
938 }
939 }
940 return result.toArray(new NetworkState[result.size()]);
941 }
942
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700943 private NetworkState getNetworkStateUnchecked(int networkType) {
944 if (isNetworkTypeValid(networkType)) {
945 final NetworkStateTracker tracker = mNetTrackers[networkType];
946 if (tracker != null) {
947 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
948 tracker.getLinkCapabilities());
949 }
950 }
951 return null;
952 }
953
954 @Override
955 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
956 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700957
958 final long token = Binder.clearCallingIdentity();
959 try {
960 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
961 if (state != null) {
962 try {
963 return mPolicyManager.getNetworkQuotaInfo(state);
964 } catch (RemoteException e) {
965 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700966 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700967 return null;
968 } finally {
969 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700970 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700971 }
972
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700973 @Override
974 public boolean isActiveNetworkMetered() {
975 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700976 final long token = Binder.clearCallingIdentity();
977 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700978 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700979 } finally {
980 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700981 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700982 }
983
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700984 private boolean isNetworkMeteredUnchecked(int networkType) {
985 final NetworkState state = getNetworkStateUnchecked(networkType);
986 if (state != null) {
987 try {
988 return mPolicyManager.isNetworkMetered(state);
989 } catch (RemoteException e) {
990 }
991 }
992 return false;
993 }
994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 public boolean setRadios(boolean turnOn) {
996 boolean result = true;
997 enforceChangePermission();
998 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700999 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 }
1001 return result;
1002 }
1003
1004 public boolean setRadio(int netType, boolean turnOn) {
1005 enforceChangePermission();
1006 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1007 return false;
1008 }
1009 NetworkStateTracker tracker = mNetTrackers[netType];
1010 return tracker != null && tracker.setRadio(turnOn);
1011 }
1012
Jeff Sharkey216c1812012-08-05 14:29:23 -07001013 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1014 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001015 public void interfaceClassDataActivityChanged(String label, boolean active) {
1016 int deviceType = Integer.parseInt(label);
1017 sendDataActivityBroadcast(deviceType, active);
1018 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001019 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001020
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001021 /**
1022 * Used to notice when the calling process dies so we can self-expire
1023 *
1024 * Also used to know if the process has cleaned up after itself when
1025 * our auto-expire timer goes off. The timer has a link to an object.
1026 *
1027 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001028 private class FeatureUser implements IBinder.DeathRecipient {
1029 int mNetworkType;
1030 String mFeature;
1031 IBinder mBinder;
1032 int mPid;
1033 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001034 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001035
1036 FeatureUser(int type, String feature, IBinder binder) {
1037 super();
1038 mNetworkType = type;
1039 mFeature = feature;
1040 mBinder = binder;
1041 mPid = getCallingPid();
1042 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001043 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001044
Robert Greenwalt42acef32009-08-12 16:08:25 -07001045 try {
1046 mBinder.linkToDeath(this, 0);
1047 } catch (RemoteException e) {
1048 binderDied();
1049 }
1050 }
1051
1052 void unlinkDeathRecipient() {
1053 mBinder.unlinkToDeath(this, 0);
1054 }
1055
1056 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001057 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001058 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1059 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001060 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001061 }
1062
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001063 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001064 if (VDBG) {
1065 log("ConnectivityService FeatureUser expire(" +
1066 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1067 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1068 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001069 stopUsingNetworkFeature(this, false);
1070 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001071
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001072 public boolean isSameUser(FeatureUser u) {
1073 if (u == null) return false;
1074
1075 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1076 }
1077
1078 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1079 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1080 TextUtils.equals(mFeature, feature)) {
1081 return true;
1082 }
1083 return false;
1084 }
1085
Robert Greenwaltb9285352009-12-21 18:24:07 -08001086 public String toString() {
1087 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1088 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1089 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001090 }
1091
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001092 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001093 public int startUsingNetworkFeature(int networkType, String feature,
1094 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001095 long startTime = 0;
1096 if (DBG) {
1097 startTime = SystemClock.elapsedRealtime();
1098 }
Wink Savillec9acde92011-09-21 11:05:43 -07001099 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001100 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1101 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001104 try {
1105 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1106 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001107 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001108 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001109
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001110 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001111
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001112 // TODO - move this into individual networktrackers
1113 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001114
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001115 if (mLockdownEnabled) {
1116 // Since carrier APNs usually aren't available from VPN
1117 // endpoint, mark them as unavailable.
1118 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1119 }
1120
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001121 if (mProtectedNetworks.contains(usedNetworkType)) {
1122 enforceConnectivityInternalPermission();
1123 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001124
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001125 // if UID is restricted, don't allow them to bring up metered APNs
1126 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1127 final int uidRules;
1128 synchronized (mRulesLock) {
1129 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1130 }
1131 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001132 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001133 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001134
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001135 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1136 if (network != null) {
1137 Integer currentPid = new Integer(getCallingPid());
1138 if (usedNetworkType != networkType) {
1139 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001140
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001141 if (ni.isAvailable() == false) {
1142 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1143 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001144 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001145 } else {
1146 // else make the attempt anyway - probably giving REQUEST_STARTED below
1147 if (DBG) {
1148 log("special network not available, but try anyway ni=" +
1149 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001150 }
1151 }
1152 }
1153
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001154 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001155
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001156 synchronized(this) {
1157 boolean addToList = true;
1158 if (restoreTimer < 0) {
1159 // In case there is no timer is specified for the feature,
1160 // make sure we don't add duplicate entry with the same request.
1161 for (FeatureUser u : mFeatureUsers) {
1162 if (u.isSameUser(f)) {
1163 // Duplicate user is found. Do not add.
1164 addToList = false;
1165 break;
1166 }
1167 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001168 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001169
1170 if (addToList) mFeatureUsers.add(f);
1171 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1172 // this gets used for per-pid dns when connected
1173 mNetRequestersPids[usedNetworkType].add(currentPid);
1174 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001175 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001176
1177 if (restoreTimer >= 0) {
1178 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1179 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1180 }
1181
1182 if ((ni.isConnectedOrConnecting() == true) &&
1183 !network.isTeardownRequested()) {
1184 if (ni.isConnected() == true) {
1185 final long token = Binder.clearCallingIdentity();
1186 try {
1187 // add the pid-specific dns
1188 handleDnsConfigurationChange(usedNetworkType);
1189 if (VDBG) log("special network already active");
1190 } finally {
1191 Binder.restoreCallingIdentity(token);
1192 }
Wink Savillea639b312012-07-10 12:37:54 -07001193 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001194 }
1195 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001196 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001197 }
1198
1199 // check if the radio in play can make another contact
1200 // assume if cannot for now
1201
1202 if (DBG) {
1203 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1204 feature);
1205 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001206 if (network.reconnect()) {
1207 return PhoneConstants.APN_REQUEST_STARTED;
1208 } else {
1209 return PhoneConstants.APN_REQUEST_FAILED;
1210 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001211 } else {
1212 // need to remember this unsupported request so we respond appropriately on stop
1213 synchronized(this) {
1214 mFeatureUsers.add(f);
1215 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1216 // this gets used for per-pid dns when connected
1217 mNetRequestersPids[usedNetworkType].add(currentPid);
1218 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001219 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001220 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001221 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001222 }
Wink Savillea639b312012-07-10 12:37:54 -07001223 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001224 } finally {
1225 if (DBG) {
1226 final long execTime = SystemClock.elapsedRealtime() - startTime;
1227 if (execTime > 250) {
1228 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1229 } else {
1230 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1231 }
1232 }
1233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001236 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001238 enforceChangePermission();
1239
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001240 int pid = getCallingPid();
1241 int uid = getCallingUid();
1242
1243 FeatureUser u = null;
1244 boolean found = false;
1245
1246 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001247 for (FeatureUser x : mFeatureUsers) {
1248 if (x.isSameUser(pid, uid, networkType, feature)) {
1249 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001250 found = true;
1251 break;
1252 }
1253 }
1254 }
1255 if (found && u != null) {
1256 // stop regardless of how many other time this proc had called start
1257 return stopUsingNetworkFeature(u, true);
1258 } else {
1259 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001260 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001261 return 1;
1262 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001263 }
1264
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001265 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1266 int networkType = u.mNetworkType;
1267 String feature = u.mFeature;
1268 int pid = u.mPid;
1269 int uid = u.mUid;
1270
1271 NetworkStateTracker tracker = null;
1272 boolean callTeardown = false; // used to carry our decision outside of sync block
1273
Wink Savillec9acde92011-09-21 11:05:43 -07001274 if (VDBG) {
1275 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001276 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001279 if (DBG) {
1280 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1281 ", net is invalid");
1282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 return -1;
1284 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001285
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001286 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1287 // sync block
1288 synchronized(this) {
1289 // check if this process still has an outstanding start request
1290 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001291 if (VDBG) {
1292 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1293 ", ignoring");
1294 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001295 return 1;
1296 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001297 u.unlinkDeathRecipient();
1298 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1299 // If we care about duplicate requests, check for that here.
1300 //
1301 // This is done to support the extension of a request - the app
1302 // can request we start the network feature again and renew the
1303 // auto-shutoff delay. Normal "stop" calls from the app though
1304 // do not pay attention to duplicate requests - in effect the
1305 // API does not refcount and a single stop will counter multiple starts.
1306 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001307 for (FeatureUser x : mFeatureUsers) {
1308 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001309 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001310 return 1;
1311 }
1312 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001313 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001314
repo syncaea743a2011-07-29 23:55:49 -07001315 // TODO - move to individual network trackers
1316 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1317
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001318 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001319 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001320 if (DBG) {
1321 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1322 " no known tracker for used net type " + usedNetworkType);
1323 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001324 return -1;
1325 }
1326 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001327 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001328 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001329
1330 final long token = Binder.clearCallingIdentity();
1331 try {
1332 reassessPidDns(pid, true);
1333 } finally {
1334 Binder.restoreCallingIdentity(token);
1335 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001336 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001337 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001338 if (VDBG) {
1339 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1340 " others still using it");
1341 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001342 return 1;
1343 }
1344 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001345 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001346 if (DBG) {
1347 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1348 " not a known feature - dropping");
1349 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001350 }
1351 }
Wink Savillec9acde92011-09-21 11:05:43 -07001352
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001353 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001354 if (DBG) {
1355 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1356 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001357 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001358 return 1;
1359 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001360 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363
1364 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001365 * @deprecated use requestRouteToHostAddress instead
1366 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 * Ensure that a network route exists to deliver traffic to the specified
1368 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001369 * @param networkType the type of the network over which traffic to the
1370 * specified host is to be routed
1371 * @param hostAddress the IP address of the host to which the route is
1372 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 * @return {@code true} on success, {@code false} on failure
1374 */
1375 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001376 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1377
1378 if (inetAddress == null) {
1379 return false;
1380 }
1381
1382 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1383 }
1384
1385 /**
1386 * Ensure that a network route exists to deliver traffic to the specified
1387 * host via the specified network interface.
1388 * @param networkType the type of the network over which traffic to the
1389 * specified host is to be routed
1390 * @param hostAddress the IP address of the host to which the route is
1391 * desired
1392 * @return {@code true} on success, {@code false} on failure
1393 */
1394 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001396 if (mProtectedNetworks.contains(networkType)) {
1397 enforceConnectivityInternalPermission();
1398 }
1399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001401 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 return false;
1403 }
1404 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001405 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001406
Irfan Sheriffda6da092012-08-16 12:49:23 -07001407 if (tracker == null || (netState != DetailedState.CONNECTED &&
1408 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001409 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001410 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001411 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001412 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001413 }
1414 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001416 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001417 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001418 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001419 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001420 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001421 } catch (UnknownHostException e) {
1422 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1423 } finally {
1424 Binder.restoreCallingIdentity(token);
1425 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001426 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001427 }
1428
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001429 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001430 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001431 }
1432
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001433 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001434 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001435 }
1436
Robert Greenwaltad55d352011-07-22 11:55:33 -07001437 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001438 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001439 }
1440
1441 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001442 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001443 }
1444
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001445 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1446 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001447 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001448 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001449 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001451 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001452 if (bestRoute.getGateway().equals(addr)) {
1453 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001454 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001455 } else {
1456 // if we will connect to this through another route, add a direct route
1457 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001458 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 }
1460 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001461 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001462 }
1463
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001464 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1465 boolean toDefaultTable) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001466 if ((lp == null) || (r == null)) {
1467 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001468 return false;
1469 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001470
1471 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001472 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001473 return false;
1474 }
1475
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001476 String ifaceName = r.getInterface();
1477 if(ifaceName == null) {
1478 loge("Error modifying route - no interface name");
1479 return false;
1480 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001481 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001482 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001483 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001484 if (bestRoute.getGateway().equals(r.getGateway())) {
1485 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001486 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001487 } else {
1488 // if we will connect to our gateway through another route, add a direct
1489 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001490 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1491 bestRoute.getGateway(),
1492 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001493 }
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001494 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001495 }
1496 }
1497 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001498 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001499 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001500 if (toDefaultTable) {
1501 mAddedRoutes.add(r); // only track default table - only one apps can effect
1502 mNetd.addRoute(ifaceName, r);
1503 } else {
1504 mNetd.addSecondaryRoute(ifaceName, r);
1505 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001506 } catch (Exception e) {
1507 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001508 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001509 return false;
1510 }
1511 } else {
1512 // if we remove this one and there are no more like it, then refcount==0 and
1513 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001514 if (toDefaultTable) {
1515 mAddedRoutes.remove(r);
1516 if (mAddedRoutes.contains(r) == false) {
1517 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1518 try {
1519 mNetd.removeRoute(ifaceName, r);
1520 } catch (Exception e) {
1521 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001522 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001523 return false;
1524 }
1525 } else {
1526 if (VDBG) log("not removing " + r + " as it's still in use");
1527 }
1528 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001529 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001530 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001531 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001532 } catch (Exception e) {
1533 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001534 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001535 return false;
1536 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001537 }
1538 }
1539 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541
1542 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001543 * @see ConnectivityManager#getMobileDataEnabled()
1544 */
1545 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001546 // TODO: This detail should probably be in DataConnectionTracker's
1547 // which is where we store the value and maybe make this
1548 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001549 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001550 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1551 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001552 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001553 return retVal;
1554 }
1555
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001556 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001557 enforceConnectivityInternalPermission();
1558
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001559 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1560 (met ? ENABLED : DISABLED), networkType));
1561 }
1562
1563 private void handleSetDependencyMet(int networkType, boolean met) {
1564 if (mNetTrackers[networkType] != null) {
1565 if (DBG) {
1566 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1567 }
1568 mNetTrackers[networkType].setDependencyMet(met);
1569 }
1570 }
1571
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001572 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1573 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001574 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001575 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001576 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001577 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001578 }
1579
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001580 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001581 // skip update when we've already applied rules
1582 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1583 if (oldRules == uidRules) return;
1584
1585 mUidRules.put(uid, uidRules);
1586 }
1587
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001588 // TODO: notify UID when it has requested targeted updates
1589 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001590
1591 @Override
1592 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001593 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001594 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001595 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001596 }
1597
1598 synchronized (mRulesLock) {
1599 mMeteredIfaces.clear();
1600 for (String iface : meteredIfaces) {
1601 mMeteredIfaces.add(iface);
1602 }
1603 }
1604 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001605
1606 @Override
1607 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1608 // caller is NPMS, since we only register with them
1609 if (LOGD_RULES) {
1610 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1611 }
1612
1613 // kick off connectivity change broadcast for active network, since
1614 // global background policy change is radical.
1615 final int networkType = mActiveDefaultNetwork;
1616 if (isNetworkTypeValid(networkType)) {
1617 final NetworkStateTracker tracker = mNetTrackers[networkType];
1618 if (tracker != null) {
1619 final NetworkInfo info = tracker.getNetworkInfo();
1620 if (info != null && info.isConnected()) {
1621 sendConnectedBroadcast(info);
1622 }
1623 }
1624 }
1625 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001626 };
1627
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001628 /**
1629 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1630 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001631 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001632 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001633 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001634
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001635 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001636 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001637 }
1638
1639 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001640 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001641 if (VDBG) {
1642 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001643 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001644 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1645 }
tk.munb97d34c2012-01-06 10:43:52 +09001646 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1647 if (VDBG) {
1648 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1649 }
1650 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1651 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001652 }
1653
1654 @Override
1655 public void setPolicyDataEnable(int networkType, boolean enabled) {
1656 // only someone like NPMS should only be calling us
1657 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1658
1659 mHandler.sendMessage(mHandler.obtainMessage(
1660 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1661 }
1662
1663 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1664 if (isNetworkTypeValid(networkType)) {
1665 final NetworkStateTracker tracker = mNetTrackers[networkType];
1666 if (tracker != null) {
1667 tracker.setPolicyDataEnable(enabled);
1668 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001669 }
1670 }
1671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001673 mContext.enforceCallingOrSelfPermission(
1674 android.Manifest.permission.ACCESS_NETWORK_STATE,
1675 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677
1678 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001679 mContext.enforceCallingOrSelfPermission(
1680 android.Manifest.permission.CHANGE_NETWORK_STATE,
1681 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001684 // TODO Make this a special check when it goes public
1685 private void enforceTetherChangePermission() {
1686 mContext.enforceCallingOrSelfPermission(
1687 android.Manifest.permission.CHANGE_NETWORK_STATE,
1688 "ConnectivityService");
1689 }
1690
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001691 private void enforceTetherAccessPermission() {
1692 mContext.enforceCallingOrSelfPermission(
1693 android.Manifest.permission.ACCESS_NETWORK_STATE,
1694 "ConnectivityService");
1695 }
1696
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001697 private void enforceConnectivityInternalPermission() {
1698 mContext.enforceCallingOrSelfPermission(
1699 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1700 "ConnectivityService");
1701 }
1702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001704 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1705 * network, we ignore it. If it is for the active network, we send out a
1706 * broadcast. But first, we check whether it might be possible to connect
1707 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 * @param info the {@code NetworkInfo} for the network
1709 */
1710 private void handleDisconnect(NetworkInfo info) {
1711
Robert Greenwalt42acef32009-08-12 16:08:25 -07001712 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713
Robert Greenwalt42acef32009-08-12 16:08:25 -07001714 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001715
1716 // Remove idletimer previously setup in {@code handleConnect}
1717 removeDataActivityTracking(prevNetType);
1718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 /*
1720 * If the disconnected network is not the active one, then don't report
1721 * this as a loss of connectivity. What probably happened is that we're
1722 * getting the disconnect for a network that we explicitly disabled
1723 * in accordance with network preference policies.
1724 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001725 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001726 List<Integer> pids = mNetRequestersPids[prevNetType];
1727 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001728 // will remove them because the net's no longer connected
1729 // need to do this now as only now do we know the pids and
1730 // can properly null things that are no longer referenced.
1731 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001736 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001737 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (info.isFailover()) {
1739 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1740 info.setFailover(false);
1741 }
1742 if (info.getReason() != null) {
1743 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1744 }
1745 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001746 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1747 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001749
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001750 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001751 tryFailover(prevNetType);
1752 if (mActiveDefaultNetwork != -1) {
1753 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001754 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1755 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001756 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001757 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1758 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001759 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001760 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001761
1762 // Reset interface if no other connections are using the same interface
1763 boolean doReset = true;
1764 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1765 if (linkProperties != null) {
1766 String oldIface = linkProperties.getInterfaceName();
1767 if (TextUtils.isEmpty(oldIface) == false) {
1768 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1769 if (networkStateTracker == null) continue;
1770 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1771 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1772 LinkProperties l = networkStateTracker.getLinkProperties();
1773 if (l == null) continue;
1774 if (oldIface.equals(l.getInterfaceName())) {
1775 doReset = false;
1776 break;
1777 }
1778 }
1779 }
1780 }
1781 }
1782
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001783 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001784 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001785
Jeff Sharkey961e3042011-08-29 16:02:57 -07001786 final Intent immediateIntent = new Intent(intent);
1787 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1788 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001789 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001790 /*
1791 * If the failover network is already connected, then immediately send
1792 * out a followup broadcast indicating successful failover
1793 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001794 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001795 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1796 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001797 }
1798 }
1799
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001800 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001801 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001802 * If this is a default network, check if other defaults are available.
1803 * Try to reconnect on all available and let them hash it out when
1804 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001805 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001806 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001807 if (mActiveDefaultNetwork == prevNetType) {
1808 mActiveDefaultNetwork = -1;
1809 }
1810
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001811 // don't signal a reconnect for anything lower or equal priority than our
1812 // current connected default
1813 // TODO - don't filter by priority now - nice optimization but risky
1814// int currentPriority = -1;
1815// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001816// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001817// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001818 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001819 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001820 if (mNetConfigs[checkType] == null) continue;
1821 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001822 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001823
1824// Enabling the isAvailable() optimization caused mobile to not get
1825// selected if it was in the middle of error handling. Specifically
1826// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1827// would not be available and we wouldn't get connected to anything.
1828// So removing the isAvailable() optimization below for now. TODO: This
1829// optimization should work and we need to investigate why it doesn't work.
1830// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1831// complete before it is really complete.
1832// if (!mNetTrackers[checkType].isAvailable()) continue;
1833
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001834// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001835
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001836 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1837 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1838 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1839 checkInfo.setFailover(true);
1840 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001841 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001842 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001847 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001848 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001849 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1850 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001851 }
1852
Wink Saville628b0852011-08-04 15:01:58 -07001853 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001854 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1855 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001856 }
1857
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001858 private void sendInetConditionBroadcast(NetworkInfo info) {
1859 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1860 }
1861
Wink Saville628b0852011-08-04 15:01:58 -07001862 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001863 if (mLockdownTracker != null) {
1864 info = mLockdownTracker.augmentNetworkInfo(info);
1865 }
1866
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001867 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001868 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001869 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 if (info.isFailover()) {
1871 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1872 info.setFailover(false);
1873 }
1874 if (info.getReason() != null) {
1875 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1876 }
1877 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001878 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1879 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001881 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001882 return intent;
1883 }
1884
1885 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1886 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1887 }
1888
1889 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1890 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892
Haoyu Baidb3c8672012-06-20 14:29:57 -07001893 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1894 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1895 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1896 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001897 final long ident = Binder.clearCallingIdentity();
1898 try {
1899 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1900 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1901 } finally {
1902 Binder.restoreCallingIdentity(ident);
1903 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001904 }
1905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 /**
1907 * Called when an attempt to fail over to another network has failed.
1908 * @param info the {@link NetworkInfo} for the failed network
1909 */
1910 private void handleConnectionFailure(NetworkInfo info) {
1911 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912
Robert Greenwalt42acef32009-08-12 16:08:25 -07001913 String reason = info.getReason();
1914 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001915
Robert Greenwalt572172b2010-10-08 16:35:52 -07001916 String reasonText;
1917 if (reason == null) {
1918 reasonText = ".";
1919 } else {
1920 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001922 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001923
1924 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001925 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001927 if (getActiveNetworkInfo() == null) {
1928 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1929 }
1930 if (reason != null) {
1931 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1932 }
1933 if (extraInfo != null) {
1934 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1935 }
1936 if (info.isFailover()) {
1937 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1938 info.setFailover(false);
1939 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001940
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001941 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001942 tryFailover(info.getType());
1943 if (mActiveDefaultNetwork != -1) {
1944 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001945 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1946 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001947 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001948 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1949 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001950 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001951
Robert Greenwalt029be812010-09-20 18:01:43 -07001952 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001953
1954 final Intent immediateIntent = new Intent(intent);
1955 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1956 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001957 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001958 /*
1959 * If the failover network is already connected, then immediately send
1960 * out a followup broadcast indicating successful failover
1961 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001962 if (mActiveDefaultNetwork != -1) {
1963 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001964 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001965 }
1966
1967 private void sendStickyBroadcast(Intent intent) {
1968 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001969 if (!mSystemReady) {
1970 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001971 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001972 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001973 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001974 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001975 }
1976
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001977 final long ident = Binder.clearCallingIdentity();
1978 try {
1979 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1980 } finally {
1981 Binder.restoreCallingIdentity(ident);
1982 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001983 }
1984 }
1985
Wink Saville628b0852011-08-04 15:01:58 -07001986 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1987 if (delayMs <= 0) {
1988 sendStickyBroadcast(intent);
1989 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001990 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001991 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1992 + intent.getAction());
1993 }
Wink Saville628b0852011-08-04 15:01:58 -07001994 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1995 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1996 }
1997 }
1998
Mike Lockwood0f79b542009-08-14 14:18:49 -04001999 void systemReady() {
2000 synchronized(this) {
2001 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002002 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002003 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002004 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002005 }
2006 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002007 // load the global proxy at startup
2008 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002009
2010 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2011 // for user to unlock device.
2012 if (!updateLockdownVpn()) {
2013 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2014 mContext.registerReceiver(mUserPresentReceiver, filter);
2015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002018 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2019 @Override
2020 public void onReceive(Context context, Intent intent) {
2021 // Try creating lockdown tracker, since user present usually means
2022 // unlocked keystore.
2023 if (updateLockdownVpn()) {
2024 mContext.unregisterReceiver(this);
2025 }
2026 }
2027 };
2028
Irfan Sheriffda6da092012-08-16 12:49:23 -07002029 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2030 if ((type != mNetworkPreference &&
2031 mNetConfigs[mActiveDefaultNetwork].priority >
2032 mNetConfigs[type].priority) ||
2033 mNetworkPreference == mActiveDefaultNetwork) return false;
2034 return true;
2035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036
Irfan Sheriffda6da092012-08-16 12:49:23 -07002037 private void handleConnect(NetworkInfo info) {
2038 final int newNetType = info.getType();
2039
2040 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 // snapshot isFailover, because sendConnectedBroadcast() resets it
2043 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002044 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002045 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046
Robert Greenwalt42acef32009-08-12 16:08:25 -07002047 // if this is a default net and other default is running
2048 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002049 if (mNetConfigs[newNetType].isDefault()) {
2050 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2051 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002052 // tear down the other
2053 NetworkStateTracker otherNet =
2054 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002055 if (DBG) {
2056 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002057 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002058 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002059 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002060 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002061 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002062 return;
2063 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002064 } else {
2065 // don't accept this one
2066 if (VDBG) {
2067 log("Not broadcasting CONNECT_ACTION " +
2068 "to torn down network " + info.getTypeName());
2069 }
2070 teardown(thisNet);
2071 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002072 }
2073 }
2074 synchronized (ConnectivityService.this) {
2075 // have a new default network, release the transition wakelock in a second
2076 // if it's held. The second pause is to allow apps to reconnect over the
2077 // new network
2078 if (mNetTransitionWakeLock.isHeld()) {
2079 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002080 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002081 mNetTransitionWakeLockSerialNumber, 0),
2082 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002083 }
2084 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002085 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002086 // this will cause us to come up initially as unconnected and switching
2087 // to connected after our normal pause unless somebody reports us as reall
2088 // disconnected
2089 mDefaultInetConditionPublished = 0;
2090 mDefaultConnectionSequence++;
2091 mInetConditionChangeInFlight = false;
2092 // Don't do this - if we never sign in stay, grey
2093 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002096 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002097 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002098 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002099
2100 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002101 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002102 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002103 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002104 } catch (RemoteException e) {
2105 // ignored; service lives in system_server
2106 }
2107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109
Irfan Sheriffda6da092012-08-16 12:49:23 -07002110 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2111 if (DBG) log("Captive portal check " + info);
2112 int type = info.getType();
2113 final NetworkStateTracker thisNet = mNetTrackers[type];
2114 if (mNetConfigs[type].isDefault()) {
2115 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2116 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2117 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002118 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002119 return;
2120 } else {
2121 if (DBG) log("Tear down low priority net " + info.getTypeName());
2122 teardown(thisNet);
2123 return;
2124 }
2125 }
2126 }
2127
2128 thisNet.captivePortalCheckComplete();
2129 }
2130
2131 /** @hide */
2132 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002133 enforceConnectivityInternalPermission();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002134 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002135 }
2136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002138 * Setup data activity tracking for the given network interface.
2139 *
2140 * Every {@code setupDataActivityTracking} should be paired with a
2141 * {@link removeDataActivityTracking} for cleanup.
2142 */
2143 private void setupDataActivityTracking(int type) {
2144 final NetworkStateTracker thisNet = mNetTrackers[type];
2145 final String iface = thisNet.getLinkProperties().getInterfaceName();
2146
2147 final int timeout;
2148
2149 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002150 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2151 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002152 0);
2153 // Canonicalize mobile network type
2154 type = ConnectivityManager.TYPE_MOBILE;
2155 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002156 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2157 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002158 0);
2159 } else {
2160 // do not track any other networks
2161 timeout = 0;
2162 }
2163
2164 if (timeout > 0 && iface != null) {
2165 try {
2166 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2167 } catch (RemoteException e) {
2168 }
2169 }
2170 }
2171
2172 /**
2173 * Remove data activity tracking when network disconnects.
2174 */
2175 private void removeDataActivityTracking(int type) {
2176 final NetworkStateTracker net = mNetTrackers[type];
2177 final String iface = net.getLinkProperties().getInterfaceName();
2178
2179 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2180 ConnectivityManager.TYPE_WIFI == type)) {
2181 try {
2182 // the call fails silently if no idletimer setup for this interface
2183 mNetd.removeIdleTimer(iface);
2184 } catch (RemoteException e) {
2185 }
2186 }
2187 }
2188
2189 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002190 * After a change in the connectivity state of a network. We're mainly
2191 * concerned with making sure that the list of DNS servers is set up
2192 * according to which networks are connected, and ensuring that the
2193 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002195 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002196 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002199 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002200 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002202 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002203
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002204 LinkProperties curLp = mCurrentLinkProperties[netType];
2205 LinkProperties newLp = null;
2206
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002207 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002208 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002209 if (VDBG) {
2210 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2211 " doReset=" + doReset + " resetMask=" + resetMask +
2212 "\n curLp=" + curLp +
2213 "\n newLp=" + newLp);
2214 }
2215
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002216 if (curLp != null) {
2217 if (curLp.isIdenticalInterfaceName(newLp)) {
2218 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2219 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2220 for (LinkAddress linkAddr : car.removed) {
2221 if (linkAddr.getAddress() instanceof Inet4Address) {
2222 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2223 }
2224 if (linkAddr.getAddress() instanceof Inet6Address) {
2225 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2226 }
Wink Savillee8222252011-07-13 13:44:13 -07002227 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002228 if (DBG) {
2229 log("handleConnectivityChange: addresses changed" +
2230 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2231 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002232 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002233 } else {
2234 if (DBG) {
2235 log("handleConnectivityChange: address are the same reset per doReset" +
2236 " linkProperty[" + netType + "]:" +
2237 " resetMask=" + resetMask);
2238 }
Wink Savillee8222252011-07-13 13:44:13 -07002239 }
2240 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002241 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002242 if (DBG) {
2243 log("handleConnectivityChange: interface not not equivalent reset both" +
2244 " linkProperty[" + netType + "]:" +
2245 " resetMask=" + resetMask);
2246 }
Wink Savillee8222252011-07-13 13:44:13 -07002247 }
Wink Savillee8222252011-07-13 13:44:13 -07002248 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002249 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002250 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002251 }
2252 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002253 if (VDBG) {
2254 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2255 " doReset=" + doReset + " resetMask=" + resetMask +
2256 "\n curLp=" + curLp +
2257 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002260 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002261 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002262
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002263 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07002264 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2265 if (linkProperties != null) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002266 for (String iface : linkProperties.getAllInterfaceNames()) {
2267 if (TextUtils.isEmpty(iface) == false) {
2268 if (resetMask != 0) {
2269 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2270 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002271
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002272 // Tell VPN the interface is down. It is a temporary
2273 // but effective fix to make VPN aware of the change.
2274 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2275 mVpn.interfaceStatusChanged(iface, false);
2276 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002277 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002278 if (resetDns) {
2279 flushVmDnsCache();
2280 if (VDBG) log("resetting DNS cache for " + iface);
2281 try {
2282 mNetd.flushInterfaceDnsCache(iface);
2283 } catch (Exception e) {
2284 // never crash - catch them all
2285 if (DBG) loge("Exception resetting dns cache: " + e);
2286 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002287 }
2288 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002289 }
2290 }
2291 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002292
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002293 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002294 NetworkStateTracker tracker = mNetTrackers[netType];
2295 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002296 // If the connection was previously using clat, but is not using it now, stop the clat
2297 // daemon. Normally, this happens automatically when the connection disconnects, but if
2298 // the disconnect is not reported, or if the connection's LinkProperties changed for
2299 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2300 // still be running. If it's not running, then stopping it is a no-op.
2301 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2302 mClat.stopClat();
2303 }
2304 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002305 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2306 mClat.startClat(tracker);
2307 } else {
2308 mClat.stopClat();
2309 }
2310 }
2311
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002312 // TODO: Temporary notifying upstread change to Tethering.
2313 // @see bug/4455071
2314 /** Notify TetheringService if interface name has been changed. */
2315 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002316 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002317 if (isTetheringSupported()) {
2318 mTethering.handleTetherIfaceChange();
2319 }
2320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 }
2322
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002323 /**
2324 * Add and remove routes using the old properties (null if not previously connected),
2325 * new properties (null if becoming disconnected). May even be double null, which
2326 * is a noop.
2327 * Uses isLinkDefault to determine if default routes should be set or conversely if
2328 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002329 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002330 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002331 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2332 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002333 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002334 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2335 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002336 if (curLp != null) {
2337 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002338 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002339 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002340 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002341 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002342 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002343 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002344
Robert Greenwaltf125a092011-08-15 12:31:55 -07002345 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2346
Robert Greenwaltad55d352011-07-22 11:55:33 -07002347 for (RouteInfo r : routeDiff.removed) {
2348 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002349 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2350 }
2351 if (isLinkDefault == false) {
2352 // remove from a secondary route table
2353 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002354 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002355 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002356
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002357 if (!isLinkDefault) {
2358 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002359 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002360 // routes changed - remove all old dns entries and add new
2361 if (curLp != null) {
2362 for (InetAddress oldDns : curLp.getDnses()) {
2363 removeRouteToAddress(curLp, oldDns);
2364 }
2365 }
2366 if (newLp != null) {
2367 for (InetAddress newDns : newLp.getDnses()) {
2368 addRouteToAddress(newLp, newDns);
2369 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002370 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002371 } else {
2372 // no change in routes, check for change in dns themselves
2373 for (InetAddress oldDns : dnsDiff.removed) {
2374 removeRouteToAddress(curLp, oldDns);
2375 }
2376 for (InetAddress newDns : dnsDiff.added) {
2377 addRouteToAddress(newLp, newDns);
2378 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002379 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002380 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002381
2382 for (RouteInfo r : routeDiff.added) {
2383 if (isLinkDefault || ! r.isDefaultRoute()) {
2384 addRoute(newLp, r, TO_DEFAULT_TABLE);
2385 } else {
2386 // add to a secondary route table
2387 addRoute(newLp, r, TO_SECONDARY_TABLE);
2388
2389 // many radios add a default route even when we don't want one.
2390 // remove the default route unless somebody else has asked for it
2391 String ifaceName = newLp.getInterfaceName();
2392 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2393 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2394 try {
2395 mNetd.removeRoute(ifaceName, r);
2396 } catch (Exception e) {
2397 // never crash - catch them all
2398 if (DBG) loge("Exception trying to remove a route: " + e);
2399 }
2400 }
2401 }
2402 }
2403
Robert Greenwaltf125a092011-08-15 12:31:55 -07002404 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002405 }
2406
2407
Irfan Sheriffd649c122010-06-09 15:39:36 -07002408 /**
2409 * Reads the network specific TCP buffer sizes from SystemProperties
2410 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2411 * wide use
2412 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002413 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002414 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002415 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002416
Jeff Sharkey899223b2012-08-04 15:24:58 -07002417 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002418 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002419
2420 // Setting to default values so we won't be stuck to previous values
2421 key = "net.tcp.buffersize.default";
2422 bufferSizes = SystemProperties.get(key);
2423 }
2424
2425 // Set values in kernel
2426 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002427 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002428 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002429 + "] which comes from [" + key + "]");
2430 }
2431 setBufferSize(bufferSizes);
2432 }
2433 }
2434
2435 /**
2436 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2437 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2438 *
2439 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2440 * writeMin, writeInitial, writeMax"
2441 */
2442 private void setBufferSize(String bufferSizes) {
2443 try {
2444 String[] values = bufferSizes.split(",");
2445
2446 if (values.length == 6) {
2447 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002448 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2449 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2450 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2451 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2452 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2453 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002454 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002455 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002456 }
2457 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002458 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002459 }
2460 }
2461
Robert Greenwalt42acef32009-08-12 16:08:25 -07002462 /**
2463 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2464 * on the highest priority active net which this process requested.
2465 * If there aren't any, clear it out
2466 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002467 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002468 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002469 if (VDBG) log("reassessPidDns for pid " + pid);
2470 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002471 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002472 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002473 continue;
2474 }
2475 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002476 if (nt.getNetworkInfo().isConnected() &&
2477 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002478 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002479 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002480 if (mNetRequestersPids[i].contains(myPid)) {
2481 try {
2482 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2483 } catch (Exception e) {
2484 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002485 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002486 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002487 }
2488 }
2489 }
2490 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002491 try {
2492 mNetd.clearDnsInterfaceForPid(pid);
2493 } catch (Exception e) {
2494 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002495 }
2496 }
2497
Mattias Falk8b47b362011-08-23 14:15:13 +02002498 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002499 /*
2500 * Tell the VMs to toss their DNS caches
2501 */
2502 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2503 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002504 /*
2505 * Connectivity events can happen before boot has completed ...
2506 */
2507 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002508 final long ident = Binder.clearCallingIdentity();
2509 try {
2510 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2511 } finally {
2512 Binder.restoreCallingIdentity(ident);
2513 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002514 }
2515
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002516 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002517 private void updateDnsLocked(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002518 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002519 int last = 0;
2520 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002521 dnses = new ArrayList();
2522 dnses.add(mDefaultDns);
2523 if (DBG) {
2524 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002525 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002526 }
2527
Mattias Falk8b47b362011-08-23 14:15:13 +02002528 try {
2529 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2530 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002531 for (InetAddress dns : dnses) {
2532 ++last;
2533 String key = "net.dns" + last;
2534 String value = dns.getHostAddress();
2535 SystemProperties.set(key, value);
2536 }
2537 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2538 String key = "net.dns" + i;
2539 SystemProperties.set(key, "");
2540 }
2541 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002542 } catch (Exception e) {
2543 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002544 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002545 }
2546
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002547 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002548 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002549 NetworkStateTracker nt = mNetTrackers[netType];
2550 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002551 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002552 if (p == null) return;
2553 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002554 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002555 String network = nt.getNetworkInfo().getTypeName();
2556 synchronized (mDnsLock) {
2557 if (!mDnsOverridden) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002558 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002559 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002560 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002561 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002562 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002563 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002564 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002565 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002566 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002567 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002568 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002569 List<Integer> pids = mNetRequestersPids[netType];
2570 for (Integer pid : pids) {
2571 try {
2572 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2573 } catch (Exception e) {
2574 Slog.e(TAG, "exception setting interface for pid: " + e);
2575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002578 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002580 }
2581
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002582 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002583 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2584 NETWORK_RESTORE_DELAY_PROP_NAME);
2585 if(restoreDefaultNetworkDelayStr != null &&
2586 restoreDefaultNetworkDelayStr.length() != 0) {
2587 try {
2588 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2589 } catch (NumberFormatException e) {
2590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002592 // if the system property isn't set, use the value for the apn type
2593 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2594
2595 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2596 (mNetConfigs[networkType] != null)) {
2597 ret = mNetConfigs[networkType].restoreTime;
2598 }
2599 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 }
2601
2602 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002603 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2604 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002605 if (mContext.checkCallingOrSelfPermission(
2606 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002608 pw.println("Permission Denial: can't dump ConnectivityService " +
2609 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2610 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 return;
2612 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002613
2614 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002616 for (int i = 0; i < mNetTrackers.length; i++) {
2617 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002618 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002619 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2620 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002621 if (nst.getNetworkInfo().isConnected()) {
2622 pw.println("Active network: " + nst.getNetworkInfo().
2623 getTypeName());
2624 }
2625 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002626 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002627 pw.println(nst);
2628 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002629 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002632
2633 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002634 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002635 for (int net : mPriorityList) {
2636 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002637 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002638 pidString = pidString + pid.toString() + ", ";
2639 }
2640 pw.println(pidString);
2641 }
2642 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002643 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002644
2645 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002646 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002647 for (Object requester : mFeatureUsers) {
2648 pw.println(requester.toString());
2649 }
2650 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002651 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002652
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002653 synchronized (this) {
2654 pw.println("NetworkTranstionWakeLock is currently " +
2655 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2656 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2657 }
2658 pw.println();
2659
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002660 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002661
2662 if (mInetLog != null) {
2663 pw.println();
2664 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002665 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002666 for(int i = 0; i < mInetLog.size(); i++) {
2667 pw.println(mInetLog.get(i));
2668 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002669 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672
Robert Greenwalt42acef32009-08-12 16:08:25 -07002673 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002674 private class NetworkStateTrackerHandler extends Handler {
2675 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002676 super(looper);
2677 }
2678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 @Override
2680 public void handleMessage(Message msg) {
2681 NetworkInfo info;
2682 switch (msg.what) {
2683 case NetworkStateTracker.EVENT_STATE_CHANGED:
2684 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002685 int type = info.getType();
2686 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002687
Wink Savillec9acde92011-09-21 11:05:43 -07002688 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2689 (state == NetworkInfo.State.DISCONNECTED)) {
2690 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002691 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002692 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694
Jeff Sharkey2528b502012-11-09 15:57:02 -08002695 EventLogTags.writeConnectivityStateChanged(
2696 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002697
2698 if (info.getDetailedState() ==
2699 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002701 } else if (info.getDetailedState() ==
2702 DetailedState.CAPTIVE_PORTAL_CHECK) {
2703 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002704 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002706 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002708 // the logic here is, handle SUSPENDED the same as
2709 // DISCONNECTED. The only difference being we are
2710 // broadcasting an intent with NetworkInfo that's
2711 // suspended. This allows the applications an
2712 // opportunity to handle DISCONNECTED and SUSPENDED
2713 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002715 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 handleConnect(info);
2717 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002718 if (mLockdownTracker != null) {
2719 mLockdownTracker.onNetworkInfoChanged(info);
2720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002723 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002724 // TODO: Temporary allowing network configuration
2725 // change not resetting sockets.
2726 // @see bug/4455071
2727 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002729 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2730 info = (NetworkInfo) msg.obj;
2731 type = info.getType();
2732 updateNetworkSettings(mNetTrackers[type]);
2733 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002734 }
2735 }
2736 }
2737
2738 private class InternalHandler extends Handler {
2739 public InternalHandler(Looper looper) {
2740 super(looper);
2741 }
2742
2743 @Override
2744 public void handleMessage(Message msg) {
2745 NetworkInfo info;
2746 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002747 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002748 String causedBy = null;
2749 synchronized (ConnectivityService.this) {
2750 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2751 mNetTransitionWakeLock.isHeld()) {
2752 mNetTransitionWakeLock.release();
2753 causedBy = mNetTransitionWakeLockCausedBy;
2754 }
2755 }
2756 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002757 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002758 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002759 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002760 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002761 FeatureUser u = (FeatureUser)msg.obj;
2762 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002763 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002764 case EVENT_INET_CONDITION_CHANGE:
2765 {
2766 int netType = msg.arg1;
2767 int condition = msg.arg2;
2768 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002769 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002770 }
2771 case EVENT_INET_CONDITION_HOLD_END:
2772 {
2773 int netType = msg.arg1;
2774 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002775 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002776 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002777 }
2778 case EVENT_SET_NETWORK_PREFERENCE:
2779 {
2780 int preference = msg.arg1;
2781 handleSetNetworkPreference(preference);
2782 break;
2783 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002784 case EVENT_SET_MOBILE_DATA:
2785 {
2786 boolean enabled = (msg.arg1 == ENABLED);
2787 handleSetMobileData(enabled);
2788 break;
2789 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002790 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2791 {
2792 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002793 break;
2794 }
2795 case EVENT_SET_DEPENDENCY_MET:
2796 {
2797 boolean met = (msg.arg1 == ENABLED);
2798 handleSetDependencyMet(msg.arg2, met);
2799 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002800 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002801 case EVENT_RESTORE_DNS:
2802 {
2803 if (mActiveDefaultNetwork != -1) {
2804 handleDnsConfigurationChange(mActiveDefaultNetwork);
2805 }
2806 break;
2807 }
Wink Saville628b0852011-08-04 15:01:58 -07002808 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2809 {
2810 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002811 sendStickyBroadcast(intent);
2812 break;
2813 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002814 case EVENT_SET_POLICY_DATA_ENABLE: {
2815 final int networkType = msg.arg1;
2816 final boolean enabled = msg.arg2 == ENABLED;
2817 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002818 break;
2819 }
2820 case EVENT_VPN_STATE_CHANGED: {
2821 if (mLockdownTracker != null) {
2822 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2823 }
2824 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827 }
2828 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002829
2830 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002831 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002832 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002833
2834 if (isTetheringSupported()) {
2835 return mTethering.tether(iface);
2836 } else {
2837 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2838 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002839 }
2840
2841 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002842 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002843 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002844
2845 if (isTetheringSupported()) {
2846 return mTethering.untether(iface);
2847 } else {
2848 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2849 }
2850 }
2851
2852 // javadoc from interface
2853 public int getLastTetherError(String iface) {
2854 enforceTetherAccessPermission();
2855
2856 if (isTetheringSupported()) {
2857 return mTethering.getLastTetherError(iface);
2858 } else {
2859 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2860 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002861 }
2862
2863 // TODO - proper iface API for selection by property, inspection, etc
2864 public String[] getTetherableUsbRegexs() {
2865 enforceTetherAccessPermission();
2866 if (isTetheringSupported()) {
2867 return mTethering.getTetherableUsbRegexs();
2868 } else {
2869 return new String[0];
2870 }
2871 }
2872
2873 public String[] getTetherableWifiRegexs() {
2874 enforceTetherAccessPermission();
2875 if (isTetheringSupported()) {
2876 return mTethering.getTetherableWifiRegexs();
2877 } else {
2878 return new String[0];
2879 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002880 }
2881
Danica Chang6fdd0c62010-08-11 14:54:43 -07002882 public String[] getTetherableBluetoothRegexs() {
2883 enforceTetherAccessPermission();
2884 if (isTetheringSupported()) {
2885 return mTethering.getTetherableBluetoothRegexs();
2886 } else {
2887 return new String[0];
2888 }
2889 }
2890
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002891 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002892 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002893 if (isTetheringSupported()) {
2894 return mTethering.setUsbTethering(enable);
2895 } else {
2896 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2897 }
2898 }
2899
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002900 // TODO - move iface listing, queries, etc to new module
2901 // javadoc from interface
2902 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002903 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002904 return mTethering.getTetherableIfaces();
2905 }
2906
2907 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002908 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002909 return mTethering.getTetheredIfaces();
2910 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002911
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002912 @Override
2913 public String[] getTetheredIfacePairs() {
2914 enforceTetherAccessPermission();
2915 return mTethering.getTetheredIfacePairs();
2916 }
2917
Robert Greenwalt5a735062010-03-02 17:25:02 -08002918 public String[] getTetheringErroredIfaces() {
2919 enforceTetherAccessPermission();
2920 return mTethering.getErroredIfaces();
2921 }
2922
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002923 // if ro.tether.denied = true we default to no tethering
2924 // gservices could set the secure setting to 1 though to enable it on a build where it
2925 // had previously been turned off.
2926 public boolean isTetheringSupported() {
2927 enforceTetherAccessPermission();
2928 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002929 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2930 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002931 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002932 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002933
2934 // An API NetworkStateTrackers can call when they lose their network.
2935 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2936 // whichever happens first. The timer is started by the first caller and not
2937 // restarted by subsequent callers.
2938 public void requestNetworkTransitionWakelock(String forWhom) {
2939 enforceConnectivityInternalPermission();
2940 synchronized (this) {
2941 if (mNetTransitionWakeLock.isHeld()) return;
2942 mNetTransitionWakeLockSerialNumber++;
2943 mNetTransitionWakeLock.acquire();
2944 mNetTransitionWakeLockCausedBy = forWhom;
2945 }
2946 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002947 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002948 mNetTransitionWakeLockSerialNumber, 0),
2949 mNetTransitionWakeLockTimeout);
2950 return;
2951 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002952
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002953 // 100 percent is full good, 0 is full bad.
2954 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002955 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002956 mContext.enforceCallingOrSelfPermission(
2957 android.Manifest.permission.STATUS_BAR,
2958 "ConnectivityService");
2959
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002960 if (DBG) {
2961 int pid = getCallingPid();
2962 int uid = getCallingUid();
2963 String s = pid + "(" + uid + ") reports inet is " +
2964 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2965 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2966 mInetLog.add(s);
2967 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2968 mInetLog.remove(0);
2969 }
2970 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002971 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002972 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2973 }
2974
2975 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002976 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002977 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002978 return;
2979 }
2980 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002981 if (DBG) log("handleInetConditionChange: net=" + netType +
2982 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002983 return;
2984 }
Wink Savillec9acde92011-09-21 11:05:43 -07002985 if (VDBG) {
2986 log("handleInetConditionChange: net=" +
2987 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00002988 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07002989 }
Wink Saville5b7573e2013-01-31 00:30:13 +00002990 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002991 int delay;
2992 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002993 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002994 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00002995 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002996 delay = Settings.Global.getInt(mContext.getContentResolver(),
2997 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002998 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002999 delay = Settings.Global.getInt(mContext.getContentResolver(),
3000 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003001 }
3002 mInetConditionChangeInFlight = true;
3003 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003004 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003005 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003006 // we've set the new condition, when this hold ends that will get picked up
3007 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003008 }
3009 }
3010
Wink Saville5b7573e2013-01-31 00:30:13 +00003011 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003012 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003013 log("handleInetConditionHoldEnd: net=" + netType +
3014 ", condition=" + mDefaultInetCondition +
3015 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003016 }
3017 mInetConditionChangeInFlight = false;
3018
3019 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003020 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003021 return;
3022 }
3023 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003024 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003025 return;
3026 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003027 // TODO: Figure out why this optimization sometimes causes a
3028 // change in mDefaultInetCondition to be missed and the
3029 // UI to not be updated.
3030 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3031 // if (DBG) log("no change in condition - aborting");
3032 // return;
3033 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003034 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3035 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003036 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003037 return;
3038 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003039 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003040 sendInetConditionBroadcast(networkInfo);
3041 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003042 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003043
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003044 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003045 // this information is already available as a world read/writable jvm property
3046 // so this API change wouldn't have a benifit. It also breaks the passing
3047 // of proxy info to all the JVMs.
3048 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003049 synchronized (mProxyLock) {
3050 if (mGlobalProxy != null) return mGlobalProxy;
3051 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003052 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003053 }
3054
3055 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003056 enforceConnectivityInternalPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003057 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003058 if (proxyProperties == mGlobalProxy) return;
3059 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3060 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3061
3062 String host = "";
3063 int port = 0;
3064 String exclList = "";
3065 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3066 mGlobalProxy = new ProxyProperties(proxyProperties);
3067 host = mGlobalProxy.getHost();
3068 port = mGlobalProxy.getPort();
3069 exclList = mGlobalProxy.getExclusionList();
3070 } else {
3071 mGlobalProxy = null;
3072 }
3073 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003074 final long token = Binder.clearCallingIdentity();
3075 try {
3076 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3077 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3078 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3079 exclList);
3080 } finally {
3081 Binder.restoreCallingIdentity(token);
3082 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003083 }
3084
3085 if (mGlobalProxy == null) {
3086 proxyProperties = mDefaultProxy;
3087 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003088 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003089 }
3090
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003091 private void loadGlobalProxy() {
3092 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003093 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3094 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3095 String exclList = Settings.Global.getString(res,
3096 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003097 if (!TextUtils.isEmpty(host)) {
3098 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003099 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003100 mGlobalProxy = proxyProperties;
3101 }
3102 }
3103 }
3104
Robert Greenwalt434203a2010-10-11 16:00:27 -07003105 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003106 // this information is already available as a world read/writable jvm property
3107 // so this API change wouldn't have a benifit. It also breaks the passing
3108 // of proxy info to all the JVMs.
3109 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003110 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003111 return mGlobalProxy;
3112 }
3113 }
3114
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003115 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3116 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3117 proxy = null;
3118 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003119 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003120 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003121 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003122 mDefaultProxy = proxy;
3123
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003124 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003125 if (!mDefaultProxyDisabled) {
3126 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003127 }
3128 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003129 }
3130
3131 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003132 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3133 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003134 if (!TextUtils.isEmpty(proxy)) {
3135 String data[] = proxy.split(":");
3136 String proxyHost = data[0];
3137 int proxyPort = 8080;
3138 if (data.length > 1) {
3139 try {
3140 proxyPort = Integer.parseInt(data[1]);
3141 } catch (NumberFormatException e) {
3142 return;
3143 }
3144 }
3145 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3146 setGlobalProxy(p);
3147 }
3148 }
3149
3150 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003151 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003152 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003153 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003154 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3155 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003156 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003157 final long ident = Binder.clearCallingIdentity();
3158 try {
3159 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3160 } finally {
3161 Binder.restoreCallingIdentity(ident);
3162 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003163 }
3164
3165 private static class SettingsObserver extends ContentObserver {
3166 private int mWhat;
3167 private Handler mHandler;
3168 SettingsObserver(Handler handler, int what) {
3169 super(handler);
3170 mHandler = handler;
3171 mWhat = what;
3172 }
3173
3174 void observe(Context context) {
3175 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003176 resolver.registerContentObserver(Settings.Global.getUriFor(
3177 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003178 }
3179
3180 @Override
3181 public void onChange(boolean selfChange) {
3182 mHandler.obtainMessage(mWhat).sendToTarget();
3183 }
3184 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003185
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003186 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003187 Slog.d(TAG, s);
3188 }
3189
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003190 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003191 Slog.e(TAG, s);
3192 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003193
repo syncaea743a2011-07-29 23:55:49 -07003194 int convertFeatureToNetworkType(int networkType, String feature) {
3195 int usedNetworkType = networkType;
3196
3197 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3198 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3199 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3200 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3201 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3202 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3203 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3204 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3205 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3206 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3207 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3208 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3209 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3210 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3211 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3212 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3213 } else {
3214 Slog.e(TAG, "Can't match any mobile netTracker!");
3215 }
3216 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3217 if (TextUtils.equals(feature, "p2p")) {
3218 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3219 } else {
3220 Slog.e(TAG, "Can't match any wifi netTracker!");
3221 }
3222 } else {
3223 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003224 }
repo syncaea743a2011-07-29 23:55:49 -07003225 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003226 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003227
3228 private static <T> T checkNotNull(T value, String message) {
3229 if (value == null) {
3230 throw new NullPointerException(message);
3231 }
3232 return value;
3233 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003234
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003235 /**
3236 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003237 * VpnBuilder and not available in ConnectivityManager. Permissions
3238 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003239 * @hide
3240 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003241 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003242 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003243 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003244 try {
3245 int type = mActiveDefaultNetwork;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003246 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003247 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3248 return true;
3249 }
3250 } catch (Exception e) {
3251 // ignore
3252 } finally {
3253 try {
3254 socket.close();
3255 } catch (Exception e) {
3256 // ignore
3257 }
3258 }
3259 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003260 }
3261
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003262 /**
3263 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003264 * and not available in ConnectivityManager. Permissions are checked
3265 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003266 * @hide
3267 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003268 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003269 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003270 throwIfLockdownEnabled();
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003271 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003272 }
3273
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003274 /**
3275 * Configure a TUN interface and return its file descriptor. Parameters
3276 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003277 * and not available in ConnectivityManager. Permissions are checked in
3278 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003279 * @hide
3280 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003281 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003282 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003283 throwIfLockdownEnabled();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003284 return mVpn.establish(config);
3285 }
3286
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003287 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003288 * Start legacy VPN, controlling native daemons as needed. Creates a
3289 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003290 */
3291 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003292 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003293 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003294 final LinkProperties egress = getActiveLinkProperties();
3295 if (egress == null) {
3296 throw new IllegalStateException("Missing active network connection");
3297 }
3298 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003299 }
3300
3301 /**
3302 * Return the information of the ongoing legacy VPN. This method is used
3303 * by VpnSettings and not available in ConnectivityManager. Permissions
3304 * are checked in Vpn class.
3305 * @hide
3306 */
3307 @Override
3308 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003309 throwIfLockdownEnabled();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003310 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003311 }
3312
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003313 /**
3314 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3315 * through NetworkStateTracker since it works differently. For example, it
3316 * needs to override DNS servers but never takes the default routes. It
3317 * relies on another data network, and it could keep existing connections
3318 * alive after reconnecting, switching between networks, or even resuming
3319 * from deep sleep. Calls from applications should be done synchronously
3320 * to avoid race conditions. As these are all hidden APIs, refactoring can
3321 * be done whenever a better abstraction is developed.
3322 */
3323 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003324 private VpnCallback() {
3325 }
3326
Jeff Sharkey899223b2012-08-04 15:24:58 -07003327 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003328 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003329 }
3330
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003331 public void override(List<String> dnsServers, List<String> searchDomains) {
3332 if (dnsServers == null) {
3333 restore();
3334 return;
3335 }
3336
3337 // Convert DNS servers into addresses.
3338 List<InetAddress> addresses = new ArrayList<InetAddress>();
3339 for (String address : dnsServers) {
3340 // Double check the addresses and remove invalid ones.
3341 try {
3342 addresses.add(InetAddress.parseNumericAddress(address));
3343 } catch (Exception e) {
3344 // ignore
3345 }
3346 }
3347 if (addresses.isEmpty()) {
3348 restore();
3349 return;
3350 }
3351
3352 // Concatenate search domains into a string.
3353 StringBuilder buffer = new StringBuilder();
3354 if (searchDomains != null) {
3355 for (String domain : searchDomains) {
3356 buffer.append(domain).append(' ');
3357 }
3358 }
3359 String domains = buffer.toString().trim();
3360
3361 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003362 synchronized (mDnsLock) {
Mattias Falk8b47b362011-08-23 14:15:13 +02003363 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003364 mDnsOverridden = true;
3365 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003366
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003367 // Temporarily disable the default proxy (not global).
3368 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003369 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003370 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003371 sendProxyBroadcast(null);
3372 }
3373 }
3374
3375 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003376 }
3377
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003378 public void restore() {
3379 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003380 if (mDnsOverridden) {
3381 mDnsOverridden = false;
3382 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003383 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003384 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003385 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003386 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003387 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003388 sendProxyBroadcast(mDefaultProxy);
3389 }
3390 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003391 }
3392 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003393
3394 @Override
3395 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003396 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3397 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3398 return false;
3399 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003400
3401 // Tear down existing lockdown if profile was removed
3402 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3403 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003404 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003405 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3406 return false;
3407 }
3408
3409 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3410 final VpnProfile profile = VpnProfile.decode(
3411 profileName, mKeyStore.get(Credentials.VPN + profileName));
3412 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3413 } else {
3414 setLockdownTracker(null);
3415 }
3416
3417 return true;
3418 }
3419
3420 /**
3421 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3422 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3423 */
3424 private void setLockdownTracker(LockdownVpnTracker tracker) {
3425 // Shutdown any existing tracker
3426 final LockdownVpnTracker existing = mLockdownTracker;
3427 mLockdownTracker = null;
3428 if (existing != null) {
3429 existing.shutdown();
3430 }
3431
3432 try {
3433 if (tracker != null) {
3434 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003435 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003436 mLockdownTracker = tracker;
3437 mLockdownTracker.init();
3438 } else {
3439 mNetd.setFirewallEnabled(false);
3440 }
3441 } catch (RemoteException e) {
3442 // ignored; NMS lives inside system_server
3443 }
3444 }
3445
3446 private void throwIfLockdownEnabled() {
3447 if (mLockdownEnabled) {
3448 throw new IllegalStateException("Unavailable in lockdown mode");
3449 }
3450 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003451
3452 public void supplyMessenger(int networkType, Messenger messenger) {
3453 enforceConnectivityInternalPermission();
3454
3455 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3456 mNetTrackers[networkType].supplyMessenger(messenger);
3457 }
3458 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003459
3460 public int findConnectionTypeForIface(String iface) {
3461 enforceConnectivityInternalPermission();
3462
3463 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3464 for (NetworkStateTracker tracker : mNetTrackers) {
3465 if (tracker != null) {
3466 LinkProperties lp = tracker.getLinkProperties();
3467 if (lp != null && iface.equals(lp.getInterfaceName())) {
3468 return tracker.getNetworkInfo().getType();
3469 }
3470 }
3471 }
3472 return ConnectivityManager.TYPE_NONE;
3473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474}