blob: 0d65cd6d28dff5aac5db7f987014b26b70ae0702 [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
Wink Savilleab9321d2013-06-29 21:10:57 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080037import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090041import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070048import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080050import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080051import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070057import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080058import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070064import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
69import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090073import android.net.wimax.WimaxManagerConstants;
Wink Savilleab9321d2013-06-29 21:10:57 -070074import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.RemoteException;
Wink Savilleab9321d2013-06-29 21:10:57 -070088import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070096import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080098import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070099import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700100import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700101import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Wink Savilleab9321d2013-06-29 21:10:57 -0700103import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400104import com.android.internal.annotations.GuardedBy;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700105import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700107import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.telephony.DctConstants;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700109import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -0700110import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jason Monk602b2322013-07-03 17:04:33 -0400113import com.android.net.IProxyService;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700114import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400115import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900116import com.android.server.connectivity.Nat464Xlat;
Jason Monk602b2322013-07-03 17:04:33 -0400117import com.android.server.connectivity.PacManager;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800118import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700119import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700120import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700121import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700122import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700123import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700124
tk.mun148c7d02011-10-13 22:51:57 +0900125import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import org.xmlpull.v1.XmlPullParser;
128import org.xmlpull.v1.XmlPullParserException;
129
130import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import java.io.FileNotFoundException;
133import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700134import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900136import java.lang.reflect.Constructor;
Wink Savilleab9321d2013-06-29 21:10:57 -0700137import java.net.HttpURLConnection;
Wink Savillec9822c52011-07-14 12:23:28 -0700138import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700139import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700140import java.net.InetAddress;
Wink Savilleab9321d2013-06-29 21:10:57 -0700141import java.net.URL;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700142import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700143import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700144import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700146import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import java.util.List;
Wink Savilleab9321d2013-06-29 21:10:57 -0700149import java.util.Random;
150import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152/**
153 * @hide
154 */
155public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700156 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Robert Greenwaltba175a52010-10-05 19:12:26 -0700158 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700159 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161 private static final boolean LOGD_RULES = false;
162
Jeff Sharkey899223b2012-08-04 15:24:58 -0700163 // TODO: create better separation between radio types and network types
164
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165 // how long to wait before switching back to a radio's default network
166 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
167 // system property that can override the above value
168 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
169 "android.telephony.apn-restore";
170
Wink Savilleab9321d2013-06-29 21:10:57 -0700171 // Default value if FAIL_FAST_TIME_MS is not set
172 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
173 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
174 private static final String FAIL_FAST_TIME_MS =
175 "persist.radio.fail_fast_time_ms";
176
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700177 // used in recursive route setting to add gateways for the host for which
178 // a host route was requested.
179 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
180
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800181 private Tethering mTethering;
182
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700183 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700184
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700185 @GuardedBy("mVpns")
186 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey899223b2012-08-04 15:24:58 -0700187 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700188
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700189 private boolean mLockdownEnabled;
190 private LockdownVpnTracker mLockdownTracker;
191
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900192 private Nat464Xlat mClat;
193
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
195 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196 /** Currently active network rules by UID. */
197 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700198 /** Set of ifaces that are costly. */
199 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 /**
202 * Sometimes we want to refer to the individual network state
203 * trackers separately, and sometimes we just want to treat them
204 * abstractly.
205 */
206 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700207
Irfan Sheriffda6da092012-08-16 12:49:23 -0700208 /* Handles captive portal check on a network */
209 private CaptivePortalTracker mCaptivePortalTracker;
210
Robert Greenwalt42acef32009-08-12 16:08:25 -0700211 /**
Wink Savillee8222252011-07-13 13:44:13 -0700212 * The link properties that define the current links
213 */
214 private LinkProperties mCurrentLinkProperties[];
215
216 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700217 * A per Net list of the PID's that requested access to the net
218 * used both as a refcount and for per-PID DNS selection
219 */
Mattias Falk8b47b362011-08-23 14:15:13 +0200220 private List<Integer> mNetRequestersPids[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700221
Robert Greenwalt42acef32009-08-12 16:08:25 -0700222 // priority order of the nettrackers
223 // (excluding dynamically set mNetworkPreference)
224 // TODO - move mNetworkTypePreference into this
225 private int[] mPriorityList;
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private Context mContext;
228 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700229 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700230 // 0 is full bad, 100 is full good
Wink Saville5b7573e2013-01-31 00:30:13 +0000231 private int mDefaultInetCondition = 0;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700232 private int mDefaultInetConditionPublished = 0;
233 private boolean mInetConditionChangeInFlight = false;
234 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700236 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800237 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
239 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700240 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700242 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700243 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700244
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245 private static final int ENABLED = 1;
246 private static final int DISABLED = 0;
247
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700248 private static final boolean ADD = true;
249 private static final boolean REMOVE = false;
250
251 private static final boolean TO_DEFAULT_TABLE = true;
252 private static final boolean TO_SECONDARY_TABLE = false;
253
Chad Brubakerf336d722013-07-15 16:34:04 -0700254 private static final boolean EXEMPT = true;
255 private static final boolean UNEXEMPT = false;
256
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257 /**
258 * used internally as a delayed event to make us switch back to the
259 * default network
260 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700261 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700262
263 /**
264 * used internally to change our mobile data enabled flag
265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267
268 /**
269 * used internally to change our network preference setting
270 * arg1 = networkType to prefer
271 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700272 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273
274 /**
275 * used internally to synchronize inet condition reports
276 * arg1 = networkType
277 * arg2 = condition (0 bad, 100 good)
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700280
281 /**
282 * used internally to mark the end of inet condition hold periods
283 * arg1 = networkType
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700286
287 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700288 * used internally to set enable/disable cellular data
289 * arg1 = ENBALED or DISABLED
290 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700291 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700292
Robert Greenwaltf3331232010-09-24 14:32:21 -0700293 /**
294 * used internally to clear a wakelock when transitioning
295 * from one net to another
296 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700297 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700298
Robert Greenwalt434203a2010-10-11 16:00:27 -0700299 /**
300 * used internally to reload global proxy settings
301 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700302 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700303
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700304 /**
305 * used internally to set external dependency met/unmet
306 * arg1 = ENABLED (met) or DISABLED (unmet)
307 * arg2 = NetworkType
308 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700309 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700310
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700311 /**
Wink Saville628b0852011-08-04 15:01:58 -0700312 * used internally to send a sticky broadcast delayed.
313 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700314 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700315
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700316 /**
317 * Used internally to
318 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
319 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700320 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321
Chad Brubakerb98703e2013-07-23 17:44:41 -0700322 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700323
Wink Savilleab9321d2013-06-29 21:10:57 -0700324 /**
325 * Used internally to disable fail fast of mobile data
326 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700327 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Savilleab9321d2013-06-29 21:10:57 -0700328
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700329 /** Handler used for internal events. */
330 private InternalHandler mHandler;
331 /** Handler used for incoming {@link NetworkStateTracker} events. */
332 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700333
334 // list of DeathRecipients used to make sure features are turned off when
335 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500336 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700337
Mike Lockwood0f79b542009-08-14 14:18:49 -0400338 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800339 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400340
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700341 private PowerManager.WakeLock mNetTransitionWakeLock;
342 private String mNetTransitionWakeLockCausedBy = "";
343 private int mNetTransitionWakeLockSerialNumber;
344 private int mNetTransitionWakeLockTimeout;
345
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700346 private InetAddress mDefaultDns;
347
Chad Brubakerf336d722013-07-15 16:34:04 -0700348 // Lock for protecting access to mAddedRoutes and mExemptAddresses
349 private final Object mRoutesLock = new Object();
350
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700351 // this collection is used to refcount the added routes - if there are none left
352 // it's time to remove the route from the route table
Chad Brubakerf336d722013-07-15 16:34:04 -0700353 @GuardedBy("mRoutesLock")
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700354 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
355
Chad Brubakerf336d722013-07-15 16:34:04 -0700356 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
357 // used to handle cleanup of exempt rules
358 @GuardedBy("mRoutesLock")
359 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
360
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700361 // used in DBG mode to track inet condition reports
362 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
363 private ArrayList mInetLog;
364
Robert Greenwalt434203a2010-10-11 16:00:27 -0700365 // track the current default http proxy - tell the world if we get a new one (real change)
366 private ProxyProperties mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700367 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700368 private boolean mDefaultProxyDisabled = false;
369
Robert Greenwalt434203a2010-10-11 16:00:27 -0700370 // track the global proxy.
371 private ProxyProperties mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700372
Jason Monk602b2322013-07-03 17:04:33 -0400373 private PacManager mPacManager = null;
374
Robert Greenwalt434203a2010-10-11 16:00:27 -0700375 private SettingsObserver mSettingsObserver;
376
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700377 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700378 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700379
Robert Greenwalt511288a2009-12-07 11:33:18 -0800380 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700381 public int mSimultaneity;
382 public int mType;
383 public RadioAttributes(String init) {
384 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700385 mType = Integer.parseInt(fragments[0]);
386 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700387 }
388 }
389 RadioAttributes[] mRadioAttributes;
390
Robert Greenwalt50393202011-06-21 17:26:14 -0700391 // the set of network types that can only be enabled by system/sig apps
392 List mProtectedNetworks;
393
John Spurlockbf991a82013-06-24 14:20:23 -0400394 private DataConnectionStats mDataConnectionStats;
Wink Savilleab9321d2013-06-29 21:10:57 -0700395 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
396
397 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400398
Wink Savillefde1ac92013-07-16 17:16:37 -0700399 // We only want one checkMobileProvisioning after booting.
400 volatile boolean mFirstProvisioningCheckStarted = false;
401
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700402 public ConnectivityService(Context context, INetworkManagementService netd,
403 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700404 // Currently, omitting a NetworkFactory will create one internally
405 // TODO: create here when we have cleaner WiMAX support
406 this(context, netd, statsService, policyManager, null);
407 }
408
Jeff Sharkey899223b2012-08-04 15:24:58 -0700409 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700410 INetworkStatsService statsService, INetworkPolicyManager policyManager,
411 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800412 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800413
Wink Savillebb08caf2010-09-02 19:23:52 -0700414 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
415 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700416 mHandler = new InternalHandler(handlerThread.getLooper());
417 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700418
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700419 if (netFactory == null) {
420 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
421 }
422
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800423 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800424 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
425 String id = Settings.Secure.getString(context.getContentResolver(),
426 Settings.Secure.ANDROID_ID);
427 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700428 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800429 SystemProperties.set("net.hostname", name);
430 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800431 }
432
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700433 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700434 String dns = Settings.Global.getString(context.getContentResolver(),
435 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700436 if (dns == null || dns.length() == 0) {
437 dns = context.getResources().getString(
438 com.android.internal.R.string.config_default_dns_server);
439 }
440 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800441 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
442 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800443 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700444 }
445
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700446 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700447 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700448 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700449 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700450 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700451
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700452 try {
453 mPolicyManager.registerListener(mPolicyListener);
454 } catch (RemoteException e) {
455 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700456 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700457 }
458
459 final PowerManager powerManager = (PowerManager) context.getSystemService(
460 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700461 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
462 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
463 com.android.internal.R.integer.config_networkTransitionTimeout);
464
Robert Greenwalt42acef32009-08-12 16:08:25 -0700465 mNetTrackers = new NetworkStateTracker[
466 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700467 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700468
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700469 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700470 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700471
Robert Greenwalt42acef32009-08-12 16:08:25 -0700472 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700473 String[] raStrings = context.getResources().getStringArray(
474 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700475 for (String raString : raStrings) {
476 RadioAttributes r = new RadioAttributes(raString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700477 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700478 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800479 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700480 continue;
481 }
482 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800483 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700484 r.mType);
485 continue;
486 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700487 mRadioAttributes[r.mType] = r;
488 }
489
Wink Saville51f456f2013-04-23 14:26:51 -0700490 // TODO: What is the "correct" way to do determine if this is a wifi only device?
491 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
492 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700493 String[] naStrings = context.getResources().getStringArray(
494 com.android.internal.R.array.networkAttributes);
495 for (String naString : naStrings) {
496 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700497 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700498 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700499 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800500 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700501 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700502 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700503 }
Wink Saville51f456f2013-04-23 14:26:51 -0700504 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
505 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
506 n.type);
507 continue;
508 }
Wink Saville975c8482011-04-07 14:23:45 -0700509 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800510 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700511 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700512 continue;
513 }
Wink Saville975c8482011-04-07 14:23:45 -0700514 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800515 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700516 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700517 continue;
518 }
Wink Saville975c8482011-04-07 14:23:45 -0700519 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700520 mNetworksDefined++;
521 } catch(Exception e) {
522 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700523 }
524 }
Wink Saville5e56bc52013-07-29 15:00:57 -0700525 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700526
Robert Greenwalt50393202011-06-21 17:26:14 -0700527 mProtectedNetworks = new ArrayList<Integer>();
528 int[] protectedNetworks = context.getResources().getIntArray(
529 com.android.internal.R.array.config_protectedNetworks);
530 for (int p : protectedNetworks) {
531 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
532 mProtectedNetworks.add(p);
533 } else {
534 if (DBG) loge("Ignoring protectedNetwork " + p);
535 }
536 }
537
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700538 // high priority first
539 mPriorityList = new int[mNetworksDefined];
540 {
541 int insertionPoint = mNetworksDefined-1;
542 int currentLowest = 0;
543 int nextLowest = 0;
544 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700545 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700546 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700547 if (na.priority < currentLowest) continue;
548 if (na.priority > currentLowest) {
549 if (na.priority < nextLowest || nextLowest == 0) {
550 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700551 }
552 continue;
553 }
Wink Saville975c8482011-04-07 14:23:45 -0700554 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700555 }
556 currentLowest = nextLowest;
557 nextLowest = 0;
558 }
559 }
560
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800561 // Update mNetworkPreference according to user mannually first then overlay config.xml
562 mNetworkPreference = getPersistedNetworkPreference();
563 if (mNetworkPreference == -1) {
564 for (int n : mPriorityList) {
565 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
566 mNetworkPreference = n;
567 break;
568 }
569 }
570 if (mNetworkPreference == -1) {
571 throw new IllegalStateException(
572 "You should set at least one default Network in config.xml!");
573 }
574 }
575
Mattias Falk8b47b362011-08-23 14:15:13 +0200576 mNetRequestersPids =
577 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700578 for (int i : mPriorityList) {
Mattias Falk8b47b362011-08-23 14:15:13 +0200579 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700580 }
581
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500582 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700583
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700584 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
585 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700586
587 // Create and start trackers for hard-coded networks
588 for (int targetNetworkType : mPriorityList) {
589 final NetworkConfig config = mNetConfigs[targetNetworkType];
590 final NetworkStateTracker tracker;
591 try {
592 tracker = netFactory.createTracker(targetNetworkType, config);
593 mNetTrackers[targetNetworkType] = tracker;
594 } catch (IllegalArgumentException e) {
595 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
596 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700597 continue;
598 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700599
600 tracker.startMonitoring(context, mTrackerHandler);
601 if (config.isDefault()) {
602 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800603 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700604 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800605
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700606 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800607
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700608 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700609 IntentFilter intentFilter = new IntentFilter();
610 intentFilter.addAction(Intent.ACTION_USER_STARTING);
611 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
612 mContext.registerReceiverAsUser(
613 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900614 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
615
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700616 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700617 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700618 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900619 mNetd.registerObserver(mClat);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700620 } catch (RemoteException e) {
621 loge("Error registering observer :" + e);
622 }
623
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700624 if (DBG) {
625 mInetLog = new ArrayList();
626 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700627
628 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
629 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800630
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700631 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800632 loadGlobalProxy();
John Spurlockbf991a82013-06-24 14:20:23 -0400633
634 mDataConnectionStats = new DataConnectionStats(mContext);
635 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400636
637 mPacManager = new PacManager(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700639
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700640 /**
641 * Factory that creates {@link NetworkStateTracker} instances using given
642 * {@link NetworkConfig}.
643 */
644 public interface NetworkFactory {
645 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
646 }
647
648 private static class DefaultNetworkFactory implements NetworkFactory {
649 private final Context mContext;
650 private final Handler mTrackerHandler;
651
652 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
653 mContext = context;
654 mTrackerHandler = trackerHandler;
655 }
656
657 @Override
658 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
659 switch (config.radio) {
660 case TYPE_WIFI:
661 return new WifiStateTracker(targetNetworkType, config.name);
662 case TYPE_MOBILE:
663 return new MobileDataStateTracker(targetNetworkType, config.name);
664 case TYPE_DUMMY:
665 return new DummyDataStateTracker(targetNetworkType, config.name);
666 case TYPE_BLUETOOTH:
667 return BluetoothTetheringDataTracker.getInstance();
668 case TYPE_WIMAX:
669 return makeWimaxStateTracker(mContext, mTrackerHandler);
670 case TYPE_ETHERNET:
671 return EthernetDataTracker.getInstance();
672 default:
673 throw new IllegalArgumentException(
674 "Trying to create a NetworkStateTracker for an unknown radio type: "
675 + config.radio);
676 }
677 }
678 }
679
680 /**
681 * Loads external WiMAX library and registers as system service, returning a
682 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
683 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
684 */
685 private static NetworkStateTracker makeWimaxStateTracker(
686 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700687 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900688 DexClassLoader wimaxClassLoader;
689 Class wimaxStateTrackerClass = null;
690 Class wimaxServiceClass = null;
691 Class wimaxManagerClass;
692 String wimaxJarLocation;
693 String wimaxLibLocation;
694 String wimaxManagerClassName;
695 String wimaxServiceClassName;
696 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697
tk.mun148c7d02011-10-13 22:51:57 +0900698 NetworkStateTracker wimaxStateTracker = null;
699
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700700 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900701 com.android.internal.R.bool.config_wimaxEnabled);
702
703 if (isWimaxEnabled) {
704 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700705 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900706 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700707 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900708 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700709 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900710 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700711 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900712 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700713 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900714 com.android.internal.R.string.config_wimaxStateTrackerClassname);
715
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800716 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900717 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700718 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900719 wimaxLibLocation, ClassLoader.getSystemClassLoader());
720
721 try {
722 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
723 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
724 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
725 } catch (ClassNotFoundException ex) {
726 loge("Exception finding Wimax classes: " + ex.toString());
727 return null;
728 }
729 } catch(Resources.NotFoundException ex) {
730 loge("Wimax Resources does not exist!!! ");
731 return null;
732 }
733
734 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800735 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900736
737 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
738 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700739 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
740 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900741
742 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
743 (new Class[] {Context.class, wimaxStateTrackerClass});
744 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700745 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900746 wmxSrvConst.setAccessible(false);
747
748 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
749
750 } catch(Exception ex) {
751 loge("Exception creating Wimax classes: " + ex.toString());
752 return null;
753 }
754 } else {
755 loge("Wimax is not enabled or not added to the network attributes!!! ");
756 return null;
757 }
758
759 return wimaxStateTracker;
760 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700763 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 * @param preference the new preference
765 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700766 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700768
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700769 mHandler.sendMessage(
770 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
772
773 public int getNetworkPreference() {
774 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700775 int preference;
776 synchronized(this) {
777 preference = mNetworkPreference;
778 }
779 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
781
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700782 private void handleSetNetworkPreference(int preference) {
783 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700784 mNetConfigs[preference] != null &&
785 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700786 if (mNetworkPreference != preference) {
787 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700788 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700789 synchronized(this) {
790 mNetworkPreference = preference;
791 }
792 enforcePreference();
793 }
794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700796
Wink Saville628b0852011-08-04 15:01:58 -0700797 private int getConnectivityChangeDelay() {
798 final ContentResolver cr = mContext.getContentResolver();
799
800 /** Check system properties for the default value then use secure settings value, if any. */
801 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700802 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
803 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
804 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700805 defaultDelay);
806 }
807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 private int getPersistedNetworkPreference() {
809 final ContentResolver cr = mContext.getContentResolver();
810
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700811 final int networkPrefSetting = Settings.Global
812 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813
Jianzheng Zhoudcf03f32012-11-16 13:45:20 +0800814 return networkPrefSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700818 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 * In this method, we only tear down a non-preferred network. Establishing
820 * a connection to the preferred network is taken care of when we handle
821 * the disconnect event from the non-preferred network
822 * (see {@link #handleDisconnect(NetworkInfo)}).
823 */
824 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700825 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 return;
827
Robert Greenwalt42acef32009-08-12 16:08:25 -0700828 if (!mNetTrackers[mNetworkPreference].isAvailable())
829 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830
Robert Greenwalt42acef32009-08-12 16:08:25 -0700831 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700832 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700833 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700834 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800835 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700836 " in enforcePreference");
837 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700838 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840 }
841 }
842
843 private boolean teardown(NetworkStateTracker netTracker) {
844 if (netTracker.teardown()) {
845 netTracker.setTeardownRequested(true);
846 return true;
847 } else {
848 return false;
849 }
850 }
851
852 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700853 * Check if UID should be blocked from using the network represented by the
854 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700855 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700856 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
857 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700858
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700859 final boolean networkCostly;
860 final int uidRules;
861 synchronized (mRulesLock) {
862 networkCostly = mMeteredIfaces.contains(iface);
863 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700864 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700865
866 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
867 return true;
868 }
869
870 // no restrictive rules; network is visible
871 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700872 }
873
874 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700875 * Return a filtered {@link NetworkInfo}, potentially marked
876 * {@link DetailedState#BLOCKED} based on
877 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700878 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700879 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
880 NetworkInfo info = tracker.getNetworkInfo();
881 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700882 // network is blocked; clone and override state
883 info = new NetworkInfo(info);
884 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700885 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700886 if (mLockdownTracker != null) {
887 info = mLockdownTracker.augmentNetworkInfo(info);
888 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700889 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700890 }
891
892 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 * Return NetworkInfo for the active (i.e., connected) network interface.
894 * It is assumed that at most one network is active at a time. If more
895 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700896 * @return the info for the active network, or {@code null} if none is
897 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700899 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700901 enforceAccessPermission();
902 final int uid = Binder.getCallingUid();
903 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 }
905
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700906 public NetworkInfo getActiveNetworkInfoUnfiltered() {
907 enforceAccessPermission();
908 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
909 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
910 if (tracker != null) {
911 return tracker.getNetworkInfo();
912 }
913 }
914 return null;
915 }
916
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700917 @Override
918 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
919 enforceConnectivityInternalPermission();
920 return getNetworkInfo(mActiveDefaultNetwork, uid);
921 }
922
923 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 public NetworkInfo getNetworkInfo(int networkType) {
925 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700926 final int uid = Binder.getCallingUid();
927 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 }
929
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700930 private NetworkInfo getNetworkInfo(int networkType, int uid) {
931 NetworkInfo info = null;
932 if (isNetworkTypeValid(networkType)) {
933 final NetworkStateTracker tracker = mNetTrackers[networkType];
934 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700935 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700936 }
937 }
938 return info;
939 }
940
941 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 public NetworkInfo[] getAllNetworkInfo() {
943 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700944 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700945 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700946 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 for (NetworkStateTracker tracker : mNetTrackers) {
948 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700949 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700950 }
951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700953 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700956 @Override
957 public boolean isNetworkSupported(int networkType) {
958 enforceAccessPermission();
959 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
960 }
961
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700962 /**
963 * Return LinkProperties for the active (i.e., connected) default
964 * network interface. It is assumed that at most one default network
965 * is active at a time. If more than one is active, it is indeterminate
966 * which will be returned.
967 * @return the ip properties for the active network, or {@code null} if
968 * none is active
969 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700970 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700971 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700972 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700973 }
974
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700975 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700976 public LinkProperties getLinkProperties(int networkType) {
977 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 if (isNetworkTypeValid(networkType)) {
979 final NetworkStateTracker tracker = mNetTrackers[networkType];
980 if (tracker != null) {
981 return tracker.getLinkProperties();
982 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700983 }
984 return null;
985 }
986
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700987 @Override
988 public NetworkState[] getAllNetworkState() {
989 enforceAccessPermission();
990 final int uid = Binder.getCallingUid();
991 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700992 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700993 for (NetworkStateTracker tracker : mNetTrackers) {
994 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700995 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700996 result.add(new NetworkState(
997 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
998 }
999 }
1000 }
1001 return result.toArray(new NetworkState[result.size()]);
1002 }
1003
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001004 private NetworkState getNetworkStateUnchecked(int networkType) {
1005 if (isNetworkTypeValid(networkType)) {
1006 final NetworkStateTracker tracker = mNetTrackers[networkType];
1007 if (tracker != null) {
1008 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1009 tracker.getLinkCapabilities());
1010 }
1011 }
1012 return null;
1013 }
1014
1015 @Override
1016 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1017 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001018
1019 final long token = Binder.clearCallingIdentity();
1020 try {
1021 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1022 if (state != null) {
1023 try {
1024 return mPolicyManager.getNetworkQuotaInfo(state);
1025 } catch (RemoteException e) {
1026 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001027 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001028 return null;
1029 } finally {
1030 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001031 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001032 }
1033
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001034 @Override
1035 public boolean isActiveNetworkMetered() {
1036 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001037 final long token = Binder.clearCallingIdentity();
1038 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001039 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001040 } finally {
1041 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001042 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001043 }
1044
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001045 private boolean isNetworkMeteredUnchecked(int networkType) {
1046 final NetworkState state = getNetworkStateUnchecked(networkType);
1047 if (state != null) {
1048 try {
1049 return mPolicyManager.isNetworkMetered(state);
1050 } catch (RemoteException e) {
1051 }
1052 }
1053 return false;
1054 }
1055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 public boolean setRadios(boolean turnOn) {
1057 boolean result = true;
1058 enforceChangePermission();
1059 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001060 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
1062 return result;
1063 }
1064
1065 public boolean setRadio(int netType, boolean turnOn) {
1066 enforceChangePermission();
1067 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1068 return false;
1069 }
1070 NetworkStateTracker tracker = mNetTrackers[netType];
1071 return tracker != null && tracker.setRadio(turnOn);
1072 }
1073
Jeff Sharkey216c1812012-08-05 14:29:23 -07001074 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1075 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -07001076 public void interfaceClassDataActivityChanged(String label, boolean active) {
1077 int deviceType = Integer.parseInt(label);
1078 sendDataActivityBroadcast(deviceType, active);
1079 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001080 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001081
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001082 /**
1083 * Used to notice when the calling process dies so we can self-expire
1084 *
1085 * Also used to know if the process has cleaned up after itself when
1086 * our auto-expire timer goes off. The timer has a link to an object.
1087 *
1088 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001089 private class FeatureUser implements IBinder.DeathRecipient {
1090 int mNetworkType;
1091 String mFeature;
1092 IBinder mBinder;
1093 int mPid;
1094 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001095 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001096
1097 FeatureUser(int type, String feature, IBinder binder) {
1098 super();
1099 mNetworkType = type;
1100 mFeature = feature;
1101 mBinder = binder;
1102 mPid = getCallingPid();
1103 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001104 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001105
Robert Greenwalt42acef32009-08-12 16:08:25 -07001106 try {
1107 mBinder.linkToDeath(this, 0);
1108 } catch (RemoteException e) {
1109 binderDied();
1110 }
1111 }
1112
1113 void unlinkDeathRecipient() {
1114 mBinder.unlinkToDeath(this, 0);
1115 }
1116
1117 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001118 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001119 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1120 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001121 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001122 }
1123
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001124 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001125 if (VDBG) {
1126 log("ConnectivityService FeatureUser expire(" +
1127 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1128 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1129 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001130 stopUsingNetworkFeature(this, false);
1131 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001132
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001133 public boolean isSameUser(FeatureUser u) {
1134 if (u == null) return false;
1135
1136 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1137 }
1138
1139 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1140 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1141 TextUtils.equals(mFeature, feature)) {
1142 return true;
1143 }
1144 return false;
1145 }
1146
Robert Greenwaltb9285352009-12-21 18:24:07 -08001147 public String toString() {
1148 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1149 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1150 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001151 }
1152
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001153 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001154 public int startUsingNetworkFeature(int networkType, String feature,
1155 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001156 long startTime = 0;
1157 if (DBG) {
1158 startTime = SystemClock.elapsedRealtime();
1159 }
Wink Savillec9acde92011-09-21 11:05:43 -07001160 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001161 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1162 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001165 try {
1166 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1167 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001168 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001169 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001170
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001171 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001172
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001173 // TODO - move this into individual networktrackers
1174 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001175
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001176 if (mLockdownEnabled) {
1177 // Since carrier APNs usually aren't available from VPN
1178 // endpoint, mark them as unavailable.
1179 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1180 }
1181
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001182 if (mProtectedNetworks.contains(usedNetworkType)) {
1183 enforceConnectivityInternalPermission();
1184 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001185
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001186 // if UID is restricted, don't allow them to bring up metered APNs
1187 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1188 final int uidRules;
1189 synchronized (mRulesLock) {
1190 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1191 }
1192 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001193 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001194 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001195
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001196 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1197 if (network != null) {
1198 Integer currentPid = new Integer(getCallingPid());
1199 if (usedNetworkType != networkType) {
1200 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001201
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001202 if (ni.isAvailable() == false) {
1203 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1204 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001205 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001206 } else {
1207 // else make the attempt anyway - probably giving REQUEST_STARTED below
1208 if (DBG) {
1209 log("special network not available, but try anyway ni=" +
1210 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001211 }
1212 }
1213 }
1214
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001215 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001216
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001217 synchronized(this) {
1218 boolean addToList = true;
1219 if (restoreTimer < 0) {
1220 // In case there is no timer is specified for the feature,
1221 // make sure we don't add duplicate entry with the same request.
1222 for (FeatureUser u : mFeatureUsers) {
1223 if (u.isSameUser(f)) {
1224 // Duplicate user is found. Do not add.
1225 addToList = false;
1226 break;
1227 }
1228 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001229 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001230
1231 if (addToList) mFeatureUsers.add(f);
1232 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1233 // this gets used for per-pid dns when connected
1234 mNetRequestersPids[usedNetworkType].add(currentPid);
1235 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001236 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001237
1238 if (restoreTimer >= 0) {
1239 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1240 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1241 }
1242
1243 if ((ni.isConnectedOrConnecting() == true) &&
1244 !network.isTeardownRequested()) {
1245 if (ni.isConnected() == true) {
1246 final long token = Binder.clearCallingIdentity();
1247 try {
1248 // add the pid-specific dns
1249 handleDnsConfigurationChange(usedNetworkType);
1250 if (VDBG) log("special network already active");
1251 } finally {
1252 Binder.restoreCallingIdentity(token);
1253 }
Wink Savillea639b312012-07-10 12:37:54 -07001254 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001255 }
1256 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001257 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001258 }
1259
1260 // check if the radio in play can make another contact
1261 // assume if cannot for now
1262
1263 if (DBG) {
1264 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1265 feature);
1266 }
Mikael Hedegren342a7cb2012-12-14 15:52:52 +01001267 if (network.reconnect()) {
1268 return PhoneConstants.APN_REQUEST_STARTED;
1269 } else {
1270 return PhoneConstants.APN_REQUEST_FAILED;
1271 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001272 } else {
1273 // need to remember this unsupported request so we respond appropriately on stop
1274 synchronized(this) {
1275 mFeatureUsers.add(f);
1276 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1277 // this gets used for per-pid dns when connected
1278 mNetRequestersPids[usedNetworkType].add(currentPid);
1279 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001280 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001281 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001282 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001283 }
Wink Savillea639b312012-07-10 12:37:54 -07001284 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001285 } finally {
1286 if (DBG) {
1287 final long execTime = SystemClock.elapsedRealtime() - startTime;
1288 if (execTime > 250) {
1289 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1290 } else {
1291 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1292 }
1293 }
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
1296
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001297 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001299 enforceChangePermission();
1300
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001301 int pid = getCallingPid();
1302 int uid = getCallingUid();
1303
1304 FeatureUser u = null;
1305 boolean found = false;
1306
1307 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001308 for (FeatureUser x : mFeatureUsers) {
1309 if (x.isSameUser(pid, uid, networkType, feature)) {
1310 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001311 found = true;
1312 break;
1313 }
1314 }
1315 }
1316 if (found && u != null) {
1317 // stop regardless of how many other time this proc had called start
1318 return stopUsingNetworkFeature(u, true);
1319 } else {
1320 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001321 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001322 return 1;
1323 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001324 }
1325
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001326 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1327 int networkType = u.mNetworkType;
1328 String feature = u.mFeature;
1329 int pid = u.mPid;
1330 int uid = u.mUid;
1331
1332 NetworkStateTracker tracker = null;
1333 boolean callTeardown = false; // used to carry our decision outside of sync block
1334
Wink Savillec9acde92011-09-21 11:05:43 -07001335 if (VDBG) {
1336 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001337 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001340 if (DBG) {
1341 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1342 ", net is invalid");
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 return -1;
1345 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001346
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001347 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1348 // sync block
1349 synchronized(this) {
1350 // check if this process still has an outstanding start request
1351 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001352 if (VDBG) {
1353 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1354 ", ignoring");
1355 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001356 return 1;
1357 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001358 u.unlinkDeathRecipient();
1359 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1360 // If we care about duplicate requests, check for that here.
1361 //
1362 // This is done to support the extension of a request - the app
1363 // can request we start the network feature again and renew the
1364 // auto-shutoff delay. Normal "stop" calls from the app though
1365 // do not pay attention to duplicate requests - in effect the
1366 // API does not refcount and a single stop will counter multiple starts.
1367 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001368 for (FeatureUser x : mFeatureUsers) {
1369 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001370 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001371 return 1;
1372 }
1373 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001374 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001375
repo syncaea743a2011-07-29 23:55:49 -07001376 // TODO - move to individual network trackers
1377 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1378
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001379 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001380 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001381 if (DBG) {
1382 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1383 " no known tracker for used net type " + usedNetworkType);
1384 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001385 return -1;
1386 }
1387 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001388 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001389 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt9055ae32013-02-12 17:18:25 -08001390
1391 final long token = Binder.clearCallingIdentity();
1392 try {
1393 reassessPidDns(pid, true);
1394 } finally {
1395 Binder.restoreCallingIdentity(token);
1396 }
Mattias Falk8b47b362011-08-23 14:15:13 +02001397 flushVmDnsCache();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001398 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001399 if (VDBG) {
1400 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1401 " others still using it");
1402 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001403 return 1;
1404 }
1405 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001406 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001407 if (DBG) {
1408 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1409 " not a known feature - dropping");
1410 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001411 }
1412 }
Wink Savillec9acde92011-09-21 11:05:43 -07001413
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001414 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001415 if (DBG) {
1416 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1417 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001418 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001419 return 1;
1420 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001421 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424
1425 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001426 * @deprecated use requestRouteToHostAddress instead
1427 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 * Ensure that a network route exists to deliver traffic to the specified
1429 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001430 * @param networkType the type of the network over which traffic to the
1431 * specified host is to be routed
1432 * @param hostAddress the IP address of the host to which the route is
1433 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 * @return {@code true} on success, {@code false} on failure
1435 */
1436 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001437 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1438
1439 if (inetAddress == null) {
1440 return false;
1441 }
1442
1443 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1444 }
1445
1446 /**
1447 * Ensure that a network route exists to deliver traffic to the specified
1448 * host via the specified network interface.
1449 * @param networkType the type of the network over which traffic to the
1450 * specified host is to be routed
1451 * @param hostAddress the IP address of the host to which the route is
1452 * desired
1453 * @return {@code true} on success, {@code false} on failure
1454 */
1455 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001457 if (mProtectedNetworks.contains(networkType)) {
1458 enforceConnectivityInternalPermission();
1459 }
1460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001462 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 return false;
1464 }
1465 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001466 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001467
Irfan Sheriffda6da092012-08-16 12:49:23 -07001468 if (tracker == null || (netState != DetailedState.CONNECTED &&
1469 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001470 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001471 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001472 log("requestRouteToHostAddress on down network "
1473 + "(" + networkType + ") - dropped"
1474 + " tracker=" + tracker
1475 + " netState=" + netState
1476 + " isTeardownRequested="
1477 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001478 }
1479 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001481 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001482 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001483 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001484 LinkProperties lp = tracker.getLinkProperties();
Chad Brubakerf336d722013-07-15 16:34:04 -07001485 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Savilleab9321d2013-06-29 21:10:57 -07001486 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1487 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001488 } catch (UnknownHostException e) {
1489 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1490 } finally {
1491 Binder.restoreCallingIdentity(token);
1492 }
Wink Savilleab9321d2013-06-29 21:10:57 -07001493 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001494 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001495 }
1496
Chad Brubakerf336d722013-07-15 16:34:04 -07001497 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1498 boolean exempt) {
1499 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001500 }
1501
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001502 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001503 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001504 }
1505
Chad Brubakerf336d722013-07-15 16:34:04 -07001506 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1507 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001508 }
1509
1510 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001511 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001512 }
1513
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001514 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubakerf336d722013-07-15 16:34:04 -07001515 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001516 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001517 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001518 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001519 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001520 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001521 if (bestRoute.getGateway().equals(addr)) {
1522 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001523 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001524 } else {
1525 // if we will connect to this through another route, add a direct route
1526 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001527 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001528 }
1529 }
Chad Brubakerf336d722013-07-15 16:34:04 -07001530 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001531 }
1532
Lorenzo Colitti2adea7f2013-03-12 07:39:59 +09001533 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubakerf336d722013-07-15 16:34:04 -07001534 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001535 if ((lp == null) || (r == null)) {
1536 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001537 return false;
1538 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001539
1540 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001541 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001542 return false;
1543 }
1544
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001545 String ifaceName = r.getInterface();
1546 if(ifaceName == null) {
1547 loge("Error modifying route - no interface name");
1548 return false;
1549 }
Robert Greenwaltca441ee2013-04-11 13:48:16 -07001550 if (r.hasGateway()) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001551 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001552 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001553 if (bestRoute.getGateway().equals(r.getGateway())) {
1554 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001555 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt476f5522011-07-15 09:45:08 -07001556 } else {
1557 // if we will connect to our gateway through another route, add a direct
1558 // route to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001559 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1560 bestRoute.getGateway(),
1561 ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001562 }
Chad Brubakerf336d722013-07-15 16:34:04 -07001563 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001564 }
1565 }
1566 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001567 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001568 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001569 if (toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001570 synchronized (mRoutesLock) {
1571 // only track default table - only one apps can effect
1572 mAddedRoutes.add(r);
1573 mNetd.addRoute(ifaceName, r);
1574 if (exempt) {
1575 LinkAddress dest = r.getDestination();
1576 if (!mExemptAddresses.contains(dest)) {
1577 mNetd.setHostExemption(dest);
1578 mExemptAddresses.add(dest);
1579 }
1580 }
1581 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001582 } else {
1583 mNetd.addSecondaryRoute(ifaceName, r);
1584 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001585 } catch (Exception e) {
1586 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001587 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001588 return false;
1589 }
1590 } else {
1591 // if we remove this one and there are no more like it, then refcount==0 and
1592 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001593 if (toDefaultTable) {
Chad Brubakerf336d722013-07-15 16:34:04 -07001594 synchronized (mRoutesLock) {
1595 mAddedRoutes.remove(r);
1596 if (mAddedRoutes.contains(r) == false) {
1597 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1598 try {
1599 mNetd.removeRoute(ifaceName, r);
1600 LinkAddress dest = r.getDestination();
1601 if (mExemptAddresses.contains(dest)) {
1602 mNetd.clearHostExemption(dest);
1603 mExemptAddresses.remove(dest);
1604 }
1605 } catch (Exception e) {
1606 // never crash - catch them all
1607 if (VDBG) loge("Exception trying to remove a route: " + e);
1608 return false;
1609 }
1610 } else {
1611 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001612 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001613 }
1614 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001615 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001616 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001617 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001618 } catch (Exception e) {
1619 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001620 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001621 return false;
1622 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001623 }
1624 }
1625 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
1628 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001629 * @see ConnectivityManager#getMobileDataEnabled()
1630 */
1631 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001632 // TODO: This detail should probably be in DataConnectionTracker's
1633 // which is where we store the value and maybe make this
1634 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001635 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001636 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1637 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001638 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001639 return retVal;
1640 }
1641
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001642 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001643 enforceConnectivityInternalPermission();
1644
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1646 (met ? ENABLED : DISABLED), networkType));
1647 }
1648
1649 private void handleSetDependencyMet(int networkType, boolean met) {
1650 if (mNetTrackers[networkType] != null) {
1651 if (DBG) {
1652 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1653 }
1654 mNetTrackers[networkType].setDependencyMet(met);
1655 }
1656 }
1657
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001658 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1659 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001660 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001661 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001662 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001663 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001664 }
1665
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001666 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001667 // skip update when we've already applied rules
1668 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1669 if (oldRules == uidRules) return;
1670
1671 mUidRules.put(uid, uidRules);
1672 }
1673
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001674 // TODO: notify UID when it has requested targeted updates
1675 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001676
1677 @Override
1678 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001679 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001680 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001681 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001682 }
1683
1684 synchronized (mRulesLock) {
1685 mMeteredIfaces.clear();
1686 for (String iface : meteredIfaces) {
1687 mMeteredIfaces.add(iface);
1688 }
1689 }
1690 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001691
1692 @Override
1693 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1694 // caller is NPMS, since we only register with them
1695 if (LOGD_RULES) {
1696 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1697 }
1698
1699 // kick off connectivity change broadcast for active network, since
1700 // global background policy change is radical.
1701 final int networkType = mActiveDefaultNetwork;
1702 if (isNetworkTypeValid(networkType)) {
1703 final NetworkStateTracker tracker = mNetTrackers[networkType];
1704 if (tracker != null) {
1705 final NetworkInfo info = tracker.getNetworkInfo();
1706 if (info != null && info.isConnected()) {
1707 sendConnectedBroadcast(info);
1708 }
1709 }
1710 }
1711 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001712 };
1713
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001714 /**
1715 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1716 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001717 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001718 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001719 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001720
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001722 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001723 }
1724
1725 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001726 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001727 if (VDBG) {
1728 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001729 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001730 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1731 }
tk.munb97d34c2012-01-06 10:43:52 +09001732 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1733 if (VDBG) {
1734 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1735 }
1736 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1737 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001738 }
1739
1740 @Override
1741 public void setPolicyDataEnable(int networkType, boolean enabled) {
1742 // only someone like NPMS should only be calling us
1743 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1744
1745 mHandler.sendMessage(mHandler.obtainMessage(
1746 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1747 }
1748
1749 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1750 if (isNetworkTypeValid(networkType)) {
1751 final NetworkStateTracker tracker = mNetTrackers[networkType];
1752 if (tracker != null) {
1753 tracker.setPolicyDataEnable(enabled);
1754 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001755 }
1756 }
1757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001759 mContext.enforceCallingOrSelfPermission(
1760 android.Manifest.permission.ACCESS_NETWORK_STATE,
1761 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
1763
1764 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001765 mContext.enforceCallingOrSelfPermission(
1766 android.Manifest.permission.CHANGE_NETWORK_STATE,
1767 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001770 // TODO Make this a special check when it goes public
1771 private void enforceTetherChangePermission() {
1772 mContext.enforceCallingOrSelfPermission(
1773 android.Manifest.permission.CHANGE_NETWORK_STATE,
1774 "ConnectivityService");
1775 }
1776
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001777 private void enforceTetherAccessPermission() {
1778 mContext.enforceCallingOrSelfPermission(
1779 android.Manifest.permission.ACCESS_NETWORK_STATE,
1780 "ConnectivityService");
1781 }
1782
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001783 private void enforceConnectivityInternalPermission() {
1784 mContext.enforceCallingOrSelfPermission(
1785 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1786 "ConnectivityService");
1787 }
1788
Chad Brubakerd475c702013-07-11 13:29:30 -07001789 private void enforceMarkNetworkSocketPermission() {
1790 //Media server special case
1791 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1792 return;
1793 }
1794 mContext.enforceCallingOrSelfPermission(
1795 android.Manifest.permission.MARK_NETWORK_SOCKET,
1796 "ConnectivityService");
1797 }
1798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001800 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1801 * network, we ignore it. If it is for the active network, we send out a
1802 * broadcast. But first, we check whether it might be possible to connect
1803 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 * @param info the {@code NetworkInfo} for the network
1805 */
1806 private void handleDisconnect(NetworkInfo info) {
1807
Robert Greenwalt42acef32009-08-12 16:08:25 -07001808 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809
Robert Greenwalt42acef32009-08-12 16:08:25 -07001810 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001811
1812 // Remove idletimer previously setup in {@code handleConnect}
1813 removeDataActivityTracking(prevNetType);
1814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 /*
1816 * If the disconnected network is not the active one, then don't report
1817 * this as a loss of connectivity. What probably happened is that we're
1818 * getting the disconnect for a network that we explicitly disabled
1819 * in accordance with network preference policies.
1820 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001821 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falk8b47b362011-08-23 14:15:13 +02001822 List<Integer> pids = mNetRequestersPids[prevNetType];
1823 for (Integer pid : pids) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001824 // will remove them because the net's no longer connected
1825 // need to do this now as only now do we know the pids and
1826 // can properly null things that are no longer referenced.
1827 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001832 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001833 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 if (info.isFailover()) {
1835 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1836 info.setFailover(false);
1837 }
1838 if (info.getReason() != null) {
1839 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1840 }
1841 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001842 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1843 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001845
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001846 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001847 tryFailover(prevNetType);
1848 if (mActiveDefaultNetwork != -1) {
1849 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001850 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1851 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001852 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001853 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1854 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001855 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001856 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001857
1858 // Reset interface if no other connections are using the same interface
1859 boolean doReset = true;
1860 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1861 if (linkProperties != null) {
1862 String oldIface = linkProperties.getInterfaceName();
1863 if (TextUtils.isEmpty(oldIface) == false) {
1864 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1865 if (networkStateTracker == null) continue;
1866 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1867 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1868 LinkProperties l = networkStateTracker.getLinkProperties();
1869 if (l == null) continue;
1870 if (oldIface.equals(l.getInterfaceName())) {
1871 doReset = false;
1872 break;
1873 }
1874 }
1875 }
1876 }
1877 }
1878
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001879 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001880 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001881
Jeff Sharkey961e3042011-08-29 16:02:57 -07001882 final Intent immediateIntent = new Intent(intent);
1883 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1884 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001885 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001886 /*
1887 * If the failover network is already connected, then immediately send
1888 * out a followup broadcast indicating successful failover
1889 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001890 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001891 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1892 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001893 }
1894 }
1895
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001896 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001897 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001898 * If this is a default network, check if other defaults are available.
1899 * Try to reconnect on all available and let them hash it out when
1900 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001901 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001902 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001903 if (mActiveDefaultNetwork == prevNetType) {
1904 mActiveDefaultNetwork = -1;
1905 }
1906
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001907 // don't signal a reconnect for anything lower or equal priority than our
1908 // current connected default
1909 // TODO - don't filter by priority now - nice optimization but risky
1910// int currentPriority = -1;
1911// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001912// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001913// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001914 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001915 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001916 if (mNetConfigs[checkType] == null) continue;
1917 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001918 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001919
1920// Enabling the isAvailable() optimization caused mobile to not get
1921// selected if it was in the middle of error handling. Specifically
1922// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1923// would not be available and we wouldn't get connected to anything.
1924// So removing the isAvailable() optimization below for now. TODO: This
1925// optimization should work and we need to investigate why it doesn't work.
1926// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1927// complete before it is really complete.
1928// if (!mNetTrackers[checkType].isAvailable()) continue;
1929
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001930// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001931
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001932 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1933 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1934 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1935 checkInfo.setFailover(true);
1936 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001937 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001938 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001943 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001944 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001945 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1946 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001947 }
1948
Wink Saville628b0852011-08-04 15:01:58 -07001949 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001950 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1951 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001952 }
1953
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001954 private void sendInetConditionBroadcast(NetworkInfo info) {
1955 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1956 }
1957
Wink Saville628b0852011-08-04 15:01:58 -07001958 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001959 if (mLockdownTracker != null) {
1960 info = mLockdownTracker.augmentNetworkInfo(info);
1961 }
1962
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001963 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001964 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001965 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 if (info.isFailover()) {
1967 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1968 info.setFailover(false);
1969 }
1970 if (info.getReason() != null) {
1971 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1972 }
1973 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001974 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1975 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001977 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001978 return intent;
1979 }
1980
1981 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1982 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1983 }
1984
1985 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1986 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
1988
Haoyu Baidb3c8672012-06-20 14:29:57 -07001989 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1990 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1991 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1992 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001993 final long ident = Binder.clearCallingIdentity();
1994 try {
1995 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1996 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1997 } finally {
1998 Binder.restoreCallingIdentity(ident);
1999 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002000 }
2001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 /**
2003 * Called when an attempt to fail over to another network has failed.
2004 * @param info the {@link NetworkInfo} for the failed network
2005 */
2006 private void handleConnectionFailure(NetworkInfo info) {
2007 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008
Robert Greenwalt42acef32009-08-12 16:08:25 -07002009 String reason = info.getReason();
2010 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002011
Robert Greenwalt572172b2010-10-08 16:35:52 -07002012 String reasonText;
2013 if (reason == null) {
2014 reasonText = ".";
2015 } else {
2016 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002018 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002019
2020 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002021 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002022 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07002023 if (getActiveNetworkInfo() == null) {
2024 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2025 }
2026 if (reason != null) {
2027 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2028 }
2029 if (extraInfo != null) {
2030 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2031 }
2032 if (info.isFailover()) {
2033 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2034 info.setFailover(false);
2035 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002036
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002037 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002038 tryFailover(info.getType());
2039 if (mActiveDefaultNetwork != -1) {
2040 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002041 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2042 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07002043 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002044 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2045 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002046 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08002047
Robert Greenwalt029be812010-09-20 18:01:43 -07002048 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07002049
2050 final Intent immediateIntent = new Intent(intent);
2051 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2052 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002053 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002054 /*
2055 * If the failover network is already connected, then immediately send
2056 * out a followup broadcast indicating successful failover
2057 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08002058 if (mActiveDefaultNetwork != -1) {
2059 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08002060 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002061 }
2062
2063 private void sendStickyBroadcast(Intent intent) {
2064 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002065 if (!mSystemReady) {
2066 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002067 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002068 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07002069 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002070 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002071 }
2072
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002073 final long ident = Binder.clearCallingIdentity();
2074 try {
2075 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2076 } finally {
2077 Binder.restoreCallingIdentity(ident);
2078 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002079 }
2080 }
2081
Wink Saville628b0852011-08-04 15:01:58 -07002082 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2083 if (delayMs <= 0) {
2084 sendStickyBroadcast(intent);
2085 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002086 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002087 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2088 + intent.getAction());
2089 }
Wink Saville628b0852011-08-04 15:01:58 -07002090 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2091 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2092 }
2093 }
2094
Mike Lockwood0f79b542009-08-14 14:18:49 -04002095 void systemReady() {
2096 synchronized(this) {
2097 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002098 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002099 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002100 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002101 }
2102 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002103 // load the global proxy at startup
2104 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002105
2106 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2107 // for user to unlock device.
2108 if (!updateLockdownVpn()) {
2109 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2110 mContext.registerReceiver(mUserPresentReceiver, filter);
2111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
2113
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002114 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2115 @Override
2116 public void onReceive(Context context, Intent intent) {
2117 // Try creating lockdown tracker, since user present usually means
2118 // unlocked keystore.
2119 if (updateLockdownVpn()) {
2120 mContext.unregisterReceiver(this);
2121 }
2122 }
2123 };
2124
Irfan Sheriffda6da092012-08-16 12:49:23 -07002125 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2126 if ((type != mNetworkPreference &&
2127 mNetConfigs[mActiveDefaultNetwork].priority >
2128 mNetConfigs[type].priority) ||
2129 mNetworkPreference == mActiveDefaultNetwork) return false;
2130 return true;
2131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132
Irfan Sheriffda6da092012-08-16 12:49:23 -07002133 private void handleConnect(NetworkInfo info) {
2134 final int newNetType = info.getType();
2135
2136 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 // snapshot isFailover, because sendConnectedBroadcast() resets it
2139 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002140 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002141 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142
Robert Greenwalt42acef32009-08-12 16:08:25 -07002143 // if this is a default net and other default is running
2144 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002145 if (mNetConfigs[newNetType].isDefault()) {
2146 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2147 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002148 // tear down the other
2149 NetworkStateTracker otherNet =
2150 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002151 if (DBG) {
2152 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002153 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002154 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002155 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002156 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002157 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002158 return;
2159 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002160 } else {
2161 // don't accept this one
2162 if (VDBG) {
2163 log("Not broadcasting CONNECT_ACTION " +
2164 "to torn down network " + info.getTypeName());
2165 }
2166 teardown(thisNet);
2167 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002168 }
2169 }
2170 synchronized (ConnectivityService.this) {
2171 // have a new default network, release the transition wakelock in a second
2172 // if it's held. The second pause is to allow apps to reconnect over the
2173 // new network
2174 if (mNetTransitionWakeLock.isHeld()) {
2175 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002176 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002177 mNetTransitionWakeLockSerialNumber, 0),
2178 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002179 }
2180 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002181 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002182 // this will cause us to come up initially as unconnected and switching
2183 // to connected after our normal pause unless somebody reports us as reall
2184 // disconnected
2185 mDefaultInetConditionPublished = 0;
2186 mDefaultConnectionSequence++;
2187 mInetConditionChangeInFlight = false;
2188 // Don't do this - if we never sign in stay, grey
2189 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002192 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002193 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002194 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002195
2196 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002197 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002198 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002199 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002200 } catch (RemoteException e) {
2201 // ignored; service lives in system_server
2202 }
2203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
2205
Irfan Sheriffda6da092012-08-16 12:49:23 -07002206 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2207 if (DBG) log("Captive portal check " + info);
2208 int type = info.getType();
2209 final NetworkStateTracker thisNet = mNetTrackers[type];
2210 if (mNetConfigs[type].isDefault()) {
2211 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2212 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2213 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002214 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002215 return;
2216 } else {
2217 if (DBG) log("Tear down low priority net " + info.getTypeName());
2218 teardown(thisNet);
2219 return;
2220 }
2221 }
2222 }
2223
2224 thisNet.captivePortalCheckComplete();
2225 }
2226
2227 /** @hide */
2228 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002229 enforceConnectivityInternalPermission();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002230 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002231 }
2232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002234 * Setup data activity tracking for the given network interface.
2235 *
2236 * Every {@code setupDataActivityTracking} should be paired with a
2237 * {@link removeDataActivityTracking} for cleanup.
2238 */
2239 private void setupDataActivityTracking(int type) {
2240 final NetworkStateTracker thisNet = mNetTrackers[type];
2241 final String iface = thisNet.getLinkProperties().getInterfaceName();
2242
2243 final int timeout;
2244
2245 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002246 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2247 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002248 0);
2249 // Canonicalize mobile network type
2250 type = ConnectivityManager.TYPE_MOBILE;
2251 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002252 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2253 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002254 0);
2255 } else {
2256 // do not track any other networks
2257 timeout = 0;
2258 }
2259
2260 if (timeout > 0 && iface != null) {
2261 try {
2262 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2263 } catch (RemoteException e) {
2264 }
2265 }
2266 }
2267
2268 /**
2269 * Remove data activity tracking when network disconnects.
2270 */
2271 private void removeDataActivityTracking(int type) {
2272 final NetworkStateTracker net = mNetTrackers[type];
2273 final String iface = net.getLinkProperties().getInterfaceName();
2274
2275 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2276 ConnectivityManager.TYPE_WIFI == type)) {
2277 try {
2278 // the call fails silently if no idletimer setup for this interface
2279 mNetd.removeIdleTimer(iface);
2280 } catch (RemoteException e) {
2281 }
2282 }
2283 }
2284
2285 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002286 * After a change in the connectivity state of a network. We're mainly
2287 * concerned with making sure that the list of DNS servers is set up
2288 * according to which networks are connected, and ensuring that the
2289 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002291 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002292 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubakerf336d722013-07-15 16:34:04 -07002293 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Savillee8222252011-07-13 13:44:13 -07002294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002296 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002297 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002299 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002300
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002301 LinkProperties curLp = mCurrentLinkProperties[netType];
2302 LinkProperties newLp = null;
2303
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002304 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002305 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002306 if (VDBG) {
2307 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2308 " doReset=" + doReset + " resetMask=" + resetMask +
2309 "\n curLp=" + curLp +
2310 "\n newLp=" + newLp);
2311 }
2312
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002313 if (curLp != null) {
2314 if (curLp.isIdenticalInterfaceName(newLp)) {
2315 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2316 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2317 for (LinkAddress linkAddr : car.removed) {
2318 if (linkAddr.getAddress() instanceof Inet4Address) {
2319 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2320 }
2321 if (linkAddr.getAddress() instanceof Inet6Address) {
2322 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2323 }
Wink Savillee8222252011-07-13 13:44:13 -07002324 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002325 if (DBG) {
2326 log("handleConnectivityChange: addresses changed" +
2327 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2328 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002329 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002330 } else {
2331 if (DBG) {
2332 log("handleConnectivityChange: address are the same reset per doReset" +
2333 " linkProperty[" + netType + "]:" +
2334 " resetMask=" + resetMask);
2335 }
Wink Savillee8222252011-07-13 13:44:13 -07002336 }
2337 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002338 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002339 if (DBG) {
2340 log("handleConnectivityChange: interface not not equivalent reset both" +
2341 " linkProperty[" + netType + "]:" +
2342 " resetMask=" + resetMask);
2343 }
Wink Savillee8222252011-07-13 13:44:13 -07002344 }
Wink Savillee8222252011-07-13 13:44:13 -07002345 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002346 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002347 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002348 }
2349 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002350 if (VDBG) {
2351 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2352 " doReset=" + doReset + " resetMask=" + resetMask +
2353 "\n curLp=" + curLp +
2354 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002357 mCurrentLinkProperties[netType] = newLp;
Chad Brubakerf336d722013-07-15 16:34:04 -07002358 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwaltec896c62011-06-15 12:22:07 -07002359
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002360 if (resetMask != 0 || resetDns) {
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002361 if (curLp != null) {
2362 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002363 if (TextUtils.isEmpty(iface) == false) {
2364 if (resetMask != 0) {
2365 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2366 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002367
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002368 // Tell VPN the interface is down. It is a temporary
2369 // but effective fix to make VPN aware of the change.
2370 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002371 synchronized(mVpns) {
2372 for (int i = 0; i < mVpns.size(); i++) {
2373 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2374 }
2375 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002376 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002377 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002378 if (resetDns) {
2379 flushVmDnsCache();
2380 if (VDBG) log("resetting DNS cache for " + iface);
2381 try {
2382 mNetd.flushInterfaceDnsCache(iface);
2383 } catch (Exception e) {
2384 // never crash - catch them all
2385 if (DBG) loge("Exception resetting dns cache: " + e);
2386 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002387 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002388 } else {
2389 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002390 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002391 }
2392 }
2393 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002394
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002395 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002396 NetworkStateTracker tracker = mNetTrackers[netType];
2397 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002398 // If the connection was previously using clat, but is not using it now, stop the clat
2399 // daemon. Normally, this happens automatically when the connection disconnects, but if
2400 // the disconnect is not reported, or if the connection's LinkProperties changed for
2401 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2402 // still be running. If it's not running, then stopping it is a no-op.
2403 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2404 mClat.stopClat();
2405 }
2406 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002407 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2408 mClat.startClat(tracker);
2409 } else {
2410 mClat.stopClat();
2411 }
2412 }
2413
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002414 // TODO: Temporary notifying upstread change to Tethering.
2415 // @see bug/4455071
2416 /** Notify TetheringService if interface name has been changed. */
2417 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002418 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002419 if (isTetheringSupported()) {
2420 mTethering.handleTetherIfaceChange();
2421 }
2422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 }
2424
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002425 /**
2426 * Add and remove routes using the old properties (null if not previously connected),
2427 * new properties (null if becoming disconnected). May even be double null, which
2428 * is a noop.
2429 * Uses isLinkDefault to determine if default routes should be set or conversely if
2430 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002431 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002432 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002433 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubakerf336d722013-07-15 16:34:04 -07002434 boolean isLinkDefault, boolean exempt) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002435 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002436 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2437 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002438 if (curLp != null) {
2439 // check for the delta between the current set and the new
Lorenzo Colittid1e0fae2013-07-31 23:23:21 +09002440 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002441 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002442 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002443 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002444 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002445 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002446
Robert Greenwaltf125a092011-08-15 12:31:55 -07002447 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2448
Robert Greenwaltad55d352011-07-22 11:55:33 -07002449 for (RouteInfo r : routeDiff.removed) {
2450 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002451 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2452 }
2453 if (isLinkDefault == false) {
2454 // remove from a secondary route table
2455 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002456 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002457 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002458
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002459 if (!isLinkDefault) {
2460 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002461 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002462 // routes changed - remove all old dns entries and add new
2463 if (curLp != null) {
2464 for (InetAddress oldDns : curLp.getDnses()) {
2465 removeRouteToAddress(curLp, oldDns);
2466 }
2467 }
2468 if (newLp != null) {
2469 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002470 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002471 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002472 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002473 } else {
2474 // no change in routes, check for change in dns themselves
2475 for (InetAddress oldDns : dnsDiff.removed) {
2476 removeRouteToAddress(curLp, oldDns);
2477 }
2478 for (InetAddress newDns : dnsDiff.added) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002479 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002480 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002481 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002482 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002483
2484 for (RouteInfo r : routeDiff.added) {
2485 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002486 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002487 } else {
2488 // add to a secondary route table
Chad Brubakerf336d722013-07-15 16:34:04 -07002489 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002490
2491 // many radios add a default route even when we don't want one.
2492 // remove the default route unless somebody else has asked for it
2493 String ifaceName = newLp.getInterfaceName();
Chad Brubakerf336d722013-07-15 16:34:04 -07002494 synchronized (mRoutesLock) {
2495 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2496 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2497 try {
2498 mNetd.removeRoute(ifaceName, r);
2499 } catch (Exception e) {
2500 // never crash - catch them all
2501 if (DBG) loge("Exception trying to remove a route: " + e);
2502 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002503 }
2504 }
2505 }
2506 }
2507
Robert Greenwaltf125a092011-08-15 12:31:55 -07002508 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002509 }
2510
2511
Irfan Sheriffd649c122010-06-09 15:39:36 -07002512 /**
2513 * Reads the network specific TCP buffer sizes from SystemProperties
2514 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2515 * wide use
2516 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002517 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002518 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002519 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002520
Jeff Sharkey899223b2012-08-04 15:24:58 -07002521 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002522 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002523
2524 // Setting to default values so we won't be stuck to previous values
2525 key = "net.tcp.buffersize.default";
2526 bufferSizes = SystemProperties.get(key);
2527 }
2528
2529 // Set values in kernel
2530 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002531 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002532 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002533 + "] which comes from [" + key + "]");
2534 }
2535 setBufferSize(bufferSizes);
2536 }
2537 }
2538
2539 /**
2540 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2541 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2542 *
2543 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2544 * writeMin, writeInitial, writeMax"
2545 */
2546 private void setBufferSize(String bufferSizes) {
2547 try {
2548 String[] values = bufferSizes.split(",");
2549
2550 if (values.length == 6) {
2551 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002552 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2553 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2554 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2555 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2556 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2557 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002558 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002559 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002560 }
2561 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002562 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002563 }
2564 }
2565
Robert Greenwalt42acef32009-08-12 16:08:25 -07002566 /**
2567 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2568 * on the highest priority active net which this process requested.
2569 * If there aren't any, clear it out
2570 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002571 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002572 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002573 if (VDBG) log("reassessPidDns for pid " + pid);
2574 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002575 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002576 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002577 continue;
2578 }
2579 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002580 if (nt.getNetworkInfo().isConnected() &&
2581 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002582 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002583 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002584 if (mNetRequestersPids[i].contains(myPid)) {
2585 try {
2586 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2587 } catch (Exception e) {
2588 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002589 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002590 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002591 }
2592 }
2593 }
2594 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002595 try {
2596 mNetd.clearDnsInterfaceForPid(pid);
2597 } catch (Exception e) {
2598 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002599 }
2600 }
2601
Mattias Falk8b47b362011-08-23 14:15:13 +02002602 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002603 /*
2604 * Tell the VMs to toss their DNS caches
2605 */
2606 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2607 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002608 /*
2609 * Connectivity events can happen before boot has completed ...
2610 */
2611 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002612 final long ident = Binder.clearCallingIdentity();
2613 try {
2614 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002618 }
2619
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002620 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002621 private void updateDnsLocked(String network, String iface,
Chad Brubaker20a7e882013-07-23 17:13:36 -07002622 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002623 int last = 0;
2624 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002625 dnses = new ArrayList();
2626 dnses.add(mDefaultDns);
2627 if (DBG) {
2628 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002629 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002630 }
2631
Mattias Falk8b47b362011-08-23 14:15:13 +02002632 try {
2633 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker20a7e882013-07-23 17:13:36 -07002634 if (defaultDns) {
2635 mNetd.setDefaultInterfaceForDns(iface);
2636 }
2637
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002638 for (InetAddress dns : dnses) {
2639 ++last;
2640 String key = "net.dns" + last;
2641 String value = dns.getHostAddress();
2642 SystemProperties.set(key, value);
2643 }
2644 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2645 String key = "net.dns" + i;
2646 SystemProperties.set(key, "");
2647 }
2648 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002649 } catch (Exception e) {
2650 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002651 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002652 }
2653
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002654 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002655 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002656 NetworkStateTracker nt = mNetTrackers[netType];
2657 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002658 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002659 if (p == null) return;
2660 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002661 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002662 String network = nt.getNetworkInfo().getTypeName();
2663 synchronized (mDnsLock) {
Chad Brubakerb98703e2013-07-23 17:44:41 -07002664 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002665 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002666 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002667 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002668 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002669 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002670 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002671 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002672 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002673 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002674 List<Integer> pids = mNetRequestersPids[netType];
2675 for (Integer pid : pids) {
2676 try {
2677 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2678 } catch (Exception e) {
2679 Slog.e(TAG, "exception setting interface for pid: " + e);
2680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 }
2682 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002683 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002685 }
2686
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002687 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002688 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2689 NETWORK_RESTORE_DELAY_PROP_NAME);
2690 if(restoreDefaultNetworkDelayStr != null &&
2691 restoreDefaultNetworkDelayStr.length() != 0) {
2692 try {
2693 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2694 } catch (NumberFormatException e) {
2695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002697 // if the system property isn't set, use the value for the apn type
2698 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2699
2700 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2701 (mNetConfigs[networkType] != null)) {
2702 ret = mNetConfigs[networkType].restoreTime;
2703 }
2704 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 }
2706
2707 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002708 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2709 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002710 if (mContext.checkCallingOrSelfPermission(
2711 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002713 pw.println("Permission Denial: can't dump ConnectivityService " +
2714 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2715 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 return;
2717 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002718
2719 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002721 for (int i = 0; i < mNetTrackers.length; i++) {
2722 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002723 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002724 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2725 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002726 if (nst.getNetworkInfo().isConnected()) {
2727 pw.println("Active network: " + nst.getNetworkInfo().
2728 getTypeName());
2729 }
2730 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002731 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002732 pw.println(nst);
2733 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002734 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002737
2738 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002739 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002740 for (int net : mPriorityList) {
2741 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002742 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002743 pidString = pidString + pid.toString() + ", ";
2744 }
2745 pw.println(pidString);
2746 }
2747 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002748 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002749
2750 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002751 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002752 for (Object requester : mFeatureUsers) {
2753 pw.println(requester.toString());
2754 }
2755 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002756 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002757
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002758 synchronized (this) {
2759 pw.println("NetworkTranstionWakeLock is currently " +
2760 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2761 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2762 }
2763 pw.println();
2764
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002765 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002766
2767 if (mInetLog != null) {
2768 pw.println();
2769 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002770 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002771 for(int i = 0; i < mInetLog.size(); i++) {
2772 pw.println(mInetLog.get(i));
2773 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002774 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 }
2777
Robert Greenwalt42acef32009-08-12 16:08:25 -07002778 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002779 private class NetworkStateTrackerHandler extends Handler {
2780 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002781 super(looper);
2782 }
2783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 @Override
2785 public void handleMessage(Message msg) {
2786 NetworkInfo info;
2787 switch (msg.what) {
2788 case NetworkStateTracker.EVENT_STATE_CHANGED:
2789 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002790 int type = info.getType();
2791 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002792
Wink Savillec9acde92011-09-21 11:05:43 -07002793 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2794 (state == NetworkInfo.State.DISCONNECTED)) {
2795 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002796 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002797 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799
Wink Savillefde1ac92013-07-16 17:16:37 -07002800 // After booting we'll check once for mobile provisioning
2801 // if we've provisioned by and connected.
2802 if (!mFirstProvisioningCheckStarted
2803 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2804 Settings.Global.DEVICE_PROVISIONED, 0))
2805 && (state == NetworkInfo.State.CONNECTED)) {
2806 log("check provisioning after booting");
2807 mFirstProvisioningCheckStarted = true;
2808 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2809 }
2810
Jeff Sharkey2528b502012-11-09 15:57:02 -08002811 EventLogTags.writeConnectivityStateChanged(
2812 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002813
2814 if (info.getDetailedState() ==
2815 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002817 } else if (info.getDetailedState() ==
2818 DetailedState.CAPTIVE_PORTAL_CHECK) {
2819 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002820 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002822 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002824 // the logic here is, handle SUSPENDED the same as
2825 // DISCONNECTED. The only difference being we are
2826 // broadcasting an intent with NetworkInfo that's
2827 // suspended. This allows the applications an
2828 // opportunity to handle DISCONNECTED and SUSPENDED
2829 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002831 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 handleConnect(info);
2833 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002834 if (mLockdownTracker != null) {
2835 mLockdownTracker.onNetworkInfoChanged(info);
2836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002839 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002840 // TODO: Temporary allowing network configuration
2841 // change not resetting sockets.
2842 // @see bug/4455071
2843 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002845 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2846 info = (NetworkInfo) msg.obj;
2847 type = info.getType();
2848 updateNetworkSettings(mNetTrackers[type]);
2849 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002850 }
2851 }
2852 }
2853
2854 private class InternalHandler extends Handler {
2855 public InternalHandler(Looper looper) {
2856 super(looper);
2857 }
2858
2859 @Override
2860 public void handleMessage(Message msg) {
2861 NetworkInfo info;
2862 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002863 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002864 String causedBy = null;
2865 synchronized (ConnectivityService.this) {
2866 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2867 mNetTransitionWakeLock.isHeld()) {
2868 mNetTransitionWakeLock.release();
2869 causedBy = mNetTransitionWakeLockCausedBy;
2870 }
2871 }
2872 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002873 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002874 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002875 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002876 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002877 FeatureUser u = (FeatureUser)msg.obj;
2878 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002879 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002880 case EVENT_INET_CONDITION_CHANGE:
2881 {
2882 int netType = msg.arg1;
2883 int condition = msg.arg2;
2884 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002885 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002886 }
2887 case EVENT_INET_CONDITION_HOLD_END:
2888 {
2889 int netType = msg.arg1;
2890 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002891 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002892 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002893 }
2894 case EVENT_SET_NETWORK_PREFERENCE:
2895 {
2896 int preference = msg.arg1;
2897 handleSetNetworkPreference(preference);
2898 break;
2899 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002900 case EVENT_SET_MOBILE_DATA:
2901 {
2902 boolean enabled = (msg.arg1 == ENABLED);
2903 handleSetMobileData(enabled);
2904 break;
2905 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002906 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2907 {
2908 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002909 break;
2910 }
2911 case EVENT_SET_DEPENDENCY_MET:
2912 {
2913 boolean met = (msg.arg1 == ENABLED);
2914 handleSetDependencyMet(msg.arg2, met);
2915 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002916 }
Wink Saville628b0852011-08-04 15:01:58 -07002917 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2918 {
2919 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002920 sendStickyBroadcast(intent);
2921 break;
2922 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002923 case EVENT_SET_POLICY_DATA_ENABLE: {
2924 final int networkType = msg.arg1;
2925 final boolean enabled = msg.arg2 == ENABLED;
2926 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002927 break;
2928 }
2929 case EVENT_VPN_STATE_CHANGED: {
2930 if (mLockdownTracker != null) {
2931 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2932 }
2933 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002934 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002935 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2936 int tag = mEnableFailFastMobileDataTag.get();
2937 if (msg.arg1 == tag) {
2938 MobileDataStateTracker mobileDst =
2939 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2940 if (mobileDst != null) {
2941 mobileDst.setEnableFailFastMobileData(msg.arg2);
2942 }
2943 } else {
2944 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2945 + " != tag:" + tag);
2946 }
2947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 }
2949 }
2950 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002951
2952 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002953 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002954 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002955
2956 if (isTetheringSupported()) {
2957 return mTethering.tether(iface);
2958 } else {
2959 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2960 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002961 }
2962
2963 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002964 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002965 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002966
2967 if (isTetheringSupported()) {
2968 return mTethering.untether(iface);
2969 } else {
2970 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2971 }
2972 }
2973
2974 // javadoc from interface
2975 public int getLastTetherError(String iface) {
2976 enforceTetherAccessPermission();
2977
2978 if (isTetheringSupported()) {
2979 return mTethering.getLastTetherError(iface);
2980 } else {
2981 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2982 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002983 }
2984
2985 // TODO - proper iface API for selection by property, inspection, etc
2986 public String[] getTetherableUsbRegexs() {
2987 enforceTetherAccessPermission();
2988 if (isTetheringSupported()) {
2989 return mTethering.getTetherableUsbRegexs();
2990 } else {
2991 return new String[0];
2992 }
2993 }
2994
2995 public String[] getTetherableWifiRegexs() {
2996 enforceTetherAccessPermission();
2997 if (isTetheringSupported()) {
2998 return mTethering.getTetherableWifiRegexs();
2999 } else {
3000 return new String[0];
3001 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003002 }
3003
Danica Chang6fdd0c62010-08-11 14:54:43 -07003004 public String[] getTetherableBluetoothRegexs() {
3005 enforceTetherAccessPermission();
3006 if (isTetheringSupported()) {
3007 return mTethering.getTetherableBluetoothRegexs();
3008 } else {
3009 return new String[0];
3010 }
3011 }
3012
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003013 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003014 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003015 if (isTetheringSupported()) {
3016 return mTethering.setUsbTethering(enable);
3017 } else {
3018 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3019 }
3020 }
3021
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003022 // TODO - move iface listing, queries, etc to new module
3023 // javadoc from interface
3024 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003025 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003026 return mTethering.getTetherableIfaces();
3027 }
3028
3029 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003030 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003031 return mTethering.getTetheredIfaces();
3032 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003033
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07003034 @Override
3035 public String[] getTetheredIfacePairs() {
3036 enforceTetherAccessPermission();
3037 return mTethering.getTetheredIfacePairs();
3038 }
3039
Robert Greenwalt5a735062010-03-02 17:25:02 -08003040 public String[] getTetheringErroredIfaces() {
3041 enforceTetherAccessPermission();
3042 return mTethering.getErroredIfaces();
3043 }
3044
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003045 // if ro.tether.denied = true we default to no tethering
3046 // gservices could set the secure setting to 1 though to enable it on a build where it
3047 // had previously been turned off.
3048 public boolean isTetheringSupported() {
3049 enforceTetherAccessPermission();
3050 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003051 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3052 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003053 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3054 mTethering.getTetherableWifiRegexs().length != 0 ||
3055 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3056 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003057 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003058
3059 // An API NetworkStateTrackers can call when they lose their network.
3060 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3061 // whichever happens first. The timer is started by the first caller and not
3062 // restarted by subsequent callers.
3063 public void requestNetworkTransitionWakelock(String forWhom) {
3064 enforceConnectivityInternalPermission();
3065 synchronized (this) {
3066 if (mNetTransitionWakeLock.isHeld()) return;
3067 mNetTransitionWakeLockSerialNumber++;
3068 mNetTransitionWakeLock.acquire();
3069 mNetTransitionWakeLockCausedBy = forWhom;
3070 }
3071 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003072 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003073 mNetTransitionWakeLockSerialNumber, 0),
3074 mNetTransitionWakeLockTimeout);
3075 return;
3076 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003077
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003078 // 100 percent is full good, 0 is full bad.
3079 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003080 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003081 mContext.enforceCallingOrSelfPermission(
3082 android.Manifest.permission.STATUS_BAR,
3083 "ConnectivityService");
3084
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003085 if (DBG) {
3086 int pid = getCallingPid();
3087 int uid = getCallingUid();
3088 String s = pid + "(" + uid + ") reports inet is " +
3089 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3090 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3091 mInetLog.add(s);
3092 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3093 mInetLog.remove(0);
3094 }
3095 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003096 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003097 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3098 }
3099
3100 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003101 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003102 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003103 return;
3104 }
3105 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003106 if (DBG) log("handleInetConditionChange: net=" + netType +
3107 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003108 return;
3109 }
Wink Savillec9acde92011-09-21 11:05:43 -07003110 if (VDBG) {
3111 log("handleInetConditionChange: net=" +
3112 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003113 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003114 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003115 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003116 int delay;
3117 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003118 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003119 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003120 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003121 delay = Settings.Global.getInt(mContext.getContentResolver(),
3122 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003123 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003124 delay = Settings.Global.getInt(mContext.getContentResolver(),
3125 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003126 }
3127 mInetConditionChangeInFlight = true;
3128 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003129 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003130 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003131 // we've set the new condition, when this hold ends that will get picked up
3132 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003133 }
3134 }
3135
Wink Saville5b7573e2013-01-31 00:30:13 +00003136 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003137 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003138 log("handleInetConditionHoldEnd: net=" + netType +
3139 ", condition=" + mDefaultInetCondition +
3140 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003141 }
3142 mInetConditionChangeInFlight = false;
3143
3144 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003145 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003146 return;
3147 }
3148 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003149 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003150 return;
3151 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003152 // TODO: Figure out why this optimization sometimes causes a
3153 // change in mDefaultInetCondition to be missed and the
3154 // UI to not be updated.
3155 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3156 // if (DBG) log("no change in condition - aborting");
3157 // return;
3158 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003159 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3160 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003161 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003162 return;
3163 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003164 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003165 sendInetConditionBroadcast(networkInfo);
3166 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003167 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003168
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003169 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003170 // this information is already available as a world read/writable jvm property
3171 // so this API change wouldn't have a benifit. It also breaks the passing
3172 // of proxy info to all the JVMs.
3173 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003174 synchronized (mProxyLock) {
Jason Monk602b2322013-07-03 17:04:33 -04003175 ProxyProperties ret = mGlobalProxy;
3176 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3177 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003178 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003179 }
3180
3181 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003182 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003183
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003184 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003185 if (proxyProperties == mGlobalProxy) return;
3186 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3187 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3188
3189 String host = "";
3190 int port = 0;
3191 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003192 String pacFileUrl = "";
3193 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3194 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003195 mGlobalProxy = new ProxyProperties(proxyProperties);
3196 host = mGlobalProxy.getHost();
3197 port = mGlobalProxy.getPort();
3198 exclList = mGlobalProxy.getExclusionList();
Jason Monk602b2322013-07-03 17:04:33 -04003199 if (proxyProperties.getPacFileUrl() != null) {
3200 pacFileUrl = proxyProperties.getPacFileUrl();
3201 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003202 } else {
3203 mGlobalProxy = null;
3204 }
3205 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003206 final long token = Binder.clearCallingIdentity();
3207 try {
3208 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3209 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3210 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3211 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003212 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003213 } finally {
3214 Binder.restoreCallingIdentity(token);
3215 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003216 }
3217
3218 if (mGlobalProxy == null) {
3219 proxyProperties = mDefaultProxy;
3220 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003221 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003222 }
3223
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003224 private void loadGlobalProxy() {
3225 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003226 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3227 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3228 String exclList = Settings.Global.getString(res,
3229 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003230 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3231 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3232 ProxyProperties proxyProperties;
3233 if (!TextUtils.isEmpty(pacFileUrl)) {
3234 proxyProperties = new ProxyProperties(pacFileUrl);
3235 } else {
3236 proxyProperties = new ProxyProperties(host, port, exclList);
3237 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003238 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003239 mGlobalProxy = proxyProperties;
3240 }
3241 }
3242 }
3243
Robert Greenwalt434203a2010-10-11 16:00:27 -07003244 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003245 // this information is already available as a world read/writable jvm property
3246 // so this API change wouldn't have a benifit. It also breaks the passing
3247 // of proxy info to all the JVMs.
3248 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003249 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003250 return mGlobalProxy;
3251 }
3252 }
3253
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003254 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003255 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3256 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003257 proxy = null;
3258 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003259 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003260 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003261 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003262 mDefaultProxy = proxy;
3263
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003264 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003265 if (!mDefaultProxyDisabled) {
3266 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003267 }
3268 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003269 }
3270
3271 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003272 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3273 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003274 if (!TextUtils.isEmpty(proxy)) {
3275 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003276 if (data.length == 0) {
3277 return;
3278 }
3279
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 String proxyHost = data[0];
3281 int proxyPort = 8080;
3282 if (data.length > 1) {
3283 try {
3284 proxyPort = Integer.parseInt(data[1]);
3285 } catch (NumberFormatException e) {
3286 return;
3287 }
3288 }
3289 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3290 setGlobalProxy(p);
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003291 } else {
3292 setGlobalProxy(null);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003293 }
3294 }
3295
3296 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003297 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monk602b2322013-07-03 17:04:33 -04003298 mPacManager.setCurrentProxyScriptUrl(proxy);
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003299 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003300 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003301 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3302 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003303 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003304 final long ident = Binder.clearCallingIdentity();
3305 try {
3306 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3307 } finally {
3308 Binder.restoreCallingIdentity(ident);
3309 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003310 }
3311
3312 private static class SettingsObserver extends ContentObserver {
3313 private int mWhat;
3314 private Handler mHandler;
3315 SettingsObserver(Handler handler, int what) {
3316 super(handler);
3317 mHandler = handler;
3318 mWhat = what;
3319 }
3320
3321 void observe(Context context) {
3322 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003323 resolver.registerContentObserver(Settings.Global.getUriFor(
3324 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003325 }
3326
3327 @Override
3328 public void onChange(boolean selfChange) {
3329 mHandler.obtainMessage(mWhat).sendToTarget();
3330 }
3331 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003332
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003333 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003334 Slog.d(TAG, s);
3335 }
3336
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003337 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003338 Slog.e(TAG, s);
3339 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003340
repo syncaea743a2011-07-29 23:55:49 -07003341 int convertFeatureToNetworkType(int networkType, String feature) {
3342 int usedNetworkType = networkType;
3343
3344 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3345 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3346 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3347 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3348 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3349 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3350 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3351 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3352 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3353 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3354 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3355 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3356 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3357 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3358 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3359 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3360 } else {
3361 Slog.e(TAG, "Can't match any mobile netTracker!");
3362 }
3363 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3364 if (TextUtils.equals(feature, "p2p")) {
3365 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3366 } else {
3367 Slog.e(TAG, "Can't match any wifi netTracker!");
3368 }
3369 } else {
3370 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003371 }
repo syncaea743a2011-07-29 23:55:49 -07003372 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003373 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003374
3375 private static <T> T checkNotNull(T value, String message) {
3376 if (value == null) {
3377 throw new NullPointerException(message);
3378 }
3379 return value;
3380 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003381
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003382 /**
3383 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003384 * VpnBuilder and not available in ConnectivityManager. Permissions
3385 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003386 * @hide
3387 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003388 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003389 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003390 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003391 try {
3392 int type = mActiveDefaultNetwork;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003393 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003394 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003395 synchronized(mVpns) {
3396 mVpns.get(user).protect(socket,
3397 mNetTrackers[type].getLinkProperties().getInterfaceName());
3398 }
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003399 return true;
3400 }
3401 } catch (Exception e) {
3402 // ignore
3403 } finally {
3404 try {
3405 socket.close();
3406 } catch (Exception e) {
3407 // ignore
3408 }
3409 }
3410 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003411 }
3412
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003413 /**
3414 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003415 * and not available in ConnectivityManager. Permissions are checked
3416 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003417 * @hide
3418 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003419 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003420 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003421 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003422 int user = UserHandle.getUserId(Binder.getCallingUid());
3423 synchronized(mVpns) {
3424 return mVpns.get(user).prepare(oldPackage, newPackage);
3425 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003426 }
3427
Chad Brubakerd475c702013-07-11 13:29:30 -07003428 @Override
3429 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3430 enforceMarkNetworkSocketPermission();
3431 final long token = Binder.clearCallingIdentity();
3432 try {
3433 int mark = mNetd.getMarkForUid(uid);
3434 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3435 if (mark == -1) {
3436 mark = 0;
3437 }
3438 NetworkUtils.markSocket(socket.getFd(), mark);
3439 } catch (RemoteException e) {
3440 } finally {
3441 Binder.restoreCallingIdentity(token);
3442 }
3443 }
3444
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003445 /**
3446 * Configure a TUN interface and return its file descriptor. Parameters
3447 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003448 * and not available in ConnectivityManager. Permissions are checked in
3449 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003450 * @hide
3451 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003452 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003453 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003454 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003455 int user = UserHandle.getUserId(Binder.getCallingUid());
3456 synchronized(mVpns) {
3457 return mVpns.get(user).establish(config);
3458 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003459 }
3460
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003461 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003462 * Start legacy VPN, controlling native daemons as needed. Creates a
3463 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003464 */
3465 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003466 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003467 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003468 final LinkProperties egress = getActiveLinkProperties();
3469 if (egress == null) {
3470 throw new IllegalStateException("Missing active network connection");
3471 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003472 int user = UserHandle.getUserId(Binder.getCallingUid());
3473 synchronized(mVpns) {
3474 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3475 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003476 }
3477
3478 /**
3479 * Return the information of the ongoing legacy VPN. This method is used
3480 * by VpnSettings and not available in ConnectivityManager. Permissions
3481 * are checked in Vpn class.
3482 * @hide
3483 */
3484 @Override
3485 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003486 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003487 int user = UserHandle.getUserId(Binder.getCallingUid());
3488 synchronized(mVpns) {
3489 return mVpns.get(user).getLegacyVpnInfo();
3490 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003491 }
3492
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003493 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003494 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3495 * not available in ConnectivityManager.
3496 * Permissions are checked in Vpn class.
3497 * @hide
3498 */
3499 @Override
3500 public VpnConfig getVpnConfig() {
3501 int user = UserHandle.getUserId(Binder.getCallingUid());
3502 synchronized(mVpns) {
3503 return mVpns.get(user).getVpnConfig();
3504 }
3505 }
3506
3507 /**
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003508 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3509 * through NetworkStateTracker since it works differently. For example, it
3510 * needs to override DNS servers but never takes the default routes. It
3511 * relies on another data network, and it could keep existing connections
3512 * alive after reconnecting, switching between networks, or even resuming
3513 * from deep sleep. Calls from applications should be done synchronously
3514 * to avoid race conditions. As these are all hidden APIs, refactoring can
3515 * be done whenever a better abstraction is developed.
3516 */
3517 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003518 private VpnCallback() {
3519 }
3520
Jeff Sharkey899223b2012-08-04 15:24:58 -07003521 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003522 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003523 }
3524
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003525 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003526 if (dnsServers == null) {
3527 restore();
3528 return;
3529 }
3530
3531 // Convert DNS servers into addresses.
3532 List<InetAddress> addresses = new ArrayList<InetAddress>();
3533 for (String address : dnsServers) {
3534 // Double check the addresses and remove invalid ones.
3535 try {
3536 addresses.add(InetAddress.parseNumericAddress(address));
3537 } catch (Exception e) {
3538 // ignore
3539 }
3540 }
3541 if (addresses.isEmpty()) {
3542 restore();
3543 return;
3544 }
3545
3546 // Concatenate search domains into a string.
3547 StringBuilder buffer = new StringBuilder();
3548 if (searchDomains != null) {
3549 for (String domain : searchDomains) {
3550 buffer.append(domain).append(' ');
3551 }
3552 }
3553 String domains = buffer.toString().trim();
3554
3555 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003556 synchronized (mDnsLock) {
Chad Brubaker20a7e882013-07-23 17:13:36 -07003557 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003558 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003559
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003560 // Temporarily disable the default proxy (not global).
3561 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003562 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003563 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003564 sendProxyBroadcast(null);
3565 }
3566 }
3567
3568 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003569 }
3570
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003571 public void restore() {
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003572 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003573 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003574 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003575 sendProxyBroadcast(mDefaultProxy);
3576 }
3577 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003578 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003579
3580 public void protect(ParcelFileDescriptor socket) {
3581 try {
3582 final int mark = mNetd.getMarkForProtect();
3583 NetworkUtils.markSocket(socket.getFd(), mark);
3584 } catch (RemoteException e) {
3585 }
3586 }
3587
3588 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3589 for (RouteInfo route : routes) {
3590 try {
3591 mNetd.setMarkedForwardingRoute(interfaze, route);
3592 } catch (RemoteException e) {
3593 }
3594 }
3595 }
3596
3597 public void setMarkedForwarding(String interfaze) {
3598 try {
3599 mNetd.setMarkedForwarding(interfaze);
3600 } catch (RemoteException e) {
3601 }
3602 }
3603
3604 public void clearMarkedForwarding(String interfaze) {
3605 try {
3606 mNetd.clearMarkedForwarding(interfaze);
3607 } catch (RemoteException e) {
3608 }
3609 }
3610
3611 public void addUserForwarding(String interfaze, int uid) {
3612 int uidStart = uid * UserHandle.PER_USER_RANGE;
3613 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3614 addUidForwarding(interfaze, uidStart, uidEnd);
3615 }
3616
3617 public void clearUserForwarding(String interfaze, int uid) {
3618 int uidStart = uid * UserHandle.PER_USER_RANGE;
3619 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3620 clearUidForwarding(interfaze, uidStart, uidEnd);
3621 }
3622
3623 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3624 try {
3625 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3626 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3627 } catch (RemoteException e) {
3628 }
3629
3630 }
3631
3632 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3633 try {
3634 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3635 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3636 } catch (RemoteException e) {
3637 }
3638
3639 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003640 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003641
3642 @Override
3643 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003644 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3645 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3646 return false;
3647 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003648
3649 // Tear down existing lockdown if profile was removed
3650 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3651 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003652 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003653 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3654 return false;
3655 }
3656
3657 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3658 final VpnProfile profile = VpnProfile.decode(
3659 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003660 int user = UserHandle.getUserId(Binder.getCallingUid());
3661 synchronized(mVpns) {
3662 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3663 profile));
3664 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003665 } else {
3666 setLockdownTracker(null);
3667 }
3668
3669 return true;
3670 }
3671
3672 /**
3673 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3674 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3675 */
3676 private void setLockdownTracker(LockdownVpnTracker tracker) {
3677 // Shutdown any existing tracker
3678 final LockdownVpnTracker existing = mLockdownTracker;
3679 mLockdownTracker = null;
3680 if (existing != null) {
3681 existing.shutdown();
3682 }
3683
3684 try {
3685 if (tracker != null) {
3686 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003687 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003688 mLockdownTracker = tracker;
3689 mLockdownTracker.init();
3690 } else {
3691 mNetd.setFirewallEnabled(false);
3692 }
3693 } catch (RemoteException e) {
3694 // ignored; NMS lives inside system_server
3695 }
3696 }
3697
3698 private void throwIfLockdownEnabled() {
3699 if (mLockdownEnabled) {
3700 throw new IllegalStateException("Unavailable in lockdown mode");
3701 }
3702 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003703
3704 public void supplyMessenger(int networkType, Messenger messenger) {
3705 enforceConnectivityInternalPermission();
3706
3707 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3708 mNetTrackers[networkType].supplyMessenger(messenger);
3709 }
3710 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003711
3712 public int findConnectionTypeForIface(String iface) {
3713 enforceConnectivityInternalPermission();
3714
3715 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3716 for (NetworkStateTracker tracker : mNetTrackers) {
3717 if (tracker != null) {
3718 LinkProperties lp = tracker.getLinkProperties();
3719 if (lp != null && iface.equals(lp.getInterfaceName())) {
3720 return tracker.getNetworkInfo().getType();
3721 }
3722 }
3723 }
3724 return ConnectivityManager.TYPE_NONE;
3725 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003726
3727 /**
3728 * Have mobile data fail fast if enabled.
3729 *
3730 * @param enabled DctConstants.ENABLED/DISABLED
3731 */
3732 private void setEnableFailFastMobileData(int enabled) {
3733 int tag;
3734
3735 if (enabled == DctConstants.ENABLED) {
3736 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3737 } else {
3738 tag = mEnableFailFastMobileDataTag.get();
3739 }
3740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3741 enabled));
3742 }
3743
3744 @Override
Wink Savillec2fee242013-07-19 09:27:56 -07003745 public int checkMobileProvisioning(final boolean sendNotification, int suggestedTimeOutMs,
Wink Savilleab9321d2013-06-29 21:10:57 -07003746 final ResultReceiver resultReceiver) {
3747 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3748 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3749 + " resultReceiver=" + resultReceiver);
3750 enforceChangePermission();
3751
Wink Savillefde1ac92013-07-16 17:16:37 -07003752 mFirstProvisioningCheckStarted = true;
3753
Wink Savilleab9321d2013-06-29 21:10:57 -07003754 int timeOutMs = suggestedTimeOutMs;
3755 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3756 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3757 }
3758
Wink Saville68e6c642013-07-02 10:55:14 -07003759 // Check that mobile networks are supported
3760 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3761 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3762 log("checkMobileProvisioning: X no mobile network");
3763 if (resultReceiver != null) {
3764 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3765 }
3766 return timeOutMs;
3767 }
3768
Wink Savilleab9321d2013-06-29 21:10:57 -07003769 final long token = Binder.clearCallingIdentity();
3770 try {
3771 CheckMp checkMp = new CheckMp(mContext, this);
3772 CheckMp.CallBack cb = new CheckMp.CallBack() {
3773 @Override
3774 void onComplete(Integer result) {
3775 log("CheckMp.onComplete: result=" + result);
3776 if (resultReceiver != null) {
3777 log("CheckMp.onComplete: send result");
3778 resultReceiver.send(result, null);
3779 }
Wink Savillec2fee242013-07-19 09:27:56 -07003780 if (!sendNotification) {
3781 log("CheckMp.onComplete: done, not sending notification");
3782 return;
3783 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003784 NetworkInfo ni =
3785 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3786 switch(result) {
3787 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3788 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3789 log("CheckMp.onComplete: ignore, connected or no connection");
3790 break;
3791 }
3792 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3793 log("CheckMp.onComplete: warm sim");
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003794 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003795 if (TextUtils.isEmpty(url)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003796 url = getMobileRedirectedProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003797 }
3798 if (TextUtils.isEmpty(url) == false) {
3799 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3800 setNotificationVisible(true, ni, url);
3801 } else {
3802 log("CheckMp.onComplete: warm sim (redirected), no url");
3803 }
3804 break;
3805 }
3806 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3807 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003808 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003809 if (TextUtils.isEmpty(url) == false) {
3810 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3811 setNotificationVisible(true, ni, url);
3812 } else {
3813 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3814 }
3815 break;
3816 }
3817 default: {
3818 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3819 break;
3820 }
3821 }
3822 }
3823 };
3824 CheckMp.Params params =
3825 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3826 log("checkMobileProvisioning: params=" + params);
3827 setNotificationVisible(false, null, null);
3828 checkMp.execute(params);
3829 } finally {
3830 Binder.restoreCallingIdentity(token);
3831 log("checkMobileProvisioning: X");
3832 }
3833 return timeOutMs;
3834 }
3835
3836 static class CheckMp extends
3837 AsyncTask<CheckMp.Params, Void, Integer> {
3838 private static final String CHECKMP_TAG = "CheckMp";
3839 public static final int MAX_TIMEOUT_MS = 60000;
3840 private static final int SOCKET_TIMEOUT_MS = 5000;
3841 private Context mContext;
3842 private ConnectivityService mCs;
3843 private TelephonyManager mTm;
3844 private Params mParams;
3845
3846 /**
3847 * Parameters for AsyncTask.execute
3848 */
3849 static class Params {
3850 private String mUrl;
3851 private long mTimeOutMs;
3852 private CallBack mCb;
3853
3854 Params(String url, long timeOutMs, CallBack cb) {
3855 mUrl = url;
3856 mTimeOutMs = timeOutMs;
3857 mCb = cb;
3858 }
3859
3860 @Override
3861 public String toString() {
3862 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3863 }
3864 }
3865
3866 /**
3867 * The call back object passed in Params. onComplete will be called
3868 * on the main thread.
3869 */
3870 abstract static class CallBack {
3871 // Called on the main thread.
3872 abstract void onComplete(Integer result);
3873 }
3874
3875 public CheckMp(Context context, ConnectivityService cs) {
3876 mContext = context;
3877 mCs = cs;
3878
3879 // Setup access to TelephonyService we'll be using.
3880 mTm = (TelephonyManager) mContext.getSystemService(
3881 Context.TELEPHONY_SERVICE);
3882 }
3883
3884 /**
3885 * Get the default url to use for the test.
3886 */
3887 public String getDefaultUrl() {
3888 // See http://go/clientsdns for usage approval
3889 String server = Settings.Global.getString(mContext.getContentResolver(),
3890 Settings.Global.CAPTIVE_PORTAL_SERVER);
3891 if (server == null) {
3892 server = "clients3.google.com";
3893 }
3894 return "http://" + server + "/generate_204";
3895 }
3896
3897 /**
3898 * Detect if its possible to connect to the http url. DNS based detection techniques
3899 * do not work at all hotspots. The best way to check is to perform a request to
3900 * a known address that fetches the data we expect.
3901 */
3902 private synchronized Integer isMobileOk(Params params) {
3903 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3904 Uri orgUri = Uri.parse(params.mUrl);
3905 Random rand = new Random();
3906 mParams = params;
3907
3908 try {
3909 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3910 log("isMobileOk: not mobile capable");
3911 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3912 return result;
3913 }
3914
3915 // Enable fail fast as we'll do retries here and use a
3916 // hipri connection so the default connection stays active.
3917 log("isMobileOk: start hipri url=" + params.mUrl);
3918 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
Wink Savilleab9321d2013-06-29 21:10:57 -07003919
3920 // Continue trying to connect until time has run out
3921 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville7f6ee2e2013-08-07 11:02:57 -07003922
3923 // First wait until we can start using hipri
3924 Binder binder = new Binder();
3925 while(SystemClock.elapsedRealtime() < endTime) {
3926 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3927 Phone.FEATURE_ENABLE_HIPRI, binder);
3928 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3929 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3930 log("isMobileOk: hipri started");
3931 break;
3932 }
3933 if (VDBG) log("isMobileOk: hipri not started yet");
3934 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3935 sleep(1);
3936 }
3937
3938 // Continue trying to connect until time has run out
Wink Savilleab9321d2013-06-29 21:10:57 -07003939 while(SystemClock.elapsedRealtime() < endTime) {
3940 try {
3941 // Wait for hipri to connect.
3942 // TODO: Don't poll and handle situation where hipri fails
3943 // because default is retrying. See b/9569540
3944 NetworkInfo.State state = mCs
3945 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3946 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville1aef7fc2013-07-31 15:49:04 -07003947 if (VDBG) {
3948 log("isMobileOk: not connected ni=" +
Wink Savilleab9321d2013-06-29 21:10:57 -07003949 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville1aef7fc2013-07-31 15:49:04 -07003950 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003951 sleep(1);
3952 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3953 continue;
3954 }
3955
3956 // Get of the addresses associated with the url host. We need to use the
3957 // address otherwise HttpURLConnection object will use the name to get
3958 // the addresses and is will try every address but that will bypass the
3959 // route to host we setup and the connection could succeed as the default
3960 // interface might be connected to the internet via wifi or other interface.
3961 InetAddress[] addresses;
3962 try {
3963 addresses = InetAddress.getAllByName(orgUri.getHost());
3964 } catch (UnknownHostException e) {
3965 log("isMobileOk: UnknownHostException");
3966 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3967 return result;
3968 }
3969 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3970
3971 // Get the type of addresses supported by this link
3972 LinkProperties lp = mCs.getLinkProperties(
3973 ConnectivityManager.TYPE_MOBILE_HIPRI);
3974 boolean linkHasIpv4 = hasIPv4Address(lp);
3975 boolean linkHasIpv6 = hasIPv6Address(lp);
3976 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3977 + " linkHasIpv6=" + linkHasIpv6);
3978
3979 // Loop through at most 3 valid addresses or all of the address or until
3980 // we run out of time
3981 int loops = Math.min(3, addresses.length);
3982 for(int validAddr=0, addrTried=0;
3983 (validAddr < loops) && (addrTried < addresses.length)
3984 && (SystemClock.elapsedRealtime() < endTime);
3985 addrTried ++) {
3986
3987 // Choose the address at random but make sure its type is supported
3988 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3989 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3990 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3991 // Valid address, so use it
3992 validAddr += 1;
3993 } else {
3994 // Invalid address so try next address
3995 continue;
3996 }
3997
3998 // Make a route to host so we check the specific interface.
3999 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4000 hostAddr.getAddress())) {
4001 // Wait a short time to be sure the route is established ??
4002 log("isMobileOk:"
4003 + " wait to establish route to hostAddr=" + hostAddr);
4004 sleep(3);
4005 } else {
4006 log("isMobileOk:"
4007 + " could not establish route to hostAddr=" + hostAddr);
4008 continue;
4009 }
4010
4011 // Rewrite the url to have numeric address to use the specific route.
4012 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4013 // is used which is useless in this case.
4014 URL newUrl = new URL(orgUri.getScheme() + "://"
4015 + hostAddr.getHostAddress() + orgUri.getPath());
4016 log("isMobileOk: newUrl=" + newUrl);
4017
4018 HttpURLConnection urlConn = null;
4019 try {
4020 // Open the connection set the request header and get the response
4021 urlConn = (HttpURLConnection) newUrl.openConnection(
4022 java.net.Proxy.NO_PROXY);
4023 urlConn.setInstanceFollowRedirects(false);
4024 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4025 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4026 urlConn.setUseCaches(false);
4027 urlConn.setAllowUserInteraction(false);
4028 urlConn.setRequestProperty("Connection", "close");
4029 int responseCode = urlConn.getResponseCode();
4030 if (responseCode == 204) {
4031 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
4032 } else {
4033 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
4034 }
4035 log("isMobileOk: connected responseCode=" + responseCode);
4036 urlConn.disconnect();
4037 urlConn = null;
4038 return result;
4039 } catch (Exception e) {
4040 log("isMobileOk: HttpURLConnection Exception e=" + e);
4041 if (urlConn != null) {
4042 urlConn.disconnect();
4043 urlConn = null;
4044 }
4045 }
4046 }
4047 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
4048 log("isMobileOk: loops|timed out");
4049 return result;
4050 } catch (Exception e) {
4051 log("isMobileOk: Exception e=" + e);
4052 continue;
4053 }
4054 }
4055 log("isMobileOk: timed out");
4056 } finally {
4057 log("isMobileOk: F stop hipri");
4058 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4059 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4060 Phone.FEATURE_ENABLE_HIPRI);
4061 log("isMobileOk: X result=" + result);
4062 }
4063 return result;
4064 }
4065
4066 @Override
4067 protected Integer doInBackground(Params... params) {
4068 return isMobileOk(params[0]);
4069 }
4070
4071 @Override
4072 protected void onPostExecute(Integer result) {
4073 log("onPostExecute: result=" + result);
4074 if ((mParams != null) && (mParams.mCb != null)) {
4075 mParams.mCb.onComplete(result);
4076 }
4077 }
4078
4079 private String inetAddressesToString(InetAddress[] addresses) {
4080 StringBuffer sb = new StringBuffer();
4081 boolean firstTime = true;
4082 for(InetAddress addr : addresses) {
4083 if (firstTime) {
4084 firstTime = false;
4085 } else {
4086 sb.append(",");
4087 }
4088 sb.append(addr);
4089 }
4090 return sb.toString();
4091 }
4092
4093 private void printNetworkInfo() {
4094 boolean hasIccCard = mTm.hasIccCard();
4095 int simState = mTm.getSimState();
4096 log("hasIccCard=" + hasIccCard
4097 + " simState=" + simState);
4098 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4099 if (ni != null) {
4100 log("ni.length=" + ni.length);
4101 for (NetworkInfo netInfo: ni) {
4102 log("netInfo=" + netInfo.toString());
4103 }
4104 } else {
4105 log("no network info ni=null");
4106 }
4107 }
4108
4109 /**
4110 * Sleep for a few seconds then return.
4111 * @param seconds
4112 */
4113 private static void sleep(int seconds) {
4114 try {
4115 Thread.sleep(seconds * 1000);
4116 } catch (InterruptedException e) {
4117 e.printStackTrace();
4118 }
4119 }
4120
4121 public boolean hasIPv4Address(LinkProperties lp) {
4122 return lp.hasIPv4Address();
4123 }
4124
4125 // Not implemented in LinkProperties, do it here.
4126 public boolean hasIPv6Address(LinkProperties lp) {
4127 for (LinkAddress address : lp.getLinkAddresses()) {
4128 if (address.getAddress() instanceof Inet6Address) {
4129 return true;
4130 }
4131 }
4132 return false;
4133 }
4134
4135 private void log(String s) {
4136 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4137 }
4138 }
4139
4140 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4141
4142 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4143 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4144
4145 Resources r = Resources.getSystem();
4146 NotificationManager notificationManager = (NotificationManager) mContext
4147 .getSystemService(Context.NOTIFICATION_SERVICE);
4148
4149 if (visible) {
4150 CharSequence title;
4151 CharSequence details;
4152 int icon;
4153 switch (networkInfo.getType()) {
4154 case ConnectivityManager.TYPE_WIFI:
4155 log("setNotificationVisible: TYPE_WIFI");
4156 title = r.getString(R.string.wifi_available_sign_in, 0);
4157 details = r.getString(R.string.network_available_sign_in_detailed,
4158 networkInfo.getExtraInfo());
4159 icon = R.drawable.stat_notify_wifi_in_range;
4160 break;
4161 case ConnectivityManager.TYPE_MOBILE:
4162 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4163 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4164 title = r.getString(R.string.network_available_sign_in, 0);
4165 // TODO: Change this to pull from NetworkInfo once a printable
4166 // name has been added to it
4167 details = mTelephonyManager.getNetworkOperatorName();
4168 icon = R.drawable.stat_notify_rssi_in_range;
4169 break;
4170 default:
4171 log("setNotificationVisible: other type=" + networkInfo.getType());
4172 title = r.getString(R.string.network_available_sign_in, 0);
4173 details = r.getString(R.string.network_available_sign_in_detailed,
4174 networkInfo.getExtraInfo());
4175 icon = R.drawable.stat_notify_rssi_in_range;
4176 break;
4177 }
4178
4179 Notification notification = new Notification();
4180 notification.when = 0;
4181 notification.icon = icon;
4182 notification.flags = Notification.FLAG_AUTO_CANCEL;
4183 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4184 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4185 Intent.FLAG_ACTIVITY_NEW_TASK);
4186 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4187 notification.tickerText = title;
4188 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4189
4190 log("setNotificaitionVisible: notify notificaiton=" + notification);
4191 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4192 } else {
4193 log("setNotificaitionVisible: cancel");
4194 notificationManager.cancel(NOTIFICATION_ID, 1);
4195 }
4196 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4197 }
4198
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004199 /** Location to an updatable file listing carrier provisioning urls.
4200 * An example:
4201 *
4202 * <?xml version="1.0" encoding="utf-8"?>
4203 * <provisioningUrls>
4204 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4205 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4206 * </provisioningUrls>
4207 */
4208 private static final String PROVISIONING_URL_PATH =
4209 "/data/misc/radio/provisioning_urls.xml";
4210 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004211
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004212 /** XML tag for root element. */
4213 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4214 /** XML tag for individual url */
4215 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4216 /** XML tag for redirected url */
4217 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4218 /** XML attribute for mcc */
4219 private static final String ATTR_MCC = "mcc";
4220 /** XML attribute for mnc */
4221 private static final String ATTR_MNC = "mnc";
4222
4223 private static final int REDIRECTED_PROVISIONING = 1;
4224 private static final int PROVISIONING = 2;
4225
4226 private String getProvisioningUrlBaseFromFile(int type) {
4227 FileReader fileReader = null;
4228 XmlPullParser parser = null;
4229 Configuration config = mContext.getResources().getConfiguration();
4230 String tagType;
4231
4232 switch (type) {
4233 case PROVISIONING:
4234 tagType = TAG_PROVISIONING_URL;
4235 break;
4236 case REDIRECTED_PROVISIONING:
4237 tagType = TAG_REDIRECTED_URL;
4238 break;
4239 default:
4240 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4241 type);
4242 }
4243
4244 try {
4245 fileReader = new FileReader(mProvisioningUrlFile);
4246 parser = Xml.newPullParser();
4247 parser.setInput(fileReader);
4248 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4249
4250 while (true) {
4251 XmlUtils.nextElement(parser);
4252
4253 String element = parser.getName();
4254 if (element == null) break;
4255
4256 if (element.equals(tagType)) {
4257 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4258 try {
4259 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4260 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4261 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4262 parser.next();
4263 if (parser.getEventType() == XmlPullParser.TEXT) {
4264 return parser.getText();
4265 }
4266 }
4267 }
4268 } catch (NumberFormatException e) {
4269 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4270 }
4271 }
4272 }
4273 return null;
4274 } catch (FileNotFoundException e) {
4275 loge("Carrier Provisioning Urls file not found");
4276 } catch (XmlPullParserException e) {
4277 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4278 } catch (IOException e) {
4279 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4280 } finally {
4281 if (fileReader != null) {
4282 try {
4283 fileReader.close();
4284 } catch (IOException e) {}
4285 }
4286 }
4287 return null;
4288 }
4289
Wink Saville42d4f082013-07-20 20:31:59 -07004290 @Override
4291 public String getMobileRedirectedProvisioningUrl() {
4292 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004293 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4294 if (TextUtils.isEmpty(url)) {
4295 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4296 }
4297 return url;
4298 }
4299
Wink Saville42d4f082013-07-20 20:31:59 -07004300 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004301 public String getMobileProvisioningUrl() {
4302 enforceConnectivityInternalPermission();
4303 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4304 if (TextUtils.isEmpty(url)) {
4305 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004306 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004307 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004308 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004309 }
Wink Saville8cf35602013-07-10 23:00:07 -07004310 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004311 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004312 String phoneNumber = mTelephonyManager.getLine1Number();
4313 if (TextUtils.isEmpty(phoneNumber)) {
4314 phoneNumber = "0000000000";
4315 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004316 url = String.format(url,
4317 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4318 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004319 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004320 }
4321
Wink Savilleab9321d2013-06-29 21:10:57 -07004322 return url;
4323 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004324
4325 private void onUserStart(int userId) {
4326 synchronized(mVpns) {
4327 Vpn userVpn = mVpns.get(userId);
4328 if (userVpn != null) {
4329 loge("Starting user already has a VPN");
4330 return;
4331 }
4332 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4333 mVpns.put(userId, userVpn);
4334 userVpn.startMonitoring(mContext, mTrackerHandler);
4335 }
4336 }
4337
4338 private void onUserStop(int userId) {
4339 synchronized(mVpns) {
4340 Vpn userVpn = mVpns.get(userId);
4341 if (userVpn == null) {
4342 loge("Stopping user has no VPN");
4343 return;
4344 }
4345 mVpns.delete(userId);
4346 }
4347 }
4348
4349 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4350 @Override
4351 public void onReceive(Context context, Intent intent) {
4352 final String action = intent.getAction();
4353 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4354 if (userId == UserHandle.USER_NULL) return;
4355
4356 if (Intent.ACTION_USER_STARTING.equals(action)) {
4357 onUserStart(userId);
4358 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4359 onUserStop(userId);
4360 }
4361 }
4362 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363}