blob: bb0d2483aea61ebe035c78709d1793a29a2a251c [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
Wink Savilled747cbc2013-08-07 16:22:47 -07002224 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002225 thisNet.captivePortalCheckComplete();
2226 }
2227
2228 /** @hide */
Wink Savilled747cbc2013-08-07 16:22:47 -07002229 @Override
Irfan Sheriffda6da092012-08-16 12:49:23 -07002230 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002231 enforceConnectivityInternalPermission();
Wink Savilled747cbc2013-08-07 16:22:47 -07002232 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002233 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002234 }
2235
Wink Savilled747cbc2013-08-07 16:22:47 -07002236 /** @hide */
2237 @Override
2238 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2239 enforceConnectivityInternalPermission();
2240 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2241 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2242 }
2243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002245 * Setup data activity tracking for the given network interface.
2246 *
2247 * Every {@code setupDataActivityTracking} should be paired with a
2248 * {@link removeDataActivityTracking} for cleanup.
2249 */
2250 private void setupDataActivityTracking(int type) {
2251 final NetworkStateTracker thisNet = mNetTrackers[type];
2252 final String iface = thisNet.getLinkProperties().getInterfaceName();
2253
2254 final int timeout;
2255
2256 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002257 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2258 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002259 0);
2260 // Canonicalize mobile network type
2261 type = ConnectivityManager.TYPE_MOBILE;
2262 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002263 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2264 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002265 0);
2266 } else {
2267 // do not track any other networks
2268 timeout = 0;
2269 }
2270
2271 if (timeout > 0 && iface != null) {
2272 try {
2273 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2274 } catch (RemoteException e) {
2275 }
2276 }
2277 }
2278
2279 /**
2280 * Remove data activity tracking when network disconnects.
2281 */
2282 private void removeDataActivityTracking(int type) {
2283 final NetworkStateTracker net = mNetTrackers[type];
2284 final String iface = net.getLinkProperties().getInterfaceName();
2285
2286 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2287 ConnectivityManager.TYPE_WIFI == type)) {
2288 try {
2289 // the call fails silently if no idletimer setup for this interface
2290 mNetd.removeIdleTimer(iface);
2291 } catch (RemoteException e) {
2292 }
2293 }
2294 }
2295
2296 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002297 * After a change in the connectivity state of a network. We're mainly
2298 * concerned with making sure that the list of DNS servers is set up
2299 * according to which networks are connected, and ensuring that the
2300 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002302 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002303 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubakerf336d722013-07-15 16:34:04 -07002304 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Savillee8222252011-07-13 13:44:13 -07002305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002307 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002308 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002310 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002311
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002312 LinkProperties curLp = mCurrentLinkProperties[netType];
2313 LinkProperties newLp = null;
2314
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002315 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002316 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002317 if (VDBG) {
2318 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2319 " doReset=" + doReset + " resetMask=" + resetMask +
2320 "\n curLp=" + curLp +
2321 "\n newLp=" + newLp);
2322 }
2323
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002324 if (curLp != null) {
2325 if (curLp.isIdenticalInterfaceName(newLp)) {
2326 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2327 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2328 for (LinkAddress linkAddr : car.removed) {
2329 if (linkAddr.getAddress() instanceof Inet4Address) {
2330 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2331 }
2332 if (linkAddr.getAddress() instanceof Inet6Address) {
2333 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2334 }
Wink Savillee8222252011-07-13 13:44:13 -07002335 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002336 if (DBG) {
2337 log("handleConnectivityChange: addresses changed" +
2338 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2339 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002340 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002341 } else {
2342 if (DBG) {
2343 log("handleConnectivityChange: address are the same reset per doReset" +
2344 " linkProperty[" + netType + "]:" +
2345 " resetMask=" + resetMask);
2346 }
Wink Savillee8222252011-07-13 13:44:13 -07002347 }
2348 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002349 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002350 if (DBG) {
2351 log("handleConnectivityChange: interface not not equivalent reset both" +
2352 " linkProperty[" + netType + "]:" +
2353 " resetMask=" + resetMask);
2354 }
Wink Savillee8222252011-07-13 13:44:13 -07002355 }
Wink Savillee8222252011-07-13 13:44:13 -07002356 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002357 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002358 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002359 }
2360 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002361 if (VDBG) {
2362 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2363 " doReset=" + doReset + " resetMask=" + resetMask +
2364 "\n curLp=" + curLp +
2365 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002368 mCurrentLinkProperties[netType] = newLp;
Chad Brubakerf336d722013-07-15 16:34:04 -07002369 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwaltec896c62011-06-15 12:22:07 -07002370
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002371 if (resetMask != 0 || resetDns) {
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002372 if (curLp != null) {
2373 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002374 if (TextUtils.isEmpty(iface) == false) {
2375 if (resetMask != 0) {
2376 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2377 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002378
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002379 // Tell VPN the interface is down. It is a temporary
2380 // but effective fix to make VPN aware of the change.
2381 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002382 synchronized(mVpns) {
2383 for (int i = 0; i < mVpns.size(); i++) {
2384 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2385 }
2386 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002387 }
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002388 }
Lorenzo Colitti4aa9bcf2013-03-20 19:22:58 +09002389 if (resetDns) {
2390 flushVmDnsCache();
2391 if (VDBG) log("resetting DNS cache for " + iface);
2392 try {
2393 mNetd.flushInterfaceDnsCache(iface);
2394 } catch (Exception e) {
2395 // never crash - catch them all
2396 if (DBG) loge("Exception resetting dns cache: " + e);
2397 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002398 }
Robert Greenwalt80eb63b2013-05-23 18:33:06 -07002399 } else {
2400 loge("Can't reset connection for type "+netType);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002401 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002402 }
2403 }
2404 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002405
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002406 // Update 464xlat state.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002407 NetworkStateTracker tracker = mNetTrackers[netType];
2408 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colittid2ef1e52013-03-28 14:13:43 +09002409 // If the connection was previously using clat, but is not using it now, stop the clat
2410 // daemon. Normally, this happens automatically when the connection disconnects, but if
2411 // the disconnect is not reported, or if the connection's LinkProperties changed for
2412 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2413 // still be running. If it's not running, then stopping it is a no-op.
2414 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2415 mClat.stopClat();
2416 }
2417 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09002418 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2419 mClat.startClat(tracker);
2420 } else {
2421 mClat.stopClat();
2422 }
2423 }
2424
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002425 // TODO: Temporary notifying upstread change to Tethering.
2426 // @see bug/4455071
2427 /** Notify TetheringService if interface name has been changed. */
2428 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002429 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002430 if (isTetheringSupported()) {
2431 mTethering.handleTetherIfaceChange();
2432 }
2433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 }
2435
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002436 /**
2437 * Add and remove routes using the old properties (null if not previously connected),
2438 * new properties (null if becoming disconnected). May even be double null, which
2439 * is a noop.
2440 * Uses isLinkDefault to determine if default routes should be set or conversely if
2441 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002442 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002443 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002444 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubakerf336d722013-07-15 16:34:04 -07002445 boolean isLinkDefault, boolean exempt) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002446 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002447 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2448 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002449 if (curLp != null) {
2450 // check for the delta between the current set and the new
Lorenzo Colittid1e0fae2013-07-31 23:23:21 +09002451 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002452 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002453 } else if (newLp != null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09002454 routeDiff.added = newLp.getAllRoutes();
Robert Greenwaltad55d352011-07-22 11:55:33 -07002455 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002456 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002457
Robert Greenwaltf125a092011-08-15 12:31:55 -07002458 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2459
Robert Greenwaltad55d352011-07-22 11:55:33 -07002460 for (RouteInfo r : routeDiff.removed) {
2461 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002462 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2463 }
2464 if (isLinkDefault == false) {
2465 // remove from a secondary route table
2466 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002467 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002468 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002469
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002470 if (!isLinkDefault) {
2471 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002472 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002473 // routes changed - remove all old dns entries and add new
2474 if (curLp != null) {
2475 for (InetAddress oldDns : curLp.getDnses()) {
2476 removeRouteToAddress(curLp, oldDns);
2477 }
2478 }
2479 if (newLp != null) {
2480 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002481 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002482 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002483 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002484 } else {
2485 // no change in routes, check for change in dns themselves
2486 for (InetAddress oldDns : dnsDiff.removed) {
2487 removeRouteToAddress(curLp, oldDns);
2488 }
2489 for (InetAddress newDns : dnsDiff.added) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002490 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002491 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002492 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002493 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002494
2495 for (RouteInfo r : routeDiff.added) {
2496 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubakerf336d722013-07-15 16:34:04 -07002497 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002498 } else {
2499 // add to a secondary route table
Chad Brubakerf336d722013-07-15 16:34:04 -07002500 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002501
2502 // many radios add a default route even when we don't want one.
2503 // remove the default route unless somebody else has asked for it
2504 String ifaceName = newLp.getInterfaceName();
Chad Brubakerf336d722013-07-15 16:34:04 -07002505 synchronized (mRoutesLock) {
2506 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2507 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2508 try {
2509 mNetd.removeRoute(ifaceName, r);
2510 } catch (Exception e) {
2511 // never crash - catch them all
2512 if (DBG) loge("Exception trying to remove a route: " + e);
2513 }
Robert Greenwalt979ee3c2013-04-05 16:49:32 -07002514 }
2515 }
2516 }
2517 }
2518
Robert Greenwaltf125a092011-08-15 12:31:55 -07002519 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002520 }
2521
2522
Irfan Sheriffd649c122010-06-09 15:39:36 -07002523 /**
2524 * Reads the network specific TCP buffer sizes from SystemProperties
2525 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2526 * wide use
2527 */
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002528 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07002529 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002530 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002531
Jeff Sharkey899223b2012-08-04 15:24:58 -07002532 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002533 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002534
2535 // Setting to default values so we won't be stuck to previous values
2536 key = "net.tcp.buffersize.default";
2537 bufferSizes = SystemProperties.get(key);
2538 }
2539
2540 // Set values in kernel
2541 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002542 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002543 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002544 + "] which comes from [" + key + "]");
2545 }
2546 setBufferSize(bufferSizes);
2547 }
2548 }
2549
2550 /**
2551 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2552 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2553 *
2554 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2555 * writeMin, writeInitial, writeMax"
2556 */
2557 private void setBufferSize(String bufferSizes) {
2558 try {
2559 String[] values = bufferSizes.split(",");
2560
2561 if (values.length == 6) {
2562 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002563 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2564 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2565 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2566 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2567 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2568 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002569 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002570 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002571 }
2572 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002573 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002574 }
2575 }
2576
Robert Greenwalt42acef32009-08-12 16:08:25 -07002577 /**
2578 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2579 * on the highest priority active net which this process requested.
2580 * If there aren't any, clear it out
2581 */
Mattias Falk8b47b362011-08-23 14:15:13 +02002582 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt42acef32009-08-12 16:08:25 -07002583 {
Mattias Falk8b47b362011-08-23 14:15:13 +02002584 if (VDBG) log("reassessPidDns for pid " + pid);
2585 Integer myPid = new Integer(pid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002586 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002587 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002588 continue;
2589 }
2590 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002591 if (nt.getNetworkInfo().isConnected() &&
2592 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002593 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002594 if (p == null) continue;
Mattias Falk8b47b362011-08-23 14:15:13 +02002595 if (mNetRequestersPids[i].contains(myPid)) {
2596 try {
2597 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2598 } catch (Exception e) {
2599 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002600 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002601 return;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002602 }
2603 }
2604 }
2605 // nothing found - delete
Mattias Falk8b47b362011-08-23 14:15:13 +02002606 try {
2607 mNetd.clearDnsInterfaceForPid(pid);
2608 } catch (Exception e) {
2609 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002610 }
2611 }
2612
Mattias Falk8b47b362011-08-23 14:15:13 +02002613 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07002614 /*
2615 * Tell the VMs to toss their DNS caches
2616 */
2617 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2618 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002619 /*
2620 * Connectivity events can happen before boot has completed ...
2621 */
2622 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002623 final long ident = Binder.clearCallingIdentity();
2624 try {
2625 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2626 } finally {
2627 Binder.restoreCallingIdentity(ident);
2628 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002629 }
2630
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002631 // Caller must grab mDnsLock.
Mattias Falk8b47b362011-08-23 14:15:13 +02002632 private void updateDnsLocked(String network, String iface,
Chad Brubaker20a7e882013-07-23 17:13:36 -07002633 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002634 int last = 0;
2635 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falk8b47b362011-08-23 14:15:13 +02002636 dnses = new ArrayList();
2637 dnses.add(mDefaultDns);
2638 if (DBG) {
2639 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwalt63837f42013-01-19 00:34:07 +00002640 }
Robert Greenwalt63837f42013-01-19 00:34:07 +00002641 }
2642
Mattias Falk8b47b362011-08-23 14:15:13 +02002643 try {
2644 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker20a7e882013-07-23 17:13:36 -07002645 if (defaultDns) {
2646 mNetd.setDefaultInterfaceForDns(iface);
2647 }
2648
Robert Greenwalt0dd19a82013-02-11 15:25:10 -08002649 for (InetAddress dns : dnses) {
2650 ++last;
2651 String key = "net.dns" + last;
2652 String value = dns.getHostAddress();
2653 SystemProperties.set(key, value);
2654 }
2655 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2656 String key = "net.dns" + i;
2657 SystemProperties.set(key, "");
2658 }
2659 mNumDnsEntries = last;
Mattias Falk8b47b362011-08-23 14:15:13 +02002660 } catch (Exception e) {
2661 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalt63837f42013-01-19 00:34:07 +00002662 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002663 }
2664
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002665 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002666 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002667 NetworkStateTracker nt = mNetTrackers[netType];
2668 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002669 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002670 if (p == null) return;
2671 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002672 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002673 String network = nt.getNetworkInfo().getTypeName();
2674 synchronized (mDnsLock) {
Chad Brubakerb98703e2013-07-23 17:44:41 -07002675 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002676 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002677 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002678 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002679 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002680 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002681 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002682 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002683 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002684 // set per-pid dns for attached secondary nets
Mattias Falk8b47b362011-08-23 14:15:13 +02002685 List<Integer> pids = mNetRequestersPids[netType];
2686 for (Integer pid : pids) {
2687 try {
2688 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2689 } catch (Exception e) {
2690 Slog.e(TAG, "exception setting interface for pid: " + e);
2691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
2693 }
Mattias Falk8b47b362011-08-23 14:15:13 +02002694 flushVmDnsCache();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002696 }
2697
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002698 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002699 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2700 NETWORK_RESTORE_DELAY_PROP_NAME);
2701 if(restoreDefaultNetworkDelayStr != null &&
2702 restoreDefaultNetworkDelayStr.length() != 0) {
2703 try {
2704 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2705 } catch (NumberFormatException e) {
2706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002708 // if the system property isn't set, use the value for the apn type
2709 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2710
2711 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2712 (mNetConfigs[networkType] != null)) {
2713 ret = mNetConfigs[networkType].restoreTime;
2714 }
2715 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717
2718 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002719 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2720 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002721 if (mContext.checkCallingOrSelfPermission(
2722 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002724 pw.println("Permission Denial: can't dump ConnectivityService " +
2725 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2726 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 return;
2728 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002729
2730 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002732 for (int i = 0; i < mNetTrackers.length; i++) {
2733 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002734 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002735 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2736 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002737 if (nst.getNetworkInfo().isConnected()) {
2738 pw.println("Active network: " + nst.getNetworkInfo().
2739 getTypeName());
2740 }
2741 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002742 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002743 pw.println(nst);
2744 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002745 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002748
2749 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002750 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002751 for (int net : mPriorityList) {
2752 String pidString = net + ": ";
Mattias Falk8b47b362011-08-23 14:15:13 +02002753 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002754 pidString = pidString + pid.toString() + ", ";
2755 }
2756 pw.println(pidString);
2757 }
2758 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002759 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002760
2761 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002762 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002763 for (Object requester : mFeatureUsers) {
2764 pw.println(requester.toString());
2765 }
2766 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002767 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002768
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002769 synchronized (this) {
2770 pw.println("NetworkTranstionWakeLock is currently " +
2771 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2772 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2773 }
2774 pw.println();
2775
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002776 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002777
2778 if (mInetLog != null) {
2779 pw.println();
2780 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002781 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002782 for(int i = 0; i < mInetLog.size(); i++) {
2783 pw.println(mInetLog.get(i));
2784 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002785 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 }
2788
Robert Greenwalt42acef32009-08-12 16:08:25 -07002789 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002790 private class NetworkStateTrackerHandler extends Handler {
2791 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002792 super(looper);
2793 }
2794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 @Override
2796 public void handleMessage(Message msg) {
2797 NetworkInfo info;
2798 switch (msg.what) {
2799 case NetworkStateTracker.EVENT_STATE_CHANGED:
2800 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002801 int type = info.getType();
2802 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002803
Wink Savillec9acde92011-09-21 11:05:43 -07002804 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2805 (state == NetworkInfo.State.DISCONNECTED)) {
2806 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002807 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002808 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810
Wink Savillefde1ac92013-07-16 17:16:37 -07002811 // After booting we'll check once for mobile provisioning
2812 // if we've provisioned by and connected.
2813 if (!mFirstProvisioningCheckStarted
2814 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2815 Settings.Global.DEVICE_PROVISIONED, 0))
2816 && (state == NetworkInfo.State.CONNECTED)) {
2817 log("check provisioning after booting");
2818 mFirstProvisioningCheckStarted = true;
2819 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2820 }
2821
Jeff Sharkey2528b502012-11-09 15:57:02 -08002822 EventLogTags.writeConnectivityStateChanged(
2823 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002824
2825 if (info.getDetailedState() ==
2826 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002828 } else if (info.getDetailedState() ==
2829 DetailedState.CAPTIVE_PORTAL_CHECK) {
2830 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002831 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002833 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002835 // the logic here is, handle SUSPENDED the same as
2836 // DISCONNECTED. The only difference being we are
2837 // broadcasting an intent with NetworkInfo that's
2838 // suspended. This allows the applications an
2839 // opportunity to handle DISCONNECTED and SUSPENDED
2840 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002842 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 handleConnect(info);
2844 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002845 if (mLockdownTracker != null) {
2846 mLockdownTracker.onNetworkInfoChanged(info);
2847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002850 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002851 // TODO: Temporary allowing network configuration
2852 // change not resetting sockets.
2853 // @see bug/4455071
2854 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002856 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2857 info = (NetworkInfo) msg.obj;
2858 type = info.getType();
2859 updateNetworkSettings(mNetTrackers[type]);
2860 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002861 }
2862 }
2863 }
2864
2865 private class InternalHandler extends Handler {
2866 public InternalHandler(Looper looper) {
2867 super(looper);
2868 }
2869
2870 @Override
2871 public void handleMessage(Message msg) {
2872 NetworkInfo info;
2873 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002874 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002875 String causedBy = null;
2876 synchronized (ConnectivityService.this) {
2877 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2878 mNetTransitionWakeLock.isHeld()) {
2879 mNetTransitionWakeLock.release();
2880 causedBy = mNetTransitionWakeLockCausedBy;
2881 }
2882 }
2883 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002884 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002885 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002886 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002887 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002888 FeatureUser u = (FeatureUser)msg.obj;
2889 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002890 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002891 case EVENT_INET_CONDITION_CHANGE:
2892 {
2893 int netType = msg.arg1;
2894 int condition = msg.arg2;
2895 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002896 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002897 }
2898 case EVENT_INET_CONDITION_HOLD_END:
2899 {
2900 int netType = msg.arg1;
2901 int sequence = msg.arg2;
Wink Saville5b7573e2013-01-31 00:30:13 +00002902 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002903 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002904 }
2905 case EVENT_SET_NETWORK_PREFERENCE:
2906 {
2907 int preference = msg.arg1;
2908 handleSetNetworkPreference(preference);
2909 break;
2910 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002911 case EVENT_SET_MOBILE_DATA:
2912 {
2913 boolean enabled = (msg.arg1 == ENABLED);
2914 handleSetMobileData(enabled);
2915 break;
2916 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2918 {
2919 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002920 break;
2921 }
2922 case EVENT_SET_DEPENDENCY_MET:
2923 {
2924 boolean met = (msg.arg1 == ENABLED);
2925 handleSetDependencyMet(msg.arg2, met);
2926 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002927 }
Wink Saville628b0852011-08-04 15:01:58 -07002928 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2929 {
2930 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002931 sendStickyBroadcast(intent);
2932 break;
2933 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002934 case EVENT_SET_POLICY_DATA_ENABLE: {
2935 final int networkType = msg.arg1;
2936 final boolean enabled = msg.arg2 == ENABLED;
2937 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002938 break;
2939 }
2940 case EVENT_VPN_STATE_CHANGED: {
2941 if (mLockdownTracker != null) {
2942 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2943 }
2944 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002945 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002946 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2947 int tag = mEnableFailFastMobileDataTag.get();
2948 if (msg.arg1 == tag) {
2949 MobileDataStateTracker mobileDst =
2950 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2951 if (mobileDst != null) {
2952 mobileDst.setEnableFailFastMobileData(msg.arg2);
2953 }
2954 } else {
2955 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2956 + " != tag:" + tag);
2957 }
2958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
2960 }
2961 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002962
2963 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002964 public int tether(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.tether(iface);
2969 } else {
2970 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2971 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002972 }
2973
2974 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002975 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002976 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002977
2978 if (isTetheringSupported()) {
2979 return mTethering.untether(iface);
2980 } else {
2981 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2982 }
2983 }
2984
2985 // javadoc from interface
2986 public int getLastTetherError(String iface) {
2987 enforceTetherAccessPermission();
2988
2989 if (isTetheringSupported()) {
2990 return mTethering.getLastTetherError(iface);
2991 } else {
2992 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2993 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002994 }
2995
2996 // TODO - proper iface API for selection by property, inspection, etc
2997 public String[] getTetherableUsbRegexs() {
2998 enforceTetherAccessPermission();
2999 if (isTetheringSupported()) {
3000 return mTethering.getTetherableUsbRegexs();
3001 } else {
3002 return new String[0];
3003 }
3004 }
3005
3006 public String[] getTetherableWifiRegexs() {
3007 enforceTetherAccessPermission();
3008 if (isTetheringSupported()) {
3009 return mTethering.getTetherableWifiRegexs();
3010 } else {
3011 return new String[0];
3012 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003013 }
3014
Danica Chang6fdd0c62010-08-11 14:54:43 -07003015 public String[] getTetherableBluetoothRegexs() {
3016 enforceTetherAccessPermission();
3017 if (isTetheringSupported()) {
3018 return mTethering.getTetherableBluetoothRegexs();
3019 } else {
3020 return new String[0];
3021 }
3022 }
3023
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003024 public int setUsbTethering(boolean enable) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08003025 enforceTetherChangePermission();
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003026 if (isTetheringSupported()) {
3027 return mTethering.setUsbTethering(enable);
3028 } else {
3029 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3030 }
3031 }
3032
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003033 // TODO - move iface listing, queries, etc to new module
3034 // javadoc from interface
3035 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003036 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003037 return mTethering.getTetherableIfaces();
3038 }
3039
3040 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003041 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003042 return mTethering.getTetheredIfaces();
3043 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003044
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07003045 @Override
3046 public String[] getTetheredIfacePairs() {
3047 enforceTetherAccessPermission();
3048 return mTethering.getTetheredIfacePairs();
3049 }
3050
Robert Greenwalt5a735062010-03-02 17:25:02 -08003051 public String[] getTetheringErroredIfaces() {
3052 enforceTetherAccessPermission();
3053 return mTethering.getErroredIfaces();
3054 }
3055
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003056 // if ro.tether.denied = true we default to no tethering
3057 // gservices could set the secure setting to 1 though to enable it on a build where it
3058 // had previously been turned off.
3059 public boolean isTetheringSupported() {
3060 enforceTetherAccessPermission();
3061 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003062 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3063 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003064 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3065 mTethering.getTetherableWifiRegexs().length != 0 ||
3066 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3067 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003068 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003069
3070 // An API NetworkStateTrackers can call when they lose their network.
3071 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3072 // whichever happens first. The timer is started by the first caller and not
3073 // restarted by subsequent callers.
3074 public void requestNetworkTransitionWakelock(String forWhom) {
3075 enforceConnectivityInternalPermission();
3076 synchronized (this) {
3077 if (mNetTransitionWakeLock.isHeld()) return;
3078 mNetTransitionWakeLockSerialNumber++;
3079 mNetTransitionWakeLock.acquire();
3080 mNetTransitionWakeLockCausedBy = forWhom;
3081 }
3082 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07003083 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003084 mNetTransitionWakeLockSerialNumber, 0),
3085 mNetTransitionWakeLockTimeout);
3086 return;
3087 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003088
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003089 // 100 percent is full good, 0 is full bad.
3090 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003091 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003092 mContext.enforceCallingOrSelfPermission(
3093 android.Manifest.permission.STATUS_BAR,
3094 "ConnectivityService");
3095
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07003096 if (DBG) {
3097 int pid = getCallingPid();
3098 int uid = getCallingUid();
3099 String s = pid + "(" + uid + ") reports inet is " +
3100 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3101 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3102 mInetLog.add(s);
3103 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3104 mInetLog.remove(0);
3105 }
3106 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003107 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003108 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3109 }
3110
3111 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003112 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003113 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003114 return;
3115 }
3116 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07003117 if (DBG) log("handleInetConditionChange: net=" + netType +
3118 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003119 return;
3120 }
Wink Savillec9acde92011-09-21 11:05:43 -07003121 if (VDBG) {
3122 log("handleInetConditionChange: net=" +
3123 netType + ", condition=" + condition +
Wink Saville5b7573e2013-01-31 00:30:13 +00003124 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillec9acde92011-09-21 11:05:43 -07003125 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003126 mDefaultInetCondition = condition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003127 int delay;
3128 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003129 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003130 // setup a new hold to debounce this
Wink Saville5b7573e2013-01-31 00:30:13 +00003131 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003132 delay = Settings.Global.getInt(mContext.getContentResolver(),
3133 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003134 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003135 delay = Settings.Global.getInt(mContext.getContentResolver(),
3136 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003137 }
3138 mInetConditionChangeInFlight = true;
3139 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville5b7573e2013-01-31 00:30:13 +00003140 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003141 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003142 // we've set the new condition, when this hold ends that will get picked up
3143 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003144 }
3145 }
3146
Wink Saville5b7573e2013-01-31 00:30:13 +00003147 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003148 if (DBG) {
Wink Saville5b7573e2013-01-31 00:30:13 +00003149 log("handleInetConditionHoldEnd: net=" + netType +
3150 ", condition=" + mDefaultInetCondition +
3151 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003152 }
3153 mInetConditionChangeInFlight = false;
3154
3155 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003156 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003157 return;
3158 }
3159 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003160 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003161 return;
3162 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003163 // TODO: Figure out why this optimization sometimes causes a
3164 // change in mDefaultInetCondition to be missed and the
3165 // UI to not be updated.
3166 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3167 // if (DBG) log("no change in condition - aborting");
3168 // return;
3169 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003170 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3171 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003172 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003173 return;
3174 }
Wink Saville5b7573e2013-01-31 00:30:13 +00003175 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003176 sendInetConditionBroadcast(networkInfo);
3177 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003178 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003179
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003180 public ProxyProperties getProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003181 // this information is already available as a world read/writable jvm property
3182 // so this API change wouldn't have a benifit. It also breaks the passing
3183 // of proxy info to all the JVMs.
3184 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003185 synchronized (mProxyLock) {
Jason Monk602b2322013-07-03 17:04:33 -04003186 ProxyProperties ret = mGlobalProxy;
3187 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3188 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003189 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003190 }
3191
3192 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003193 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003194
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003195 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003196 if (proxyProperties == mGlobalProxy) return;
3197 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3198 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3199
3200 String host = "";
3201 int port = 0;
3202 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003203 String pacFileUrl = "";
3204 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3205 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003206 mGlobalProxy = new ProxyProperties(proxyProperties);
3207 host = mGlobalProxy.getHost();
3208 port = mGlobalProxy.getPort();
3209 exclList = mGlobalProxy.getExclusionList();
Jason Monk602b2322013-07-03 17:04:33 -04003210 if (proxyProperties.getPacFileUrl() != null) {
3211 pacFileUrl = proxyProperties.getPacFileUrl();
3212 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003213 } else {
3214 mGlobalProxy = null;
3215 }
3216 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003217 final long token = Binder.clearCallingIdentity();
3218 try {
3219 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3220 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3221 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3222 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003223 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003224 } finally {
3225 Binder.restoreCallingIdentity(token);
3226 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003227 }
3228
3229 if (mGlobalProxy == null) {
3230 proxyProperties = mDefaultProxy;
3231 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003232 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003233 }
3234
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003235 private void loadGlobalProxy() {
3236 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003237 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3238 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3239 String exclList = Settings.Global.getString(res,
3240 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003241 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3242 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3243 ProxyProperties proxyProperties;
3244 if (!TextUtils.isEmpty(pacFileUrl)) {
3245 proxyProperties = new ProxyProperties(pacFileUrl);
3246 } else {
3247 proxyProperties = new ProxyProperties(host, port, exclList);
3248 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003249 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003250 mGlobalProxy = proxyProperties;
3251 }
3252 }
3253 }
3254
Robert Greenwalt434203a2010-10-11 16:00:27 -07003255 public ProxyProperties getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003256 // this information is already available as a world read/writable jvm property
3257 // so this API change wouldn't have a benifit. It also breaks the passing
3258 // of proxy info to all the JVMs.
3259 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003260 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 return mGlobalProxy;
3262 }
3263 }
3264
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003265 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003266 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3267 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003268 proxy = null;
3269 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003270 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003272 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003273 mDefaultProxy = proxy;
3274
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003275 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003276 if (!mDefaultProxyDisabled) {
3277 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003278 }
3279 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 }
3281
3282 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003283 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3284 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003285 if (!TextUtils.isEmpty(proxy)) {
3286 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003287 if (data.length == 0) {
3288 return;
3289 }
3290
Robert Greenwalt434203a2010-10-11 16:00:27 -07003291 String proxyHost = data[0];
3292 int proxyPort = 8080;
3293 if (data.length > 1) {
3294 try {
3295 proxyPort = Integer.parseInt(data[1]);
3296 } catch (NumberFormatException e) {
3297 return;
3298 }
3299 }
3300 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3301 setGlobalProxy(p);
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003302 } else {
3303 setGlobalProxy(null);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003304 }
3305 }
3306
3307 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003308 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monk602b2322013-07-03 17:04:33 -04003309 mPacManager.setCurrentProxyScriptUrl(proxy);
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003310 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003311 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003312 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3313 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003315 final long ident = Binder.clearCallingIdentity();
3316 try {
3317 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3318 } finally {
3319 Binder.restoreCallingIdentity(ident);
3320 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 }
3322
3323 private static class SettingsObserver extends ContentObserver {
3324 private int mWhat;
3325 private Handler mHandler;
3326 SettingsObserver(Handler handler, int what) {
3327 super(handler);
3328 mHandler = handler;
3329 mWhat = what;
3330 }
3331
3332 void observe(Context context) {
3333 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003334 resolver.registerContentObserver(Settings.Global.getUriFor(
3335 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003336 }
3337
3338 @Override
3339 public void onChange(boolean selfChange) {
3340 mHandler.obtainMessage(mWhat).sendToTarget();
3341 }
3342 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003343
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003344 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003345 Slog.d(TAG, s);
3346 }
3347
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003348 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003349 Slog.e(TAG, s);
3350 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003351
repo syncaea743a2011-07-29 23:55:49 -07003352 int convertFeatureToNetworkType(int networkType, String feature) {
3353 int usedNetworkType = networkType;
3354
3355 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3356 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3357 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3358 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3359 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3360 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3361 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3362 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3363 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3364 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3365 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3366 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3367 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3368 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3369 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3370 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3371 } else {
3372 Slog.e(TAG, "Can't match any mobile netTracker!");
3373 }
3374 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3375 if (TextUtils.equals(feature, "p2p")) {
3376 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3377 } else {
3378 Slog.e(TAG, "Can't match any wifi netTracker!");
3379 }
3380 } else {
3381 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003382 }
repo syncaea743a2011-07-29 23:55:49 -07003383 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003384 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003385
3386 private static <T> T checkNotNull(T value, String message) {
3387 if (value == null) {
3388 throw new NullPointerException(message);
3389 }
3390 return value;
3391 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003392
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003393 /**
3394 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003395 * VpnBuilder and not available in ConnectivityManager. Permissions
3396 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003397 * @hide
3398 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003399 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003400 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003401 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003402 try {
3403 int type = mActiveDefaultNetwork;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003404 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003405 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003406 synchronized(mVpns) {
3407 mVpns.get(user).protect(socket,
3408 mNetTrackers[type].getLinkProperties().getInterfaceName());
3409 }
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003410 return true;
3411 }
3412 } catch (Exception e) {
3413 // ignore
3414 } finally {
3415 try {
3416 socket.close();
3417 } catch (Exception e) {
3418 // ignore
3419 }
3420 }
3421 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003422 }
3423
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003424 /**
3425 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003426 * and not available in ConnectivityManager. Permissions are checked
3427 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003428 * @hide
3429 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003430 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003431 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003432 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003433 int user = UserHandle.getUserId(Binder.getCallingUid());
3434 synchronized(mVpns) {
3435 return mVpns.get(user).prepare(oldPackage, newPackage);
3436 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003437 }
3438
Chad Brubakerd475c702013-07-11 13:29:30 -07003439 @Override
3440 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3441 enforceMarkNetworkSocketPermission();
3442 final long token = Binder.clearCallingIdentity();
3443 try {
3444 int mark = mNetd.getMarkForUid(uid);
3445 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3446 if (mark == -1) {
3447 mark = 0;
3448 }
3449 NetworkUtils.markSocket(socket.getFd(), mark);
3450 } catch (RemoteException e) {
3451 } finally {
3452 Binder.restoreCallingIdentity(token);
3453 }
3454 }
3455
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003456 /**
3457 * Configure a TUN interface and return its file descriptor. Parameters
3458 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003459 * and not available in ConnectivityManager. Permissions are checked in
3460 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003461 * @hide
3462 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003463 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003464 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003465 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003466 int user = UserHandle.getUserId(Binder.getCallingUid());
3467 synchronized(mVpns) {
3468 return mVpns.get(user).establish(config);
3469 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003470 }
3471
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003472 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003473 * Start legacy VPN, controlling native daemons as needed. Creates a
3474 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003475 */
3476 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003477 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003478 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003479 final LinkProperties egress = getActiveLinkProperties();
3480 if (egress == null) {
3481 throw new IllegalStateException("Missing active network connection");
3482 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003483 int user = UserHandle.getUserId(Binder.getCallingUid());
3484 synchronized(mVpns) {
3485 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3486 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003487 }
3488
3489 /**
3490 * Return the information of the ongoing legacy VPN. This method is used
3491 * by VpnSettings and not available in ConnectivityManager. Permissions
3492 * are checked in Vpn class.
3493 * @hide
3494 */
3495 @Override
3496 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003497 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003498 int user = UserHandle.getUserId(Binder.getCallingUid());
3499 synchronized(mVpns) {
3500 return mVpns.get(user).getLegacyVpnInfo();
3501 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003502 }
3503
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003504 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003505 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3506 * not available in ConnectivityManager.
3507 * Permissions are checked in Vpn class.
3508 * @hide
3509 */
3510 @Override
3511 public VpnConfig getVpnConfig() {
3512 int user = UserHandle.getUserId(Binder.getCallingUid());
3513 synchronized(mVpns) {
3514 return mVpns.get(user).getVpnConfig();
3515 }
3516 }
3517
3518 /**
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003519 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3520 * through NetworkStateTracker since it works differently. For example, it
3521 * needs to override DNS servers but never takes the default routes. It
3522 * relies on another data network, and it could keep existing connections
3523 * alive after reconnecting, switching between networks, or even resuming
3524 * from deep sleep. Calls from applications should be done synchronously
3525 * to avoid race conditions. As these are all hidden APIs, refactoring can
3526 * be done whenever a better abstraction is developed.
3527 */
3528 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003529 private VpnCallback() {
3530 }
3531
Jeff Sharkey899223b2012-08-04 15:24:58 -07003532 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003533 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003534 }
3535
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003536 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003537 if (dnsServers == null) {
3538 restore();
3539 return;
3540 }
3541
3542 // Convert DNS servers into addresses.
3543 List<InetAddress> addresses = new ArrayList<InetAddress>();
3544 for (String address : dnsServers) {
3545 // Double check the addresses and remove invalid ones.
3546 try {
3547 addresses.add(InetAddress.parseNumericAddress(address));
3548 } catch (Exception e) {
3549 // ignore
3550 }
3551 }
3552 if (addresses.isEmpty()) {
3553 restore();
3554 return;
3555 }
3556
3557 // Concatenate search domains into a string.
3558 StringBuilder buffer = new StringBuilder();
3559 if (searchDomains != null) {
3560 for (String domain : searchDomains) {
3561 buffer.append(domain).append(' ');
3562 }
3563 }
3564 String domains = buffer.toString().trim();
3565
3566 // Apply DNS changes.
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003567 synchronized (mDnsLock) {
Chad Brubaker20a7e882013-07-23 17:13:36 -07003568 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003569 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003570
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003571 // Temporarily disable the default proxy (not global).
3572 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003573 mDefaultProxyDisabled = true;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003574 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003575 sendProxyBroadcast(null);
3576 }
3577 }
3578
3579 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003580 }
3581
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003582 public void restore() {
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003583 synchronized (mProxyLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003584 mDefaultProxyDisabled = false;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003585 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003586 sendProxyBroadcast(mDefaultProxy);
3587 }
3588 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003589 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003590
3591 public void protect(ParcelFileDescriptor socket) {
3592 try {
3593 final int mark = mNetd.getMarkForProtect();
3594 NetworkUtils.markSocket(socket.getFd(), mark);
3595 } catch (RemoteException e) {
3596 }
3597 }
3598
3599 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3600 for (RouteInfo route : routes) {
3601 try {
3602 mNetd.setMarkedForwardingRoute(interfaze, route);
3603 } catch (RemoteException e) {
3604 }
3605 }
3606 }
3607
3608 public void setMarkedForwarding(String interfaze) {
3609 try {
3610 mNetd.setMarkedForwarding(interfaze);
3611 } catch (RemoteException e) {
3612 }
3613 }
3614
3615 public void clearMarkedForwarding(String interfaze) {
3616 try {
3617 mNetd.clearMarkedForwarding(interfaze);
3618 } catch (RemoteException e) {
3619 }
3620 }
3621
3622 public void addUserForwarding(String interfaze, int uid) {
3623 int uidStart = uid * UserHandle.PER_USER_RANGE;
3624 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3625 addUidForwarding(interfaze, uidStart, uidEnd);
3626 }
3627
3628 public void clearUserForwarding(String interfaze, int uid) {
3629 int uidStart = uid * UserHandle.PER_USER_RANGE;
3630 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3631 clearUidForwarding(interfaze, uidStart, uidEnd);
3632 }
3633
3634 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3635 try {
3636 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3637 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3638 } catch (RemoteException e) {
3639 }
3640
3641 }
3642
3643 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3644 try {
3645 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3646 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3647 } catch (RemoteException e) {
3648 }
3649
3650 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003651 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003652
3653 @Override
3654 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003655 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3656 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3657 return false;
3658 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003659
3660 // Tear down existing lockdown if profile was removed
3661 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3662 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003663 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003664 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3665 return false;
3666 }
3667
3668 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3669 final VpnProfile profile = VpnProfile.decode(
3670 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003671 int user = UserHandle.getUserId(Binder.getCallingUid());
3672 synchronized(mVpns) {
3673 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3674 profile));
3675 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003676 } else {
3677 setLockdownTracker(null);
3678 }
3679
3680 return true;
3681 }
3682
3683 /**
3684 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3685 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3686 */
3687 private void setLockdownTracker(LockdownVpnTracker tracker) {
3688 // Shutdown any existing tracker
3689 final LockdownVpnTracker existing = mLockdownTracker;
3690 mLockdownTracker = null;
3691 if (existing != null) {
3692 existing.shutdown();
3693 }
3694
3695 try {
3696 if (tracker != null) {
3697 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003698 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003699 mLockdownTracker = tracker;
3700 mLockdownTracker.init();
3701 } else {
3702 mNetd.setFirewallEnabled(false);
3703 }
3704 } catch (RemoteException e) {
3705 // ignored; NMS lives inside system_server
3706 }
3707 }
3708
3709 private void throwIfLockdownEnabled() {
3710 if (mLockdownEnabled) {
3711 throw new IllegalStateException("Unavailable in lockdown mode");
3712 }
3713 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003714
3715 public void supplyMessenger(int networkType, Messenger messenger) {
3716 enforceConnectivityInternalPermission();
3717
3718 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3719 mNetTrackers[networkType].supplyMessenger(messenger);
3720 }
3721 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003722
3723 public int findConnectionTypeForIface(String iface) {
3724 enforceConnectivityInternalPermission();
3725
3726 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3727 for (NetworkStateTracker tracker : mNetTrackers) {
3728 if (tracker != null) {
3729 LinkProperties lp = tracker.getLinkProperties();
3730 if (lp != null && iface.equals(lp.getInterfaceName())) {
3731 return tracker.getNetworkInfo().getType();
3732 }
3733 }
3734 }
3735 return ConnectivityManager.TYPE_NONE;
3736 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003737
3738 /**
3739 * Have mobile data fail fast if enabled.
3740 *
3741 * @param enabled DctConstants.ENABLED/DISABLED
3742 */
3743 private void setEnableFailFastMobileData(int enabled) {
3744 int tag;
3745
3746 if (enabled == DctConstants.ENABLED) {
3747 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3748 } else {
3749 tag = mEnableFailFastMobileDataTag.get();
3750 }
3751 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3752 enabled));
3753 }
3754
3755 @Override
Wink Savillec2fee242013-07-19 09:27:56 -07003756 public int checkMobileProvisioning(final boolean sendNotification, int suggestedTimeOutMs,
Wink Savilleab9321d2013-06-29 21:10:57 -07003757 final ResultReceiver resultReceiver) {
3758 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3759 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3760 + " resultReceiver=" + resultReceiver);
3761 enforceChangePermission();
3762
Wink Savillefde1ac92013-07-16 17:16:37 -07003763 mFirstProvisioningCheckStarted = true;
3764
Wink Savilleab9321d2013-06-29 21:10:57 -07003765 int timeOutMs = suggestedTimeOutMs;
3766 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3767 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3768 }
3769
Wink Saville68e6c642013-07-02 10:55:14 -07003770 // Check that mobile networks are supported
3771 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3772 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3773 log("checkMobileProvisioning: X no mobile network");
3774 if (resultReceiver != null) {
3775 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3776 }
3777 return timeOutMs;
3778 }
3779
Wink Savilleab9321d2013-06-29 21:10:57 -07003780 final long token = Binder.clearCallingIdentity();
3781 try {
3782 CheckMp checkMp = new CheckMp(mContext, this);
3783 CheckMp.CallBack cb = new CheckMp.CallBack() {
3784 @Override
3785 void onComplete(Integer result) {
3786 log("CheckMp.onComplete: result=" + result);
3787 if (resultReceiver != null) {
3788 log("CheckMp.onComplete: send result");
3789 resultReceiver.send(result, null);
3790 }
Wink Savillec2fee242013-07-19 09:27:56 -07003791 if (!sendNotification) {
3792 log("CheckMp.onComplete: done, not sending notification");
3793 return;
3794 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003795 NetworkInfo ni =
3796 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3797 switch(result) {
3798 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3799 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3800 log("CheckMp.onComplete: ignore, connected or no connection");
3801 break;
3802 }
3803 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3804 log("CheckMp.onComplete: warm sim");
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003805 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003806 if (TextUtils.isEmpty(url)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003807 url = getMobileRedirectedProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003808 }
3809 if (TextUtils.isEmpty(url) == false) {
3810 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3811 setNotificationVisible(true, ni, url);
3812 } else {
3813 log("CheckMp.onComplete: warm sim (redirected), no url");
3814 }
3815 break;
3816 }
3817 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3818 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003819 String url = getMobileProvisioningUrl();
Wink Savilleab9321d2013-06-29 21:10:57 -07003820 if (TextUtils.isEmpty(url) == false) {
3821 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3822 setNotificationVisible(true, ni, url);
3823 } else {
3824 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3825 }
3826 break;
3827 }
3828 default: {
3829 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3830 break;
3831 }
3832 }
3833 }
3834 };
3835 CheckMp.Params params =
3836 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3837 log("checkMobileProvisioning: params=" + params);
3838 setNotificationVisible(false, null, null);
3839 checkMp.execute(params);
3840 } finally {
3841 Binder.restoreCallingIdentity(token);
3842 log("checkMobileProvisioning: X");
3843 }
3844 return timeOutMs;
3845 }
3846
3847 static class CheckMp extends
3848 AsyncTask<CheckMp.Params, Void, Integer> {
3849 private static final String CHECKMP_TAG = "CheckMp";
3850 public static final int MAX_TIMEOUT_MS = 60000;
3851 private static final int SOCKET_TIMEOUT_MS = 5000;
3852 private Context mContext;
3853 private ConnectivityService mCs;
3854 private TelephonyManager mTm;
3855 private Params mParams;
3856
3857 /**
3858 * Parameters for AsyncTask.execute
3859 */
3860 static class Params {
3861 private String mUrl;
3862 private long mTimeOutMs;
3863 private CallBack mCb;
3864
3865 Params(String url, long timeOutMs, CallBack cb) {
3866 mUrl = url;
3867 mTimeOutMs = timeOutMs;
3868 mCb = cb;
3869 }
3870
3871 @Override
3872 public String toString() {
3873 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3874 }
3875 }
3876
3877 /**
3878 * The call back object passed in Params. onComplete will be called
3879 * on the main thread.
3880 */
3881 abstract static class CallBack {
3882 // Called on the main thread.
3883 abstract void onComplete(Integer result);
3884 }
3885
3886 public CheckMp(Context context, ConnectivityService cs) {
3887 mContext = context;
3888 mCs = cs;
3889
3890 // Setup access to TelephonyService we'll be using.
3891 mTm = (TelephonyManager) mContext.getSystemService(
3892 Context.TELEPHONY_SERVICE);
3893 }
3894
3895 /**
3896 * Get the default url to use for the test.
3897 */
3898 public String getDefaultUrl() {
3899 // See http://go/clientsdns for usage approval
3900 String server = Settings.Global.getString(mContext.getContentResolver(),
3901 Settings.Global.CAPTIVE_PORTAL_SERVER);
3902 if (server == null) {
3903 server = "clients3.google.com";
3904 }
3905 return "http://" + server + "/generate_204";
3906 }
3907
3908 /**
3909 * Detect if its possible to connect to the http url. DNS based detection techniques
3910 * do not work at all hotspots. The best way to check is to perform a request to
3911 * a known address that fetches the data we expect.
3912 */
3913 private synchronized Integer isMobileOk(Params params) {
3914 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3915 Uri orgUri = Uri.parse(params.mUrl);
3916 Random rand = new Random();
3917 mParams = params;
3918
3919 try {
3920 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3921 log("isMobileOk: not mobile capable");
3922 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3923 return result;
3924 }
3925
3926 // Enable fail fast as we'll do retries here and use a
3927 // hipri connection so the default connection stays active.
3928 log("isMobileOk: start hipri url=" + params.mUrl);
3929 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
Wink Savilleab9321d2013-06-29 21:10:57 -07003930
3931 // Continue trying to connect until time has run out
3932 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville7f6ee2e2013-08-07 11:02:57 -07003933
3934 // First wait until we can start using hipri
3935 Binder binder = new Binder();
3936 while(SystemClock.elapsedRealtime() < endTime) {
3937 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3938 Phone.FEATURE_ENABLE_HIPRI, binder);
3939 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3940 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3941 log("isMobileOk: hipri started");
3942 break;
3943 }
3944 if (VDBG) log("isMobileOk: hipri not started yet");
3945 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3946 sleep(1);
3947 }
3948
3949 // Continue trying to connect until time has run out
Wink Savilleab9321d2013-06-29 21:10:57 -07003950 while(SystemClock.elapsedRealtime() < endTime) {
3951 try {
3952 // Wait for hipri to connect.
3953 // TODO: Don't poll and handle situation where hipri fails
3954 // because default is retrying. See b/9569540
3955 NetworkInfo.State state = mCs
3956 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3957 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville1aef7fc2013-07-31 15:49:04 -07003958 if (VDBG) {
3959 log("isMobileOk: not connected ni=" +
Wink Savilleab9321d2013-06-29 21:10:57 -07003960 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville1aef7fc2013-07-31 15:49:04 -07003961 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003962 sleep(1);
3963 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3964 continue;
3965 }
3966
3967 // Get of the addresses associated with the url host. We need to use the
3968 // address otherwise HttpURLConnection object will use the name to get
3969 // the addresses and is will try every address but that will bypass the
3970 // route to host we setup and the connection could succeed as the default
3971 // interface might be connected to the internet via wifi or other interface.
3972 InetAddress[] addresses;
3973 try {
3974 addresses = InetAddress.getAllByName(orgUri.getHost());
3975 } catch (UnknownHostException e) {
3976 log("isMobileOk: UnknownHostException");
3977 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3978 return result;
3979 }
3980 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3981
3982 // Get the type of addresses supported by this link
3983 LinkProperties lp = mCs.getLinkProperties(
3984 ConnectivityManager.TYPE_MOBILE_HIPRI);
3985 boolean linkHasIpv4 = hasIPv4Address(lp);
3986 boolean linkHasIpv6 = hasIPv6Address(lp);
3987 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3988 + " linkHasIpv6=" + linkHasIpv6);
3989
3990 // Loop through at most 3 valid addresses or all of the address or until
3991 // we run out of time
3992 int loops = Math.min(3, addresses.length);
3993 for(int validAddr=0, addrTried=0;
3994 (validAddr < loops) && (addrTried < addresses.length)
3995 && (SystemClock.elapsedRealtime() < endTime);
3996 addrTried ++) {
3997
3998 // Choose the address at random but make sure its type is supported
3999 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4000 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4001 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4002 // Valid address, so use it
4003 validAddr += 1;
4004 } else {
4005 // Invalid address so try next address
4006 continue;
4007 }
4008
4009 // Make a route to host so we check the specific interface.
4010 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4011 hostAddr.getAddress())) {
4012 // Wait a short time to be sure the route is established ??
4013 log("isMobileOk:"
4014 + " wait to establish route to hostAddr=" + hostAddr);
4015 sleep(3);
4016 } else {
4017 log("isMobileOk:"
4018 + " could not establish route to hostAddr=" + hostAddr);
4019 continue;
4020 }
4021
4022 // Rewrite the url to have numeric address to use the specific route.
4023 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4024 // is used which is useless in this case.
4025 URL newUrl = new URL(orgUri.getScheme() + "://"
4026 + hostAddr.getHostAddress() + orgUri.getPath());
4027 log("isMobileOk: newUrl=" + newUrl);
4028
4029 HttpURLConnection urlConn = null;
4030 try {
4031 // Open the connection set the request header and get the response
4032 urlConn = (HttpURLConnection) newUrl.openConnection(
4033 java.net.Proxy.NO_PROXY);
4034 urlConn.setInstanceFollowRedirects(false);
4035 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4036 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4037 urlConn.setUseCaches(false);
4038 urlConn.setAllowUserInteraction(false);
4039 urlConn.setRequestProperty("Connection", "close");
4040 int responseCode = urlConn.getResponseCode();
4041 if (responseCode == 204) {
4042 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
4043 } else {
4044 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
4045 }
4046 log("isMobileOk: connected responseCode=" + responseCode);
4047 urlConn.disconnect();
4048 urlConn = null;
4049 return result;
4050 } catch (Exception e) {
4051 log("isMobileOk: HttpURLConnection Exception e=" + e);
4052 if (urlConn != null) {
4053 urlConn.disconnect();
4054 urlConn = null;
4055 }
4056 }
4057 }
4058 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
4059 log("isMobileOk: loops|timed out");
4060 return result;
4061 } catch (Exception e) {
4062 log("isMobileOk: Exception e=" + e);
4063 continue;
4064 }
4065 }
4066 log("isMobileOk: timed out");
4067 } finally {
4068 log("isMobileOk: F stop hipri");
4069 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4070 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4071 Phone.FEATURE_ENABLE_HIPRI);
4072 log("isMobileOk: X result=" + result);
4073 }
4074 return result;
4075 }
4076
4077 @Override
4078 protected Integer doInBackground(Params... params) {
4079 return isMobileOk(params[0]);
4080 }
4081
4082 @Override
4083 protected void onPostExecute(Integer result) {
4084 log("onPostExecute: result=" + result);
4085 if ((mParams != null) && (mParams.mCb != null)) {
4086 mParams.mCb.onComplete(result);
4087 }
4088 }
4089
4090 private String inetAddressesToString(InetAddress[] addresses) {
4091 StringBuffer sb = new StringBuffer();
4092 boolean firstTime = true;
4093 for(InetAddress addr : addresses) {
4094 if (firstTime) {
4095 firstTime = false;
4096 } else {
4097 sb.append(",");
4098 }
4099 sb.append(addr);
4100 }
4101 return sb.toString();
4102 }
4103
4104 private void printNetworkInfo() {
4105 boolean hasIccCard = mTm.hasIccCard();
4106 int simState = mTm.getSimState();
4107 log("hasIccCard=" + hasIccCard
4108 + " simState=" + simState);
4109 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4110 if (ni != null) {
4111 log("ni.length=" + ni.length);
4112 for (NetworkInfo netInfo: ni) {
4113 log("netInfo=" + netInfo.toString());
4114 }
4115 } else {
4116 log("no network info ni=null");
4117 }
4118 }
4119
4120 /**
4121 * Sleep for a few seconds then return.
4122 * @param seconds
4123 */
4124 private static void sleep(int seconds) {
4125 try {
4126 Thread.sleep(seconds * 1000);
4127 } catch (InterruptedException e) {
4128 e.printStackTrace();
4129 }
4130 }
4131
4132 public boolean hasIPv4Address(LinkProperties lp) {
4133 return lp.hasIPv4Address();
4134 }
4135
4136 // Not implemented in LinkProperties, do it here.
4137 public boolean hasIPv6Address(LinkProperties lp) {
4138 for (LinkAddress address : lp.getLinkAddresses()) {
4139 if (address.getAddress() instanceof Inet6Address) {
4140 return true;
4141 }
4142 }
4143 return false;
4144 }
4145
4146 private void log(String s) {
4147 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4148 }
4149 }
4150
4151 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4152
4153 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4154 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4155
4156 Resources r = Resources.getSystem();
4157 NotificationManager notificationManager = (NotificationManager) mContext
4158 .getSystemService(Context.NOTIFICATION_SERVICE);
4159
4160 if (visible) {
4161 CharSequence title;
4162 CharSequence details;
4163 int icon;
4164 switch (networkInfo.getType()) {
4165 case ConnectivityManager.TYPE_WIFI:
4166 log("setNotificationVisible: TYPE_WIFI");
4167 title = r.getString(R.string.wifi_available_sign_in, 0);
4168 details = r.getString(R.string.network_available_sign_in_detailed,
4169 networkInfo.getExtraInfo());
4170 icon = R.drawable.stat_notify_wifi_in_range;
4171 break;
4172 case ConnectivityManager.TYPE_MOBILE:
4173 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4174 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4175 title = r.getString(R.string.network_available_sign_in, 0);
4176 // TODO: Change this to pull from NetworkInfo once a printable
4177 // name has been added to it
4178 details = mTelephonyManager.getNetworkOperatorName();
4179 icon = R.drawable.stat_notify_rssi_in_range;
4180 break;
4181 default:
4182 log("setNotificationVisible: other type=" + networkInfo.getType());
4183 title = r.getString(R.string.network_available_sign_in, 0);
4184 details = r.getString(R.string.network_available_sign_in_detailed,
4185 networkInfo.getExtraInfo());
4186 icon = R.drawable.stat_notify_rssi_in_range;
4187 break;
4188 }
4189
4190 Notification notification = new Notification();
4191 notification.when = 0;
4192 notification.icon = icon;
4193 notification.flags = Notification.FLAG_AUTO_CANCEL;
4194 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4195 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4196 Intent.FLAG_ACTIVITY_NEW_TASK);
4197 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4198 notification.tickerText = title;
4199 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4200
4201 log("setNotificaitionVisible: notify notificaiton=" + notification);
4202 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4203 } else {
4204 log("setNotificaitionVisible: cancel");
4205 notificationManager.cancel(NOTIFICATION_ID, 1);
4206 }
4207 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4208 }
4209
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004210 /** Location to an updatable file listing carrier provisioning urls.
4211 * An example:
4212 *
4213 * <?xml version="1.0" encoding="utf-8"?>
4214 * <provisioningUrls>
4215 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4216 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4217 * </provisioningUrls>
4218 */
4219 private static final String PROVISIONING_URL_PATH =
4220 "/data/misc/radio/provisioning_urls.xml";
4221 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004222
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004223 /** XML tag for root element. */
4224 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4225 /** XML tag for individual url */
4226 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4227 /** XML tag for redirected url */
4228 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4229 /** XML attribute for mcc */
4230 private static final String ATTR_MCC = "mcc";
4231 /** XML attribute for mnc */
4232 private static final String ATTR_MNC = "mnc";
4233
4234 private static final int REDIRECTED_PROVISIONING = 1;
4235 private static final int PROVISIONING = 2;
4236
4237 private String getProvisioningUrlBaseFromFile(int type) {
4238 FileReader fileReader = null;
4239 XmlPullParser parser = null;
4240 Configuration config = mContext.getResources().getConfiguration();
4241 String tagType;
4242
4243 switch (type) {
4244 case PROVISIONING:
4245 tagType = TAG_PROVISIONING_URL;
4246 break;
4247 case REDIRECTED_PROVISIONING:
4248 tagType = TAG_REDIRECTED_URL;
4249 break;
4250 default:
4251 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4252 type);
4253 }
4254
4255 try {
4256 fileReader = new FileReader(mProvisioningUrlFile);
4257 parser = Xml.newPullParser();
4258 parser.setInput(fileReader);
4259 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4260
4261 while (true) {
4262 XmlUtils.nextElement(parser);
4263
4264 String element = parser.getName();
4265 if (element == null) break;
4266
4267 if (element.equals(tagType)) {
4268 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4269 try {
4270 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4271 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4272 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4273 parser.next();
4274 if (parser.getEventType() == XmlPullParser.TEXT) {
4275 return parser.getText();
4276 }
4277 }
4278 }
4279 } catch (NumberFormatException e) {
4280 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4281 }
4282 }
4283 }
4284 return null;
4285 } catch (FileNotFoundException e) {
4286 loge("Carrier Provisioning Urls file not found");
4287 } catch (XmlPullParserException e) {
4288 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4289 } catch (IOException e) {
4290 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4291 } finally {
4292 if (fileReader != null) {
4293 try {
4294 fileReader.close();
4295 } catch (IOException e) {}
4296 }
4297 }
4298 return null;
4299 }
4300
Wink Saville42d4f082013-07-20 20:31:59 -07004301 @Override
4302 public String getMobileRedirectedProvisioningUrl() {
4303 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004304 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4305 if (TextUtils.isEmpty(url)) {
4306 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4307 }
4308 return url;
4309 }
4310
Wink Saville42d4f082013-07-20 20:31:59 -07004311 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004312 public String getMobileProvisioningUrl() {
4313 enforceConnectivityInternalPermission();
4314 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4315 if (TextUtils.isEmpty(url)) {
4316 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004317 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004318 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004319 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004320 }
Wink Saville8cf35602013-07-10 23:00:07 -07004321 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004322 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004323 String phoneNumber = mTelephonyManager.getLine1Number();
4324 if (TextUtils.isEmpty(phoneNumber)) {
4325 phoneNumber = "0000000000";
4326 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004327 url = String.format(url,
4328 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4329 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004330 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004331 }
4332
Wink Savilleab9321d2013-06-29 21:10:57 -07004333 return url;
4334 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004335
4336 private void onUserStart(int userId) {
4337 synchronized(mVpns) {
4338 Vpn userVpn = mVpns.get(userId);
4339 if (userVpn != null) {
4340 loge("Starting user already has a VPN");
4341 return;
4342 }
4343 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4344 mVpns.put(userId, userVpn);
4345 userVpn.startMonitoring(mContext, mTrackerHandler);
4346 }
4347 }
4348
4349 private void onUserStop(int userId) {
4350 synchronized(mVpns) {
4351 Vpn userVpn = mVpns.get(userId);
4352 if (userVpn == null) {
4353 loge("Stopping user has no VPN");
4354 return;
4355 }
4356 mVpns.delete(userId);
4357 }
4358 }
4359
4360 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4361 @Override
4362 public void onReceive(Context context, Intent intent) {
4363 final String action = intent.getAction();
4364 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4365 if (userId == UserHandle.USER_NULL) return;
4366
4367 if (Intent.ACTION_USER_STARTING.equals(action)) {
4368 onUserStart(userId);
4369 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4370 onUserStop(userId);
4371 }
4372 }
4373 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374}