blob: a022fb1d8769babd43c055faaecad7ea8637df9c [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Wink Saville32506bc2013-06-29 21:10:57 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville9a1a7ef2013-08-29 08:55:16 -070038import android.content.ActivityNotFoundException;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090042import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080043import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalt39d56012013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070048import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070049import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080050import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080051import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080052import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080053import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070054import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070055import android.net.INetworkPolicyListener;
56import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070057import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070058import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080059import android.net.LinkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -070060import android.net.Uri;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070063import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080064import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070065import android.net.NetworkInfo.DetailedState;
Wink Saville32506bc2013-06-29 21:10:57 -070066import android.net.NetworkInfo.State;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070073import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080074import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090075import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070076import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070089import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070090import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080091import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070092import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070094import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070096import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070097import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -070098import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070099import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800100import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700101import android.util.SparseIntArray;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700102import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800103
Wink Saville32506bc2013-06-29 21:10:57 -0700104import com.android.internal.R;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700105import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700107import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700108import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700109import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700110import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700113import com.android.server.am.BatteryStatsService;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900114import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800115import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700116import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700117import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700118import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700119import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700120import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700121
tk.mun093f55c2011-10-13 22:51:57 +0900122import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700123
Robert Greenwalt39d56012013-07-16 12:06:09 -0700124import org.xmlpull.v1.XmlPullParser;
125import org.xmlpull.v1.XmlPullParserException;
126
127import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800128import java.io.FileDescriptor;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700129import java.io.FileNotFoundException;
130import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700131import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900133import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700134import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700135import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700136import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700137import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700138import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700139import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700140import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700141import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700142import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700143import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700144import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700145import java.util.List;
Wink Saville32506bc2013-06-29 21:10:57 -0700146import java.util.Random;
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700147import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville32506bc2013-06-29 21:10:57 -0700148import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149
150/**
151 * @hide
152 */
153public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700154 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700156 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700157 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700159 private static final boolean LOGD_RULES = false;
160
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700161 // TODO: create better separation between radio types and network types
162
Robert Greenwalt2034b912009-08-12 16:08:25 -0700163 // how long to wait before switching back to a radio's default network
164 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
165 // system property that can override the above value
166 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
167 "android.telephony.apn-restore";
168
Wink Saville32506bc2013-06-29 21:10:57 -0700169 // Default value if FAIL_FAST_TIME_MS is not set
170 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
171 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
172 private static final String FAIL_FAST_TIME_MS =
173 "persist.radio.fail_fast_time_ms";
174
Robert Greenwaltbd492212011-05-06 17:10:53 -0700175 // used in recursive route setting to add gateways for the host for which
176 // a host route was requested.
177 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
178
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800179 private Tethering mTethering;
180
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700181 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700182
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700183 private Vpn mVpn;
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700184 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700185
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700186 private boolean mLockdownEnabled;
187 private LockdownVpnTracker mLockdownTracker;
188
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900189 private Nat464Xlat mClat;
190
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700191 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
192 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700193 /** Currently active network rules by UID. */
194 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700195 /** Set of ifaces that are costly. */
196 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700197
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198 /**
199 * Sometimes we want to refer to the individual network state
200 * trackers separately, and sometimes we just want to treat them
201 * abstractly.
202 */
203 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700204
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700205 /* Handles captive portal check on a network */
206 private CaptivePortalTracker mCaptivePortalTracker;
207
Robert Greenwalt2034b912009-08-12 16:08:25 -0700208 /**
Wink Saville051a6642011-07-13 13:44:13 -0700209 * The link properties that define the current links
210 */
211 private LinkProperties mCurrentLinkProperties[];
212
213 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700214 * A per Net list of the PID's that requested access to the net
215 * used both as a refcount and for per-PID DNS selection
216 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200217 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700218
Robert Greenwalt2034b912009-08-12 16:08:25 -0700219 // priority order of the nettrackers
220 // (excluding dynamically set mNetworkPreference)
221 // TODO - move mNetworkTypePreference into this
222 private int[] mPriorityList;
223
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224 private Context mContext;
225 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700227 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000228 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700229 private int mDefaultInetConditionPublished = 0;
230 private boolean mInetConditionChangeInFlight = false;
231 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232
Chia-chi Yehcc844502011-07-14 18:01:57 -0700233 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800234 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700235 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800236
237 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700238 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800239
Robert Greenwalt355205c2011-05-10 15:05:02 -0700240 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700241 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700242
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700243 private static final int ENABLED = 1;
244 private static final int DISABLED = 0;
245
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700246 private static final boolean ADD = true;
247 private static final boolean REMOVE = false;
248
249 private static final boolean TO_DEFAULT_TABLE = true;
250 private static final boolean TO_SECONDARY_TABLE = false;
251
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700252 /**
253 * used internally as a delayed event to make us switch back to the
254 * default network
255 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700256 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700257
258 /**
259 * used internally to change our mobile data enabled flag
260 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700261 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700262
263 /**
264 * used internally to change our network preference setting
265 * arg1 = networkType to prefer
266 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700267 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700268
269 /**
270 * used internally to synchronize inet condition reports
271 * arg1 = networkType
272 * arg2 = condition (0 bad, 100 good)
273 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700274 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700275
276 /**
277 * used internally to mark the end of inet condition hold periods
278 * arg1 = networkType
279 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700280 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700281
282 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700283 * used internally to set enable/disable cellular data
284 * arg1 = ENBALED or DISABLED
285 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700286 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700287
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700288 /**
289 * used internally to clear a wakelock when transitioning
290 * from one net to another
291 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700292 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700293
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700294 /**
295 * used internally to reload global proxy settings
296 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700297 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700298
Robert Greenwalt34848c02011-03-25 13:09:25 -0700299 /**
300 * used internally to set external dependency met/unmet
301 * arg1 = ENABLED (met) or DISABLED (unmet)
302 * arg2 = NetworkType
303 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700304 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700305
Chia-chi Yehcc844502011-07-14 18:01:57 -0700306 /**
307 * used internally to restore DNS properties back to the
308 * default network
309 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700310 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700311
Wink Saville7e4333c2011-08-05 11:40:22 -0700312 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700313 * used internally to send a sticky broadcast delayed.
314 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700315 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700316
Jeff Sharkey805662d2011-08-19 02:24:24 -0700317 /**
318 * Used internally to
319 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
320 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700321 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700322
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700323 private static final int EVENT_VPN_STATE_CHANGED = 14;
324
Wink Saville32506bc2013-06-29 21:10:57 -0700325 /**
326 * Used internally to disable fail fast of mobile data
327 */
328 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
329
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700330 /** Handler used for internal events. */
331 private InternalHandler mHandler;
332 /** Handler used for incoming {@link NetworkStateTracker} events. */
333 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700334
335 // list of DeathRecipients used to make sure features are turned off when
336 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500337 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700338
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400339 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800340 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400341
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700342 private PowerManager.WakeLock mNetTransitionWakeLock;
343 private String mNetTransitionWakeLockCausedBy = "";
344 private int mNetTransitionWakeLockSerialNumber;
345 private int mNetTransitionWakeLockTimeout;
346
Robert Greenwalt94daa182010-09-01 11:34:05 -0700347 private InetAddress mDefaultDns;
348
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700349 // this collection is used to refcount the added routes - if there are none left
350 // it's time to remove the route from the route table
351 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
352
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700353 // used in DBG mode to track inet condition reports
354 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
355 private ArrayList mInetLog;
356
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700357 // track the current default http proxy - tell the world if we get a new one (real change)
358 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700359 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700360 private boolean mDefaultProxyDisabled = false;
361
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700362 // track the global proxy.
363 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700364
365 private SettingsObserver mSettingsObserver;
366
Robert Greenwalt34848c02011-03-25 13:09:25 -0700367 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700368 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700369
Robert Greenwalt12c44552009-12-07 11:33:18 -0800370 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700371 public int mSimultaneity;
372 public int mType;
373 public RadioAttributes(String init) {
374 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700375 mType = Integer.parseInt(fragments[0]);
376 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700377 }
378 }
379 RadioAttributes[] mRadioAttributes;
380
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700381 // the set of network types that can only be enabled by system/sig apps
382 List mProtectedNetworks;
383
Wink Saville32506bc2013-06-29 21:10:57 -0700384 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
385
386 TelephonyManager mTelephonyManager;
387
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700388 public ConnectivityService(Context context, INetworkManagementService netd,
389 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700390 // Currently, omitting a NetworkFactory will create one internally
391 // TODO: create here when we have cleaner WiMAX support
392 this(context, netd, statsService, policyManager, null);
393 }
394
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700395 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700396 INetworkStatsService statsService, INetworkPolicyManager policyManager,
397 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800398 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800399
Wink Saville775aad62010-09-02 19:23:52 -0700400 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
401 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700402 mHandler = new InternalHandler(handlerThread.getLooper());
403 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700404
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700405 if (netFactory == null) {
406 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
407 }
408
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800409 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800410 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
411 String id = Settings.Secure.getString(context.getContentResolver(),
412 Settings.Secure.ANDROID_ID);
413 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700414 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800415 SystemProperties.set("net.hostname", name);
416 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800417 }
418
Robert Greenwalt94daa182010-09-01 11:34:05 -0700419 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700420 String dns = Settings.Global.getString(context.getContentResolver(),
421 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700422 if (dns == null || dns.length() == 0) {
423 dns = context.getResources().getString(
424 com.android.internal.R.string.config_default_dns_server);
425 }
426 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800427 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
428 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800429 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700430 }
431
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700432 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700433 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700434 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700435 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700436 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700437
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700438 try {
439 mPolicyManager.registerListener(mPolicyListener);
440 } catch (RemoteException e) {
441 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700442 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700443 }
444
445 final PowerManager powerManager = (PowerManager) context.getSystemService(
446 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700447 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
448 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
449 com.android.internal.R.integer.config_networkTransitionTimeout);
450
Robert Greenwalt2034b912009-08-12 16:08:25 -0700451 mNetTrackers = new NetworkStateTracker[
452 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700453 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700454
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700455 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700456 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700457
Robert Greenwalt2034b912009-08-12 16:08:25 -0700458 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700459 String[] raStrings = context.getResources().getStringArray(
460 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700461 for (String raString : raStrings) {
462 RadioAttributes r = new RadioAttributes(raString);
463 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800464 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700465 continue;
466 }
467 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800468 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700469 r.mType);
470 continue;
471 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700472 mRadioAttributes[r.mType] = r;
473 }
474
Wink Saville00fe5092013-04-23 14:26:51 -0700475 // TODO: What is the "correct" way to do determine if this is a wifi only device?
476 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
477 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700478 String[] naStrings = context.getResources().getStringArray(
479 com.android.internal.R.array.networkAttributes);
480 for (String naString : naStrings) {
481 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700482 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700483 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800484 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700485 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700486 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700487 }
Wink Saville00fe5092013-04-23 14:26:51 -0700488 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
489 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
490 n.type);
491 continue;
492 }
Wink Savillef2a62832011-04-07 14:23:45 -0700493 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800494 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700495 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700496 continue;
497 }
Wink Savillef2a62832011-04-07 14:23:45 -0700498 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800499 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700500 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700501 continue;
502 }
Wink Savillef2a62832011-04-07 14:23:45 -0700503 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700504 mNetworksDefined++;
505 } catch(Exception e) {
506 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700507 }
508 }
509
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700510 mProtectedNetworks = new ArrayList<Integer>();
511 int[] protectedNetworks = context.getResources().getIntArray(
512 com.android.internal.R.array.config_protectedNetworks);
513 for (int p : protectedNetworks) {
514 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
515 mProtectedNetworks.add(p);
516 } else {
517 if (DBG) loge("Ignoring protectedNetwork " + p);
518 }
519 }
520
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700521 // high priority first
522 mPriorityList = new int[mNetworksDefined];
523 {
524 int insertionPoint = mNetworksDefined-1;
525 int currentLowest = 0;
526 int nextLowest = 0;
527 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700528 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700529 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700530 if (na.priority < currentLowest) continue;
531 if (na.priority > currentLowest) {
532 if (na.priority < nextLowest || nextLowest == 0) {
533 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700534 }
535 continue;
536 }
Wink Savillef2a62832011-04-07 14:23:45 -0700537 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700538 }
539 currentLowest = nextLowest;
540 nextLowest = 0;
541 }
542 }
543
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800544 // Update mNetworkPreference according to user mannually first then overlay config.xml
545 mNetworkPreference = getPersistedNetworkPreference();
546 if (mNetworkPreference == -1) {
547 for (int n : mPriorityList) {
548 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
549 mNetworkPreference = n;
550 break;
551 }
552 }
553 if (mNetworkPreference == -1) {
554 throw new IllegalStateException(
555 "You should set at least one default Network in config.xml!");
556 }
557 }
558
Mattias Falkd697aa22011-08-23 14:15:13 +0200559 mNetRequestersPids =
560 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700561 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200562 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700563 }
564
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500565 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700566
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700567 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
568 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700569
570 // Create and start trackers for hard-coded networks
571 for (int targetNetworkType : mPriorityList) {
572 final NetworkConfig config = mNetConfigs[targetNetworkType];
573 final NetworkStateTracker tracker;
574 try {
575 tracker = netFactory.createTracker(targetNetworkType, config);
576 mNetTrackers[targetNetworkType] = tracker;
577 } catch (IllegalArgumentException e) {
578 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
579 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700580 continue;
581 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700582
583 tracker.startMonitoring(context, mTrackerHandler);
584 if (config.isDefault()) {
585 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800586 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700587 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800588
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700589 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800590
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -0700591 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700592 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700593
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900594 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
595
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700596 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700597 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700598 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900599 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700600 } catch (RemoteException e) {
601 loge("Error registering observer :" + e);
602 }
603
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700604 if (DBG) {
605 mInetLog = new ArrayList();
606 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700607
608 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
609 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800610
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700611 IntentFilter filter = new IntentFilter();
612 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
613 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800614 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700615
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700616 /**
617 * Factory that creates {@link NetworkStateTracker} instances using given
618 * {@link NetworkConfig}.
619 */
620 public interface NetworkFactory {
621 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
622 }
623
624 private static class DefaultNetworkFactory implements NetworkFactory {
625 private final Context mContext;
626 private final Handler mTrackerHandler;
627
628 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
629 mContext = context;
630 mTrackerHandler = trackerHandler;
631 }
632
633 @Override
634 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
635 switch (config.radio) {
636 case TYPE_WIFI:
637 return new WifiStateTracker(targetNetworkType, config.name);
638 case TYPE_MOBILE:
639 return new MobileDataStateTracker(targetNetworkType, config.name);
640 case TYPE_DUMMY:
641 return new DummyDataStateTracker(targetNetworkType, config.name);
642 case TYPE_BLUETOOTH:
643 return BluetoothTetheringDataTracker.getInstance();
644 case TYPE_WIMAX:
645 return makeWimaxStateTracker(mContext, mTrackerHandler);
646 case TYPE_ETHERNET:
647 return EthernetDataTracker.getInstance();
648 default:
649 throw new IllegalArgumentException(
650 "Trying to create a NetworkStateTracker for an unknown radio type: "
651 + config.radio);
652 }
653 }
654 }
655
656 /**
657 * Loads external WiMAX library and registers as system service, returning a
658 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
659 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
660 */
661 private static NetworkStateTracker makeWimaxStateTracker(
662 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700663 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900664 DexClassLoader wimaxClassLoader;
665 Class wimaxStateTrackerClass = null;
666 Class wimaxServiceClass = null;
667 Class wimaxManagerClass;
668 String wimaxJarLocation;
669 String wimaxLibLocation;
670 String wimaxManagerClassName;
671 String wimaxServiceClassName;
672 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800673
tk.mun093f55c2011-10-13 22:51:57 +0900674 NetworkStateTracker wimaxStateTracker = null;
675
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700676 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900677 com.android.internal.R.bool.config_wimaxEnabled);
678
679 if (isWimaxEnabled) {
680 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700681 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900682 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700683 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900684 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700685 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900686 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700687 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900688 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700689 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900690 com.android.internal.R.string.config_wimaxStateTrackerClassname);
691
Dianne Hackborndc456a62012-11-08 11:12:09 -0800692 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900693 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700694 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900695 wimaxLibLocation, ClassLoader.getSystemClassLoader());
696
697 try {
698 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
699 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
700 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
701 } catch (ClassNotFoundException ex) {
702 loge("Exception finding Wimax classes: " + ex.toString());
703 return null;
704 }
705 } catch(Resources.NotFoundException ex) {
706 loge("Wimax Resources does not exist!!! ");
707 return null;
708 }
709
710 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800711 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900712
713 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
714 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700715 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
716 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900717
718 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
719 (new Class[] {Context.class, wimaxStateTrackerClass});
720 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700721 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900722 wmxSrvConst.setAccessible(false);
723
724 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
725
726 } catch(Exception ex) {
727 loge("Exception creating Wimax classes: " + ex.toString());
728 return null;
729 }
730 } else {
731 loge("Wimax is not enabled or not added to the network attributes!!! ");
732 return null;
733 }
734
735 return wimaxStateTracker;
736 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700737
The Android Open Source Project28527d22009-03-03 19:31:44 -0800738 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700739 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800740 * @param preference the new preference
741 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700742 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800743 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700744
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700745 mHandler.sendMessage(
746 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800747 }
748
749 public int getNetworkPreference() {
750 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700751 int preference;
752 synchronized(this) {
753 preference = mNetworkPreference;
754 }
755 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800756 }
757
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700758 private void handleSetNetworkPreference(int preference) {
759 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700760 mNetConfigs[preference] != null &&
761 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700762 if (mNetworkPreference != preference) {
763 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700764 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700765 synchronized(this) {
766 mNetworkPreference = preference;
767 }
768 enforcePreference();
769 }
770 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800771 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700772
Wink Saville4f0de1e2011-08-04 15:01:58 -0700773 private int getConnectivityChangeDelay() {
774 final ContentResolver cr = mContext.getContentResolver();
775
776 /** Check system properties for the default value then use secure settings value, if any. */
777 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700778 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
779 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
780 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700781 defaultDelay);
782 }
783
The Android Open Source Project28527d22009-03-03 19:31:44 -0800784 private int getPersistedNetworkPreference() {
785 final ContentResolver cr = mContext.getContentResolver();
786
Jeff Brownc67cf562012-09-25 15:03:20 -0700787 final int networkPrefSetting = Settings.Global
788 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800790 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800791 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700792
The Android Open Source Project28527d22009-03-03 19:31:44 -0800793 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700794 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800795 * In this method, we only tear down a non-preferred network. Establishing
796 * a connection to the preferred network is taken care of when we handle
797 * the disconnect event from the non-preferred network
798 * (see {@link #handleDisconnect(NetworkInfo)}).
799 */
800 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700801 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800802 return;
803
Robert Greenwalt2034b912009-08-12 16:08:25 -0700804 if (!mNetTrackers[mNetworkPreference].isAvailable())
805 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800806
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700808 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700809 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700810 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800811 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700812 " in enforcePreference");
813 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800815 }
816 }
817 }
818
819 private boolean teardown(NetworkStateTracker netTracker) {
820 if (netTracker.teardown()) {
821 netTracker.setTeardownRequested(true);
822 return true;
823 } else {
824 return false;
825 }
826 }
827
828 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700829 * Check if UID should be blocked from using the network represented by the
830 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700831 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700832 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
833 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700834
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700835 final boolean networkCostly;
836 final int uidRules;
837 synchronized (mRulesLock) {
838 networkCostly = mMeteredIfaces.contains(iface);
839 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700840 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700841
842 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
843 return true;
844 }
845
846 // no restrictive rules; network is visible
847 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700848 }
849
850 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700851 * Return a filtered {@link NetworkInfo}, potentially marked
852 * {@link DetailedState#BLOCKED} based on
853 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700854 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700855 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
856 NetworkInfo info = tracker.getNetworkInfo();
857 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700858 // network is blocked; clone and override state
859 info = new NetworkInfo(info);
860 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700861 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700862 if (mLockdownTracker != null) {
863 info = mLockdownTracker.augmentNetworkInfo(info);
864 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700865 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700866 }
867
868 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 * Return NetworkInfo for the active (i.e., connected) network interface.
870 * It is assumed that at most one network is active at a time. If more
871 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700872 * @return the info for the active network, or {@code null} if none is
873 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800874 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700875 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800876 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700877 enforceAccessPermission();
878 final int uid = Binder.getCallingUid();
879 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800880 }
881
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700882 /**
883 * Find the first Provisioning network.
884 *
885 * @return NetworkInfo or null if none.
886 */
887 private NetworkInfo getProvisioningNetworkInfo() {
888 enforceAccessPermission();
889
890 // Find the first Provisioning Network
891 NetworkInfo provNi = null;
892 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Savilleb1a32022013-09-05 12:02:25 -0700893 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700894 provNi = ni;
895 break;
896 }
897 }
898 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
899 return provNi;
900 }
901
902 /**
903 * Find the first Provisioning network or the ActiveDefaultNetwork
904 * if there is no Provisioning network
905 *
906 * @return NetworkInfo or null if none.
907 */
908 @Override
909 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
910 enforceAccessPermission();
911
912 NetworkInfo provNi = getProvisioningNetworkInfo();
913 if (provNi == null) {
914 final int uid = Binder.getCallingUid();
915 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
916 }
917 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
918 return provNi;
919 }
920
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700921 public NetworkInfo getActiveNetworkInfoUnfiltered() {
922 enforceAccessPermission();
923 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
924 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
925 if (tracker != null) {
926 return tracker.getNetworkInfo();
927 }
928 }
929 return null;
930 }
931
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700932 @Override
933 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
934 enforceConnectivityInternalPermission();
935 return getNetworkInfo(mActiveDefaultNetwork, uid);
936 }
937
938 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800939 public NetworkInfo getNetworkInfo(int networkType) {
940 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700941 final int uid = Binder.getCallingUid();
942 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800943 }
944
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700945 private NetworkInfo getNetworkInfo(int networkType, int uid) {
946 NetworkInfo info = null;
947 if (isNetworkTypeValid(networkType)) {
948 final NetworkStateTracker tracker = mNetTrackers[networkType];
949 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700950 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700951 }
952 }
953 return info;
954 }
955
956 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800957 public NetworkInfo[] getAllNetworkInfo() {
958 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700959 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700960 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700961 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700962 for (NetworkStateTracker tracker : mNetTrackers) {
963 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700964 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700965 }
966 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800967 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700968 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800969 }
970
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700971 @Override
972 public boolean isNetworkSupported(int networkType) {
973 enforceAccessPermission();
974 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
975 }
976
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700977 /**
978 * Return LinkProperties for the active (i.e., connected) default
979 * network interface. It is assumed that at most one default network
980 * is active at a time. If more than one is active, it is indeterminate
981 * which will be returned.
982 * @return the ip properties for the active network, or {@code null} if
983 * none is active
984 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700985 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700986 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700987 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700988 }
989
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700990 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700991 public LinkProperties getLinkProperties(int networkType) {
992 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700993 if (isNetworkTypeValid(networkType)) {
994 final NetworkStateTracker tracker = mNetTrackers[networkType];
995 if (tracker != null) {
996 return tracker.getLinkProperties();
997 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700998 }
999 return null;
1000 }
1001
Jeff Sharkey21062e72011-05-28 20:56:34 -07001002 @Override
1003 public NetworkState[] getAllNetworkState() {
1004 enforceAccessPermission();
1005 final int uid = Binder.getCallingUid();
1006 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001007 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001008 for (NetworkStateTracker tracker : mNetTrackers) {
1009 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001010 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001011 result.add(new NetworkState(
1012 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1013 }
1014 }
1015 }
1016 return result.toArray(new NetworkState[result.size()]);
1017 }
1018
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001019 private NetworkState getNetworkStateUnchecked(int networkType) {
1020 if (isNetworkTypeValid(networkType)) {
1021 final NetworkStateTracker tracker = mNetTrackers[networkType];
1022 if (tracker != null) {
1023 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1024 tracker.getLinkCapabilities());
1025 }
1026 }
1027 return null;
1028 }
1029
1030 @Override
1031 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1032 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001033
1034 final long token = Binder.clearCallingIdentity();
1035 try {
1036 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1037 if (state != null) {
1038 try {
1039 return mPolicyManager.getNetworkQuotaInfo(state);
1040 } catch (RemoteException e) {
1041 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001042 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001043 return null;
1044 } finally {
1045 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001046 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001047 }
1048
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001049 @Override
1050 public boolean isActiveNetworkMetered() {
1051 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001052 final long token = Binder.clearCallingIdentity();
1053 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001054 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001055 } finally {
1056 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001057 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001058 }
1059
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001060 private boolean isNetworkMeteredUnchecked(int networkType) {
1061 final NetworkState state = getNetworkStateUnchecked(networkType);
1062 if (state != null) {
1063 try {
1064 return mPolicyManager.isNetworkMetered(state);
1065 } catch (RemoteException e) {
1066 }
1067 }
1068 return false;
1069 }
1070
The Android Open Source Project28527d22009-03-03 19:31:44 -08001071 public boolean setRadios(boolean turnOn) {
1072 boolean result = true;
1073 enforceChangePermission();
1074 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001075 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001076 }
1077 return result;
1078 }
1079
1080 public boolean setRadio(int netType, boolean turnOn) {
1081 enforceChangePermission();
1082 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1083 return false;
1084 }
1085 NetworkStateTracker tracker = mNetTrackers[netType];
1086 return tracker != null && tracker.setRadio(turnOn);
1087 }
1088
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001089 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1090 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001091 public void interfaceClassDataActivityChanged(String label, boolean active) {
1092 int deviceType = Integer.parseInt(label);
1093 sendDataActivityBroadcast(deviceType, active);
1094 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001095 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001096
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001097 /**
1098 * Used to notice when the calling process dies so we can self-expire
1099 *
1100 * Also used to know if the process has cleaned up after itself when
1101 * our auto-expire timer goes off. The timer has a link to an object.
1102 *
1103 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001104 private class FeatureUser implements IBinder.DeathRecipient {
1105 int mNetworkType;
1106 String mFeature;
1107 IBinder mBinder;
1108 int mPid;
1109 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001110 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001111
1112 FeatureUser(int type, String feature, IBinder binder) {
1113 super();
1114 mNetworkType = type;
1115 mFeature = feature;
1116 mBinder = binder;
1117 mPid = getCallingPid();
1118 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001119 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001120
Robert Greenwalt2034b912009-08-12 16:08:25 -07001121 try {
1122 mBinder.linkToDeath(this, 0);
1123 } catch (RemoteException e) {
1124 binderDied();
1125 }
1126 }
1127
1128 void unlinkDeathRecipient() {
1129 mBinder.unlinkToDeath(this, 0);
1130 }
1131
1132 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001133 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001134 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1135 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001136 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001137 }
1138
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001139 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001140 if (VDBG) {
1141 log("ConnectivityService FeatureUser expire(" +
1142 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1143 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1144 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001145 stopUsingNetworkFeature(this, false);
1146 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001147
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001148 public boolean isSameUser(FeatureUser u) {
1149 if (u == null) return false;
1150
1151 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1152 }
1153
1154 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1155 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1156 TextUtils.equals(mFeature, feature)) {
1157 return true;
1158 }
1159 return false;
1160 }
1161
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001162 public String toString() {
1163 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1164 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1165 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001166 }
1167
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001168 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001169 public int startUsingNetworkFeature(int networkType, String feature,
1170 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001171 long startTime = 0;
1172 if (DBG) {
1173 startTime = SystemClock.elapsedRealtime();
1174 }
Wink Savillea7d56572011-09-21 11:05:43 -07001175 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001176 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1177 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001178 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001179 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001180 try {
1181 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1182 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001183 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001184 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001185
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001186 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001187
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001188 // TODO - move this into individual networktrackers
1189 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001190
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001191 if (mLockdownEnabled) {
1192 // Since carrier APNs usually aren't available from VPN
1193 // endpoint, mark them as unavailable.
1194 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1195 }
1196
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001197 if (mProtectedNetworks.contains(usedNetworkType)) {
1198 enforceConnectivityInternalPermission();
1199 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001200
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001201 // if UID is restricted, don't allow them to bring up metered APNs
1202 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1203 final int uidRules;
1204 synchronized (mRulesLock) {
1205 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1206 }
1207 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001208 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001209 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001210
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001211 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1212 if (network != null) {
1213 Integer currentPid = new Integer(getCallingPid());
1214 if (usedNetworkType != networkType) {
1215 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001216
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001217 if (ni.isAvailable() == false) {
1218 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1219 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001220 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001221 } else {
1222 // else make the attempt anyway - probably giving REQUEST_STARTED below
1223 if (DBG) {
1224 log("special network not available, but try anyway ni=" +
1225 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001226 }
1227 }
1228 }
1229
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001230 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001231
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001232 synchronized(this) {
1233 boolean addToList = true;
1234 if (restoreTimer < 0) {
1235 // In case there is no timer is specified for the feature,
1236 // make sure we don't add duplicate entry with the same request.
1237 for (FeatureUser u : mFeatureUsers) {
1238 if (u.isSameUser(f)) {
1239 // Duplicate user is found. Do not add.
1240 addToList = false;
1241 break;
1242 }
1243 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001244 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001245
1246 if (addToList) mFeatureUsers.add(f);
1247 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1248 // this gets used for per-pid dns when connected
1249 mNetRequestersPids[usedNetworkType].add(currentPid);
1250 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001251 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001252
1253 if (restoreTimer >= 0) {
1254 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1255 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1256 }
1257
1258 if ((ni.isConnectedOrConnecting() == true) &&
1259 !network.isTeardownRequested()) {
1260 if (ni.isConnected() == true) {
1261 final long token = Binder.clearCallingIdentity();
1262 try {
1263 // add the pid-specific dns
1264 handleDnsConfigurationChange(usedNetworkType);
1265 if (VDBG) log("special network already active");
1266 } finally {
1267 Binder.restoreCallingIdentity(token);
1268 }
Wink Saville64e3f782012-07-10 12:37:54 -07001269 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001270 }
1271 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001272 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001273 }
1274
1275 // check if the radio in play can make another contact
1276 // assume if cannot for now
1277
1278 if (DBG) {
1279 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1280 feature);
1281 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001282 if (network.reconnect()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001283 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001284 return PhoneConstants.APN_REQUEST_STARTED;
1285 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001286 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001287 return PhoneConstants.APN_REQUEST_FAILED;
1288 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001289 } else {
1290 // need to remember this unsupported request so we respond appropriately on stop
1291 synchronized(this) {
1292 mFeatureUsers.add(f);
1293 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1294 // this gets used for per-pid dns when connected
1295 mNetRequestersPids[usedNetworkType].add(currentPid);
1296 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001297 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001298 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001299 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001300 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001301 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001302 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001303 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001304 } finally {
1305 if (DBG) {
1306 final long execTime = SystemClock.elapsedRealtime() - startTime;
1307 if (execTime > 250) {
1308 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1309 } else {
1310 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1311 }
1312 }
1313 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001314 }
1315
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001316 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001317 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001318 enforceChangePermission();
1319
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001320 int pid = getCallingPid();
1321 int uid = getCallingUid();
1322
1323 FeatureUser u = null;
1324 boolean found = false;
1325
1326 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001327 for (FeatureUser x : mFeatureUsers) {
1328 if (x.isSameUser(pid, uid, networkType, feature)) {
1329 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001330 found = true;
1331 break;
1332 }
1333 }
1334 }
1335 if (found && u != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001336 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001337 // stop regardless of how many other time this proc had called start
1338 return stopUsingNetworkFeature(u, true);
1339 } else {
1340 // none found!
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001341 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001342 return 1;
1343 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001344 }
1345
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001346 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1347 int networkType = u.mNetworkType;
1348 String feature = u.mFeature;
1349 int pid = u.mPid;
1350 int uid = u.mUid;
1351
1352 NetworkStateTracker tracker = null;
1353 boolean callTeardown = false; // used to carry our decision outside of sync block
1354
Wink Savillea7d56572011-09-21 11:05:43 -07001355 if (VDBG) {
1356 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001357 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001358
The Android Open Source Project28527d22009-03-03 19:31:44 -08001359 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001360 if (DBG) {
1361 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1362 ", net is invalid");
1363 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001364 return -1;
1365 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001366
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001367 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1368 // sync block
1369 synchronized(this) {
1370 // check if this process still has an outstanding start request
1371 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001372 if (VDBG) {
1373 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1374 ", ignoring");
1375 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001376 return 1;
1377 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001378 u.unlinkDeathRecipient();
1379 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1380 // If we care about duplicate requests, check for that here.
1381 //
1382 // This is done to support the extension of a request - the app
1383 // can request we start the network feature again and renew the
1384 // auto-shutoff delay. Normal "stop" calls from the app though
1385 // do not pay attention to duplicate requests - in effect the
1386 // API does not refcount and a single stop will counter multiple starts.
1387 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001388 for (FeatureUser x : mFeatureUsers) {
1389 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001390 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001391 return 1;
1392 }
1393 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001394 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395
repo syncf5de5572011-07-29 23:55:49 -07001396 // TODO - move to individual network trackers
1397 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1398
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001399 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001400 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001401 if (DBG) {
1402 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1403 " no known tracker for used net type " + usedNetworkType);
1404 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001405 return -1;
1406 }
1407 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001408 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001409 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001410
1411 final long token = Binder.clearCallingIdentity();
1412 try {
1413 reassessPidDns(pid, true);
1414 } finally {
1415 Binder.restoreCallingIdentity(token);
1416 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001417 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001418 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001419 if (VDBG) {
1420 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1421 " others still using it");
1422 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001423 return 1;
1424 }
1425 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001426 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001427 if (DBG) {
1428 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1429 " not a known feature - dropping");
1430 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001431 }
1432 }
Wink Savillea7d56572011-09-21 11:05:43 -07001433
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001434 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001435 if (DBG) {
1436 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1437 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001438 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001439 return 1;
1440 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001441 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001442 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001443 }
1444
1445 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001446 * @deprecated use requestRouteToHostAddress instead
1447 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001448 * Ensure that a network route exists to deliver traffic to the specified
1449 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001450 * @param networkType the type of the network over which traffic to the
1451 * specified host is to be routed
1452 * @param hostAddress the IP address of the host to which the route is
1453 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001454 * @return {@code true} on success, {@code false} on failure
1455 */
1456 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001457 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1458
1459 if (inetAddress == null) {
1460 return false;
1461 }
1462
1463 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1464 }
1465
1466 /**
1467 * Ensure that a network route exists to deliver traffic to the specified
1468 * host via the specified network interface.
1469 * @param networkType the type of the network over which traffic to the
1470 * specified host is to be routed
1471 * @param hostAddress the IP address of the host to which the route is
1472 * desired
1473 * @return {@code true} on success, {@code false} on failure
1474 */
1475 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001476 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001477 if (mProtectedNetworks.contains(networkType)) {
1478 enforceConnectivityInternalPermission();
1479 }
1480
The Android Open Source Project28527d22009-03-03 19:31:44 -08001481 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001482 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001483 return false;
1484 }
1485 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001486 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001487
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001488 if (tracker == null || (netState != DetailedState.CONNECTED &&
1489 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001490 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001491 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001492 log("requestRouteToHostAddress on down network "
1493 + "(" + networkType + ") - dropped"
1494 + " tracker=" + tracker
1495 + " netState=" + netState
1496 + " isTeardownRequested="
1497 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001498 }
1499 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001500 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001501 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001502 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001503 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001504 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001505 boolean ok = addRouteToAddress(lp, addr);
1506 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1507 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001508 } catch (UnknownHostException e) {
1509 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1510 } finally {
1511 Binder.restoreCallingIdentity(token);
1512 }
Wink Saville32506bc2013-06-29 21:10:57 -07001513 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001514 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001515 }
1516
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001517 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001518 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001519 }
1520
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001521 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001522 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001523 }
1524
Robert Greenwalt98107422011-07-22 11:55:33 -07001525 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001526 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001527 }
1528
1529 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001530 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001531 }
1532
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001533 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1534 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001535 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001536 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001537 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001538 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001539 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001540 if (bestRoute.getGateway().equals(addr)) {
1541 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001542 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001543 } else {
1544 // if we will connect to this through another route, add a direct route
1545 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001546 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001547 }
1548 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001549 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001550 }
1551
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001552 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1553 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001554 if ((lp == null) || (r == null)) {
1555 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001556 return false;
1557 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001558
1559 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001560 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001561 return false;
1562 }
1563
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001564 String ifaceName = r.getInterface();
1565 if(ifaceName == null) {
1566 loge("Error modifying route - no interface name");
1567 return false;
1568 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001569 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001570 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001571 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001572 if (bestRoute.getGateway().equals(r.getGateway())) {
1573 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001574 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001575 } else {
1576 // if we will connect to our gateway through another route, add a direct
1577 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001578 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1579 bestRoute.getGateway(),
1580 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001581 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001582 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001583 }
1584 }
1585 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001586 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001587 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001588 if (toDefaultTable) {
1589 mAddedRoutes.add(r); // only track default table - only one apps can effect
1590 mNetd.addRoute(ifaceName, r);
1591 } else {
1592 mNetd.addSecondaryRoute(ifaceName, r);
1593 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001594 } catch (Exception e) {
1595 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001596 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001597 return false;
1598 }
1599 } else {
1600 // if we remove this one and there are no more like it, then refcount==0 and
1601 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001602 if (toDefaultTable) {
1603 mAddedRoutes.remove(r);
1604 if (mAddedRoutes.contains(r) == false) {
1605 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1606 try {
1607 mNetd.removeRoute(ifaceName, r);
1608 } catch (Exception e) {
1609 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001610 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001611 return false;
1612 }
1613 } else {
1614 if (VDBG) log("not removing " + r + " as it's still in use");
1615 }
1616 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001617 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001618 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001619 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001620 } catch (Exception e) {
1621 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001622 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001623 return false;
1624 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001625 }
1626 }
1627 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001628 }
1629
1630 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001631 * @see ConnectivityManager#getMobileDataEnabled()
1632 */
1633 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001634 // TODO: This detail should probably be in DataConnectionTracker's
1635 // which is where we store the value and maybe make this
1636 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001637 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001638 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1639 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001640 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001641 return retVal;
1642 }
1643
Robert Greenwalt34848c02011-03-25 13:09:25 -07001644 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001645 enforceConnectivityInternalPermission();
1646
Robert Greenwalt34848c02011-03-25 13:09:25 -07001647 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1648 (met ? ENABLED : DISABLED), networkType));
1649 }
1650
1651 private void handleSetDependencyMet(int networkType, boolean met) {
1652 if (mNetTrackers[networkType] != null) {
1653 if (DBG) {
1654 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1655 }
1656 mNetTrackers[networkType].setDependencyMet(met);
1657 }
1658 }
1659
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001660 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1661 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001662 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001663 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001664 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001665 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001666 }
1667
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001668 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001669 // skip update when we've already applied rules
1670 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1671 if (oldRules == uidRules) return;
1672
1673 mUidRules.put(uid, uidRules);
1674 }
1675
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001676 // TODO: notify UID when it has requested targeted updates
1677 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001678
1679 @Override
1680 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001681 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001682 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001683 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001684 }
1685
1686 synchronized (mRulesLock) {
1687 mMeteredIfaces.clear();
1688 for (String iface : meteredIfaces) {
1689 mMeteredIfaces.add(iface);
1690 }
1691 }
1692 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001693
1694 @Override
1695 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1696 // caller is NPMS, since we only register with them
1697 if (LOGD_RULES) {
1698 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1699 }
1700
1701 // kick off connectivity change broadcast for active network, since
1702 // global background policy change is radical.
1703 final int networkType = mActiveDefaultNetwork;
1704 if (isNetworkTypeValid(networkType)) {
1705 final NetworkStateTracker tracker = mNetTrackers[networkType];
1706 if (tracker != null) {
1707 final NetworkInfo info = tracker.getNetworkInfo();
1708 if (info != null && info.isConnected()) {
1709 sendConnectedBroadcast(info);
1710 }
1711 }
1712 }
1713 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001714 };
1715
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001716 /**
1717 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1718 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001719 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001720 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001721 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001722
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001724 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001725 }
1726
1727 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001728 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001729 if (VDBG) {
1730 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001731 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001732 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1733 }
tk.mun5eee1042012-01-06 10:43:52 +09001734 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1735 if (VDBG) {
1736 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1737 }
1738 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1739 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001740 }
1741
1742 @Override
1743 public void setPolicyDataEnable(int networkType, boolean enabled) {
1744 // only someone like NPMS should only be calling us
1745 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1746
1747 mHandler.sendMessage(mHandler.obtainMessage(
1748 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1749 }
1750
1751 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1752 if (isNetworkTypeValid(networkType)) {
1753 final NetworkStateTracker tracker = mNetTrackers[networkType];
1754 if (tracker != null) {
1755 tracker.setPolicyDataEnable(enabled);
1756 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001757 }
1758 }
1759
The Android Open Source Project28527d22009-03-03 19:31:44 -08001760 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001761 mContext.enforceCallingOrSelfPermission(
1762 android.Manifest.permission.ACCESS_NETWORK_STATE,
1763 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001764 }
1765
1766 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001767 mContext.enforceCallingOrSelfPermission(
1768 android.Manifest.permission.CHANGE_NETWORK_STATE,
1769 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001770 }
1771
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001772 // TODO Make this a special check when it goes public
1773 private void enforceTetherChangePermission() {
1774 mContext.enforceCallingOrSelfPermission(
1775 android.Manifest.permission.CHANGE_NETWORK_STATE,
1776 "ConnectivityService");
1777 }
1778
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001779 private void enforceTetherAccessPermission() {
1780 mContext.enforceCallingOrSelfPermission(
1781 android.Manifest.permission.ACCESS_NETWORK_STATE,
1782 "ConnectivityService");
1783 }
1784
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001785 private void enforceConnectivityInternalPermission() {
1786 mContext.enforceCallingOrSelfPermission(
1787 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1788 "ConnectivityService");
1789 }
1790
The Android Open Source Project28527d22009-03-03 19:31:44 -08001791 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001792 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1793 * network, we ignore it. If it is for the active network, we send out a
1794 * broadcast. But first, we check whether it might be possible to connect
1795 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001796 * @param info the {@code NetworkInfo} for the network
1797 */
1798 private void handleDisconnect(NetworkInfo info) {
1799
Robert Greenwalt2034b912009-08-12 16:08:25 -07001800 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001801
Robert Greenwalt2034b912009-08-12 16:08:25 -07001802 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001803
1804 // Remove idletimer previously setup in {@code handleConnect}
1805 removeDataActivityTracking(prevNetType);
1806
The Android Open Source Project28527d22009-03-03 19:31:44 -08001807 /*
1808 * If the disconnected network is not the active one, then don't report
1809 * this as a loss of connectivity. What probably happened is that we're
1810 * getting the disconnect for a network that we explicitly disabled
1811 * in accordance with network preference policies.
1812 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001813 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001814 List<Integer> pids = mNetRequestersPids[prevNetType];
1815 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001816 // will remove them because the net's no longer connected
1817 // need to do this now as only now do we know the pids and
1818 // can properly null things that are no longer referenced.
1819 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001820 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001821 }
1822
The Android Open Source Project28527d22009-03-03 19:31:44 -08001823 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001824 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001825 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001826 if (info.isFailover()) {
1827 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1828 info.setFailover(false);
1829 }
1830 if (info.getReason() != null) {
1831 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1832 }
1833 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001834 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1835 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001836 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001837
Robert Greenwalt34848c02011-03-25 13:09:25 -07001838 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001839 tryFailover(prevNetType);
1840 if (mActiveDefaultNetwork != -1) {
1841 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001842 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1843 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001844 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001845 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1846 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001847 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001848 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001849
1850 // Reset interface if no other connections are using the same interface
1851 boolean doReset = true;
1852 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1853 if (linkProperties != null) {
1854 String oldIface = linkProperties.getInterfaceName();
1855 if (TextUtils.isEmpty(oldIface) == false) {
1856 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1857 if (networkStateTracker == null) continue;
1858 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1859 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1860 LinkProperties l = networkStateTracker.getLinkProperties();
1861 if (l == null) continue;
1862 if (oldIface.equals(l.getInterfaceName())) {
1863 doReset = false;
1864 break;
1865 }
1866 }
1867 }
1868 }
1869 }
1870
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001871 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001872 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001873
Jeff Sharkey971cd162011-08-29 16:02:57 -07001874 final Intent immediateIntent = new Intent(intent);
1875 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1876 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001877 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001878 /*
1879 * If the failover network is already connected, then immediately send
1880 * out a followup broadcast indicating successful failover
1881 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001882 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001883 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1884 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001885 }
1886 }
1887
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001888 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001889 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001890 * If this is a default network, check if other defaults are available.
1891 * Try to reconnect on all available and let them hash it out when
1892 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001893 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001894 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001895 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001896 if (DBG) {
1897 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
1898 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001899 mActiveDefaultNetwork = -1;
1900 }
1901
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001902 // don't signal a reconnect for anything lower or equal priority than our
1903 // current connected default
1904 // TODO - don't filter by priority now - nice optimization but risky
1905// int currentPriority = -1;
1906// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001907// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001908// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001909 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001910 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001911 if (mNetConfigs[checkType] == null) continue;
1912 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001913 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001914
1915// Enabling the isAvailable() optimization caused mobile to not get
1916// selected if it was in the middle of error handling. Specifically
1917// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1918// would not be available and we wouldn't get connected to anything.
1919// So removing the isAvailable() optimization below for now. TODO: This
1920// optimization should work and we need to investigate why it doesn't work.
1921// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1922// complete before it is really complete.
1923// if (!mNetTrackers[checkType].isAvailable()) continue;
1924
Robert Greenwalt34848c02011-03-25 13:09:25 -07001925// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001926
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001927 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1928 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1929 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1930 checkInfo.setFailover(true);
1931 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001932 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001933 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001934 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001935 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001936 }
1937
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001938 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001939 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001940 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1941 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001942 }
1943
Wink Saville4f0de1e2011-08-04 15:01:58 -07001944 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001945 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1946 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001947 }
1948
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001949 private void sendInetConditionBroadcast(NetworkInfo info) {
1950 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1951 }
1952
Wink Saville4f0de1e2011-08-04 15:01:58 -07001953 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001954 if (mLockdownTracker != null) {
1955 info = mLockdownTracker.augmentNetworkInfo(info);
1956 }
1957
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001958 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001959 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001960 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001961 if (info.isFailover()) {
1962 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1963 info.setFailover(false);
1964 }
1965 if (info.getReason() != null) {
1966 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1967 }
1968 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001969 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1970 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001971 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001972 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001973 return intent;
1974 }
1975
1976 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1977 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1978 }
1979
1980 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1981 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001982 }
1983
Haoyu Baib5da5752012-06-20 14:29:57 -07001984 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1985 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1986 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1987 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001988 final long ident = Binder.clearCallingIdentity();
1989 try {
1990 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1991 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1992 } finally {
1993 Binder.restoreCallingIdentity(ident);
1994 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001995 }
1996
The Android Open Source Project28527d22009-03-03 19:31:44 -08001997 /**
1998 * Called when an attempt to fail over to another network has failed.
1999 * @param info the {@link NetworkInfo} for the failed network
2000 */
2001 private void handleConnectionFailure(NetworkInfo info) {
2002 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002003
Robert Greenwalt2034b912009-08-12 16:08:25 -07002004 String reason = info.getReason();
2005 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002006
Robert Greenwalte981bc52010-10-08 16:35:52 -07002007 String reasonText;
2008 if (reason == null) {
2009 reasonText = ".";
2010 } else {
2011 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002012 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002013 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002014
2015 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002016 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002017 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002018 if (getActiveNetworkInfo() == null) {
2019 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2020 }
2021 if (reason != null) {
2022 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2023 }
2024 if (extraInfo != null) {
2025 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2026 }
2027 if (info.isFailover()) {
2028 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2029 info.setFailover(false);
2030 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002031
Robert Greenwalt34848c02011-03-25 13:09:25 -07002032 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002033 tryFailover(info.getType());
2034 if (mActiveDefaultNetwork != -1) {
2035 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002036 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2037 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002038 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002039 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2040 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002041 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002042
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002043 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002044
2045 final Intent immediateIntent = new Intent(intent);
2046 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2047 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002048 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002049 /*
2050 * If the failover network is already connected, then immediately send
2051 * out a followup broadcast indicating successful failover
2052 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002053 if (mActiveDefaultNetwork != -1) {
2054 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002055 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002056 }
2057
2058 private void sendStickyBroadcast(Intent intent) {
2059 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002060 if (!mSystemReady) {
2061 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002062 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002063 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002064 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002065 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002066 }
2067
Dianne Hackborne588ca12012-09-04 18:48:37 -07002068 final long ident = Binder.clearCallingIdentity();
2069 try {
2070 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2071 } finally {
2072 Binder.restoreCallingIdentity(ident);
2073 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002074 }
2075 }
2076
Wink Saville4f0de1e2011-08-04 15:01:58 -07002077 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2078 if (delayMs <= 0) {
2079 sendStickyBroadcast(intent);
2080 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002081 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002082 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2083 + intent.getAction());
2084 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002085 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2086 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2087 }
2088 }
2089
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002090 void systemReady() {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002091 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2092 loadGlobalProxy();
2093
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002094 synchronized(this) {
2095 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002096 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002097 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002098 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002099 }
2100 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002101 // load the global proxy at startup
2102 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002103
2104 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2105 // for user to unlock device.
2106 if (!updateLockdownVpn()) {
2107 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2108 mContext.registerReceiver(mUserPresentReceiver, filter);
2109 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002110 }
2111
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002112 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2113 @Override
2114 public void onReceive(Context context, Intent intent) {
2115 // Try creating lockdown tracker, since user present usually means
2116 // unlocked keystore.
2117 if (updateLockdownVpn()) {
2118 mContext.unregisterReceiver(this);
2119 }
2120 }
2121 };
2122
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002123 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002124 if (((type != mNetworkPreference)
2125 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2126 || (mNetworkPreference == mActiveDefaultNetwork)) {
2127 return false;
2128 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002129 return true;
2130 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002131
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002132 private void handleConnect(NetworkInfo info) {
2133 final int newNetType = info.getType();
2134
2135 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002136
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 // snapshot isFailover, because sendConnectedBroadcast() resets it
2138 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002139 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002140 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002141
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002142 if (VDBG) {
2143 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2144 + " isFailover" + isFailover);
2145 }
2146
Robert Greenwalt2034b912009-08-12 16:08:25 -07002147 // if this is a default net and other default is running
2148 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002149 if (mNetConfigs[newNetType].isDefault()) {
2150 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2151 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002152 // tear down the other
2153 NetworkStateTracker otherNet =
2154 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002155 if (DBG) {
2156 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002157 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002158 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002159 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002160 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002161 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002162 return;
2163 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002164 } else {
2165 // don't accept this one
2166 if (VDBG) {
2167 log("Not broadcasting CONNECT_ACTION " +
2168 "to torn down network " + info.getTypeName());
2169 }
2170 teardown(thisNet);
2171 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002172 }
2173 }
2174 synchronized (ConnectivityService.this) {
2175 // have a new default network, release the transition wakelock in a second
2176 // if it's held. The second pause is to allow apps to reconnect over the
2177 // new network
2178 if (mNetTransitionWakeLock.isHeld()) {
2179 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002180 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002181 mNetTransitionWakeLockSerialNumber, 0),
2182 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002183 }
2184 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002185 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002186 // this will cause us to come up initially as unconnected and switching
2187 // to connected after our normal pause unless somebody reports us as reall
2188 // disconnected
2189 mDefaultInetConditionPublished = 0;
2190 mDefaultConnectionSequence++;
2191 mInetConditionChangeInFlight = false;
2192 // Don't do this - if we never sign in stay, grey
2193 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002194 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002195 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002196 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002197 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002198 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002199
2200 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002201 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002202 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002203 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002204 } catch (RemoteException e) {
2205 // ignored; service lives in system_server
2206 }
2207 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002208 }
2209
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002210 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2211 if (DBG) log("Captive portal check " + info);
2212 int type = info.getType();
2213 final NetworkStateTracker thisNet = mNetTrackers[type];
2214 if (mNetConfigs[type].isDefault()) {
2215 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2216 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2217 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002218 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002219 return;
2220 } else {
2221 if (DBG) log("Tear down low priority net " + info.getTypeName());
2222 teardown(thisNet);
2223 return;
2224 }
2225 }
2226 }
2227
Wink Saville674777e2013-08-07 16:22:47 -07002228 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002229 thisNet.captivePortalCheckComplete();
2230 }
2231
2232 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002233 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002234 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002235 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002236 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002237 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002238 }
2239
Wink Saville674777e2013-08-07 16:22:47 -07002240 /** @hide */
2241 @Override
2242 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2243 enforceConnectivityInternalPermission();
2244 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2245 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2246 }
2247
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002249 * Setup data activity tracking for the given network interface.
2250 *
2251 * Every {@code setupDataActivityTracking} should be paired with a
2252 * {@link removeDataActivityTracking} for cleanup.
2253 */
2254 private void setupDataActivityTracking(int type) {
2255 final NetworkStateTracker thisNet = mNetTrackers[type];
2256 final String iface = thisNet.getLinkProperties().getInterfaceName();
2257
2258 final int timeout;
2259
2260 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002261 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2262 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002263 0);
2264 // Canonicalize mobile network type
2265 type = ConnectivityManager.TYPE_MOBILE;
2266 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002267 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2268 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002269 0);
2270 } else {
2271 // do not track any other networks
2272 timeout = 0;
2273 }
2274
2275 if (timeout > 0 && iface != null) {
2276 try {
2277 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2278 } catch (RemoteException e) {
2279 }
2280 }
2281 }
2282
2283 /**
2284 * Remove data activity tracking when network disconnects.
2285 */
2286 private void removeDataActivityTracking(int type) {
2287 final NetworkStateTracker net = mNetTrackers[type];
2288 final String iface = net.getLinkProperties().getInterfaceName();
2289
2290 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2291 ConnectivityManager.TYPE_WIFI == type)) {
2292 try {
2293 // the call fails silently if no idletimer setup for this interface
2294 mNetd.removeIdleTimer(iface);
2295 } catch (RemoteException e) {
2296 }
2297 }
2298 }
2299
2300 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002301 * After a change in the connectivity state of a network. We're mainly
2302 * concerned with making sure that the list of DNS servers is set up
2303 * according to which networks are connected, and ensuring that the
2304 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002305 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002306 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002307 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002308 if (VDBG) {
2309 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2310 + " resetMask=" + resetMask);
2311 }
Wink Saville051a6642011-07-13 13:44:13 -07002312
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002314 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002315 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002316 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002317 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002318
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002319 LinkProperties curLp = mCurrentLinkProperties[netType];
2320 LinkProperties newLp = null;
2321
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002322 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002323 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002324 if (VDBG) {
2325 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2326 " doReset=" + doReset + " resetMask=" + resetMask +
2327 "\n curLp=" + curLp +
2328 "\n newLp=" + newLp);
2329 }
2330
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002331 if (curLp != null) {
2332 if (curLp.isIdenticalInterfaceName(newLp)) {
2333 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2334 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2335 for (LinkAddress linkAddr : car.removed) {
2336 if (linkAddr.getAddress() instanceof Inet4Address) {
2337 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2338 }
2339 if (linkAddr.getAddress() instanceof Inet6Address) {
2340 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2341 }
Wink Saville051a6642011-07-13 13:44:13 -07002342 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002343 if (DBG) {
2344 log("handleConnectivityChange: addresses changed" +
2345 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2346 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002347 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002348 } else {
2349 if (DBG) {
2350 log("handleConnectivityChange: address are the same reset per doReset" +
2351 " linkProperty[" + netType + "]:" +
2352 " resetMask=" + resetMask);
2353 }
Wink Saville051a6642011-07-13 13:44:13 -07002354 }
2355 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002356 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002357 if (DBG) {
2358 log("handleConnectivityChange: interface not not equivalent reset both" +
2359 " linkProperty[" + netType + "]:" +
2360 " resetMask=" + resetMask);
2361 }
Wink Saville051a6642011-07-13 13:44:13 -07002362 }
Wink Saville051a6642011-07-13 13:44:13 -07002363 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002364 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002365 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002366 }
2367 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002368 if (VDBG) {
2369 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2370 " doReset=" + doReset + " resetMask=" + resetMask +
2371 "\n curLp=" + curLp +
2372 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002373 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002374 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002375 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002376 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002377
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002378 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002379 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002380 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002381 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002382 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002383 if (TextUtils.isEmpty(iface) == false) {
2384 if (resetMask != 0) {
2385 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2386 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002387
Lorenzo Colitti63839822013-03-20 19:22:58 +09002388 // Tell VPN the interface is down. It is a temporary
2389 // but effective fix to make VPN aware of the change.
2390 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2391 mVpn.interfaceStatusChanged(iface, false);
2392 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002393 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002394 if (resetDns) {
2395 flushVmDnsCache();
2396 if (VDBG) log("resetting DNS cache for " + iface);
2397 try {
2398 mNetd.flushInterfaceDnsCache(iface);
2399 } catch (Exception e) {
2400 // never crash - catch them all
2401 if (DBG) loge("Exception resetting dns cache: " + e);
2402 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002403 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002404 } else {
2405 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002406 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002407 }
2408 }
2409 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002410
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002411 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002412 NetworkStateTracker tracker = mNetTrackers[netType];
2413 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002414
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002415 // If the connection was previously using clat, but is not using it now, stop the clat
2416 // daemon. Normally, this happens automatically when the connection disconnects, but if
2417 // the disconnect is not reported, or if the connection's LinkProperties changed for
2418 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2419 // still be running. If it's not running, then stopping it is a no-op.
2420 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2421 mClat.stopClat();
2422 }
2423 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002424 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2425 mClat.startClat(tracker);
2426 } else {
2427 mClat.stopClat();
2428 }
2429 }
2430
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002431 // TODO: Temporary notifying upstread change to Tethering.
2432 // @see bug/4455071
2433 /** Notify TetheringService if interface name has been changed. */
2434 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002435 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002436 if (isTetheringSupported()) {
2437 mTethering.handleTetherIfaceChange();
2438 }
2439 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002440 }
2441
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002442 /**
2443 * Add and remove routes using the old properties (null if not previously connected),
2444 * new properties (null if becoming disconnected). May even be double null, which
2445 * is a noop.
2446 * Uses isLinkDefault to determine if default routes should be set or conversely if
2447 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002448 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002449 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002450 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2451 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002452 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002453 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2454 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002455 if (curLp != null) {
2456 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002457 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002458 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002459 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002460 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002461 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002462 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002463
Robert Greenwalt8d777252011-08-15 12:31:55 -07002464 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2465
Robert Greenwalt98107422011-07-22 11:55:33 -07002466 for (RouteInfo r : routeDiff.removed) {
2467 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002468 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002469 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2470 }
2471 if (isLinkDefault == false) {
2472 // remove from a secondary route table
2473 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002474 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002475 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002476
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002477 if (!isLinkDefault) {
2478 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002479 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002480 // routes changed - remove all old dns entries and add new
2481 if (curLp != null) {
2482 for (InetAddress oldDns : curLp.getDnses()) {
2483 removeRouteToAddress(curLp, oldDns);
2484 }
2485 }
2486 if (newLp != null) {
2487 for (InetAddress newDns : newLp.getDnses()) {
2488 addRouteToAddress(newLp, newDns);
2489 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002490 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002491 } else {
2492 // no change in routes, check for change in dns themselves
2493 for (InetAddress oldDns : dnsDiff.removed) {
2494 removeRouteToAddress(curLp, oldDns);
2495 }
2496 for (InetAddress newDns : dnsDiff.added) {
2497 addRouteToAddress(newLp, newDns);
2498 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002499 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002500 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002501
2502 for (RouteInfo r : routeDiff.added) {
2503 if (isLinkDefault || ! r.isDefaultRoute()) {
2504 addRoute(newLp, r, TO_DEFAULT_TABLE);
2505 } else {
2506 // add to a secondary route table
2507 addRoute(newLp, r, TO_SECONDARY_TABLE);
2508
2509 // many radios add a default route even when we don't want one.
2510 // remove the default route unless somebody else has asked for it
2511 String ifaceName = newLp.getInterfaceName();
2512 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002513 try {
2514 mNetd.removeRoute(ifaceName, r);
2515 } catch (Exception e) {
2516 // never crash - catch them all
2517 if (DBG) loge("Exception trying to remove a route: " + e);
2518 }
2519 }
2520 }
2521 }
2522
Robert Greenwalt8d777252011-08-15 12:31:55 -07002523 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002524 }
2525
2526
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002527 /**
2528 * Reads the network specific TCP buffer sizes from SystemProperties
2529 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2530 * wide use
2531 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002532 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002533 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002534 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002535
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002536 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002537 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002538
2539 // Setting to default values so we won't be stuck to previous values
2540 key = "net.tcp.buffersize.default";
2541 bufferSizes = SystemProperties.get(key);
2542 }
2543
2544 // Set values in kernel
2545 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002546 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002547 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002548 + "] which comes from [" + key + "]");
2549 }
2550 setBufferSize(bufferSizes);
2551 }
2552 }
2553
2554 /**
2555 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2556 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2557 *
2558 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2559 * writeMin, writeInitial, writeMax"
2560 */
2561 private void setBufferSize(String bufferSizes) {
2562 try {
2563 String[] values = bufferSizes.split(",");
2564
2565 if (values.length == 6) {
2566 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002567 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2568 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2569 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2570 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2571 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2572 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002573 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002574 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002575 }
2576 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002577 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002578 }
2579 }
2580
Robert Greenwalt2034b912009-08-12 16:08:25 -07002581 /**
2582 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2583 * on the highest priority active net which this process requested.
2584 * If there aren't any, clear it out
2585 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002586 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002587 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002588 if (VDBG) log("reassessPidDns for pid " + pid);
2589 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002590 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002591 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002592 continue;
2593 }
2594 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002595 if (nt.getNetworkInfo().isConnected() &&
2596 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002597 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002598 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002599 if (mNetRequestersPids[i].contains(myPid)) {
2600 try {
2601 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2602 } catch (Exception e) {
2603 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002604 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002605 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002606 }
2607 }
2608 }
2609 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002610 try {
2611 mNetd.clearDnsInterfaceForPid(pid);
2612 } catch (Exception e) {
2613 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002614 }
2615 }
2616
Mattias Falkd697aa22011-08-23 14:15:13 +02002617 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002618 /*
2619 * Tell the VMs to toss their DNS caches
2620 */
2621 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2622 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002623 /*
2624 * Connectivity events can happen before boot has completed ...
2625 */
2626 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002627 final long ident = Binder.clearCallingIdentity();
2628 try {
2629 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2630 } finally {
2631 Binder.restoreCallingIdentity(ident);
2632 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002633 }
2634
Chia-chi Yehcc844502011-07-14 18:01:57 -07002635 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002636 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002637 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002638 int last = 0;
2639 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002640 dnses = new ArrayList();
2641 dnses.add(mDefaultDns);
2642 if (DBG) {
2643 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002644 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002645 }
2646
Mattias Falkd697aa22011-08-23 14:15:13 +02002647 try {
2648 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2649 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002650 for (InetAddress dns : dnses) {
2651 ++last;
2652 String key = "net.dns" + last;
2653 String value = dns.getHostAddress();
2654 SystemProperties.set(key, value);
2655 }
2656 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2657 String key = "net.dns" + i;
2658 SystemProperties.set(key, "");
2659 }
2660 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002661 } catch (Exception e) {
2662 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002663 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002664 }
2665
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002666 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002667 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002668 NetworkStateTracker nt = mNetTrackers[netType];
2669 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002670 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002671 if (p == null) return;
2672 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002673 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002674 String network = nt.getNetworkInfo().getTypeName();
2675 synchronized (mDnsLock) {
2676 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002677 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002678 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002679 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002680 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002681 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002682 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002683 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002684 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002685 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002686 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002687 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002688 List<Integer> pids = mNetRequestersPids[netType];
2689 for (Integer pid : pids) {
2690 try {
2691 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2692 } catch (Exception e) {
2693 Slog.e(TAG, "exception setting interface for pid: " + e);
2694 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002695 }
2696 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002697 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002698 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002699 }
2700
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002701 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002702 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2703 NETWORK_RESTORE_DELAY_PROP_NAME);
2704 if(restoreDefaultNetworkDelayStr != null &&
2705 restoreDefaultNetworkDelayStr.length() != 0) {
2706 try {
2707 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2708 } catch (NumberFormatException e) {
2709 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002710 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002711 // if the system property isn't set, use the value for the apn type
2712 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2713
2714 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2715 (mNetConfigs[networkType] != null)) {
2716 ret = mNetConfigs[networkType].restoreTime;
2717 }
2718 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002719 }
2720
2721 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002722 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2723 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002724 if (mContext.checkCallingOrSelfPermission(
2725 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002726 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002727 pw.println("Permission Denial: can't dump ConnectivityService " +
2728 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2729 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002730 return;
2731 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002732
2733 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002734 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002735 for (int i = 0; i < mNetTrackers.length; i++) {
2736 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002737 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002738 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2739 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002740 if (nst.getNetworkInfo().isConnected()) {
2741 pw.println("Active network: " + nst.getNetworkInfo().
2742 getTypeName());
2743 }
2744 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002745 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002746 pw.println(nst);
2747 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002748 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002749 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002750 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002751
2752 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002753 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002754 for (int net : mPriorityList) {
2755 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002756 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002757 pidString = pidString + pid.toString() + ", ";
2758 }
2759 pw.println(pidString);
2760 }
2761 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002762 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002763
2764 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002765 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002766 for (Object requester : mFeatureUsers) {
2767 pw.println(requester.toString());
2768 }
2769 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002770 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002771
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002772 synchronized (this) {
2773 pw.println("NetworkTranstionWakeLock is currently " +
2774 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2775 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2776 }
2777 pw.println();
2778
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002779 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002780
2781 if (mInetLog != null) {
2782 pw.println();
2783 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002784 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002785 for(int i = 0; i < mInetLog.size(); i++) {
2786 pw.println(mInetLog.get(i));
2787 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002788 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002789 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002790 }
2791
Robert Greenwalt2034b912009-08-12 16:08:25 -07002792 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002793 private class NetworkStateTrackerHandler extends Handler {
2794 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002795 super(looper);
2796 }
2797
The Android Open Source Project28527d22009-03-03 19:31:44 -08002798 @Override
2799 public void handleMessage(Message msg) {
2800 NetworkInfo info;
2801 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002802 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002803 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002804 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002805
Wink Savillea7d56572011-09-21 11:05:43 -07002806 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Savilleb1a32022013-09-05 12:02:25 -07002807 (state == NetworkInfo.State.DISCONNECTED) ||
2808 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002809 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002810 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002811 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002812 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002813
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002814 // Since mobile has the notion of a network/apn that can be used for
2815 // provisioning we need to check every time we're connected as
2816 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2817 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2818 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2819 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2820 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002821 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2822 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleb1a32022013-09-05 12:02:25 -07002823 && ((state == NetworkInfo.State.CONNECTED)
2824 || info.isConnectedToProvisioningNetwork())) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002825 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002826 }
2827
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002828 EventLogTags.writeConnectivityStateChanged(
2829 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002830
2831 if (info.getDetailedState() ==
2832 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002833 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002834 } else if (info.getDetailedState() ==
2835 DetailedState.CAPTIVE_PORTAL_CHECK) {
2836 handleCaptivePortalTrackerCheck(info);
Wink Savilleb1a32022013-09-05 12:02:25 -07002837 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002838 /**
2839 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2840 * for now its an in between network, its a network that
2841 * is actually a default network but we don't want it to be
2842 * announced as such to keep background applications from
2843 * trying to use it. It turns out that some still try so we
2844 * take the additional step of clearing any default routes
2845 * to the link that may have incorrectly setup by the lower
2846 * levels.
2847 */
2848 LinkProperties lp = getLinkProperties(info.getType());
2849 if (DBG) {
2850 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2851 }
2852
2853 // Clear any default routes setup by the radio so
2854 // any activity by applications trying to use this
2855 // connection will fail until the provisioning network
2856 // is enabled.
2857 for (RouteInfo r : lp.getRoutes()) {
2858 removeRoute(lp, r, TO_DEFAULT_TABLE);
2859 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002860 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002861 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002862 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002863 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002864 // the logic here is, handle SUSPENDED the same as
2865 // DISCONNECTED. The only difference being we are
2866 // broadcasting an intent with NetworkInfo that's
2867 // suspended. This allows the applications an
2868 // opportunity to handle DISCONNECTED and SUSPENDED
2869 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002870 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002871 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002872 handleConnect(info);
2873 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002874 if (mLockdownTracker != null) {
2875 mLockdownTracker.onNetworkInfoChanged(info);
2876 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002877 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002878 }
2879 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002880 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002881 // TODO: Temporary allowing network configuration
2882 // change not resetting sockets.
2883 // @see bug/4455071
2884 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002885 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002886 }
2887 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002888 info = (NetworkInfo) msg.obj;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002889 int type = info.getType();
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002890 updateNetworkSettings(mNetTrackers[type]);
2891 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002892 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002893 }
2894 }
2895 }
2896
2897 private class InternalHandler extends Handler {
2898 public InternalHandler(Looper looper) {
2899 super(looper);
2900 }
2901
2902 @Override
2903 public void handleMessage(Message msg) {
2904 NetworkInfo info;
2905 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002906 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002907 String causedBy = null;
2908 synchronized (ConnectivityService.this) {
2909 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2910 mNetTransitionWakeLock.isHeld()) {
2911 mNetTransitionWakeLock.release();
2912 causedBy = mNetTransitionWakeLockCausedBy;
2913 }
2914 }
2915 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002916 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002917 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002918 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002919 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002920 FeatureUser u = (FeatureUser)msg.obj;
2921 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002922 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002923 case EVENT_INET_CONDITION_CHANGE:
2924 {
2925 int netType = msg.arg1;
2926 int condition = msg.arg2;
2927 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002928 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002929 }
2930 case EVENT_INET_CONDITION_HOLD_END:
2931 {
2932 int netType = msg.arg1;
2933 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00002934 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002935 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002936 }
2937 case EVENT_SET_NETWORK_PREFERENCE:
2938 {
2939 int preference = msg.arg1;
2940 handleSetNetworkPreference(preference);
2941 break;
2942 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002943 case EVENT_SET_MOBILE_DATA:
2944 {
2945 boolean enabled = (msg.arg1 == ENABLED);
2946 handleSetMobileData(enabled);
2947 break;
2948 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002949 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2950 {
2951 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002952 break;
2953 }
2954 case EVENT_SET_DEPENDENCY_MET:
2955 {
2956 boolean met = (msg.arg1 == ENABLED);
2957 handleSetDependencyMet(msg.arg2, met);
2958 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002959 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002960 case EVENT_RESTORE_DNS:
2961 {
2962 if (mActiveDefaultNetwork != -1) {
2963 handleDnsConfigurationChange(mActiveDefaultNetwork);
2964 }
2965 break;
2966 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002967 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2968 {
2969 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002970 sendStickyBroadcast(intent);
2971 break;
2972 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002973 case EVENT_SET_POLICY_DATA_ENABLE: {
2974 final int networkType = msg.arg1;
2975 final boolean enabled = msg.arg2 == ENABLED;
2976 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002977 break;
2978 }
2979 case EVENT_VPN_STATE_CHANGED: {
2980 if (mLockdownTracker != null) {
2981 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2982 }
2983 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002984 }
Wink Saville32506bc2013-06-29 21:10:57 -07002985 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2986 int tag = mEnableFailFastMobileDataTag.get();
2987 if (msg.arg1 == tag) {
2988 MobileDataStateTracker mobileDst =
2989 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2990 if (mobileDst != null) {
2991 mobileDst.setEnableFailFastMobileData(msg.arg2);
2992 }
2993 } else {
2994 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2995 + " != tag:" + tag);
2996 }
2997 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002998 }
2999 }
3000 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003001
3002 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003003 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003004 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003005
3006 if (isTetheringSupported()) {
3007 return mTethering.tether(iface);
3008 } else {
3009 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3010 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003011 }
3012
3013 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003014 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003015 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003016
3017 if (isTetheringSupported()) {
3018 return mTethering.untether(iface);
3019 } else {
3020 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3021 }
3022 }
3023
3024 // javadoc from interface
3025 public int getLastTetherError(String iface) {
3026 enforceTetherAccessPermission();
3027
3028 if (isTetheringSupported()) {
3029 return mTethering.getLastTetherError(iface);
3030 } else {
3031 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3032 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003033 }
3034
3035 // TODO - proper iface API for selection by property, inspection, etc
3036 public String[] getTetherableUsbRegexs() {
3037 enforceTetherAccessPermission();
3038 if (isTetheringSupported()) {
3039 return mTethering.getTetherableUsbRegexs();
3040 } else {
3041 return new String[0];
3042 }
3043 }
3044
3045 public String[] getTetherableWifiRegexs() {
3046 enforceTetherAccessPermission();
3047 if (isTetheringSupported()) {
3048 return mTethering.getTetherableWifiRegexs();
3049 } else {
3050 return new String[0];
3051 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003052 }
3053
Danica Chang96567052010-08-11 14:54:43 -07003054 public String[] getTetherableBluetoothRegexs() {
3055 enforceTetherAccessPermission();
3056 if (isTetheringSupported()) {
3057 return mTethering.getTetherableBluetoothRegexs();
3058 } else {
3059 return new String[0];
3060 }
3061 }
3062
Mike Lockwooded4a1742011-07-19 13:04:47 -07003063 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003064 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003065 if (isTetheringSupported()) {
3066 return mTethering.setUsbTethering(enable);
3067 } else {
3068 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3069 }
3070 }
3071
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003072 // TODO - move iface listing, queries, etc to new module
3073 // javadoc from interface
3074 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003075 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003076 return mTethering.getTetherableIfaces();
3077 }
3078
3079 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003080 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003081 return mTethering.getTetheredIfaces();
3082 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003083
Jeff Sharkey300f08f2011-09-16 01:52:49 -07003084 @Override
3085 public String[] getTetheredIfacePairs() {
3086 enforceTetherAccessPermission();
3087 return mTethering.getTetheredIfacePairs();
3088 }
3089
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003090 public String[] getTetheringErroredIfaces() {
3091 enforceTetherAccessPermission();
3092 return mTethering.getErroredIfaces();
3093 }
3094
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003095 // if ro.tether.denied = true we default to no tethering
3096 // gservices could set the secure setting to 1 though to enable it on a build where it
3097 // had previously been turned off.
3098 public boolean isTetheringSupported() {
3099 enforceTetherAccessPermission();
3100 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003101 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3102 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt368095f2013-07-18 14:24:42 -07003103 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3104 mTethering.getTetherableWifiRegexs().length != 0 ||
3105 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3106 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003107 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003108
3109 // An API NetworkStateTrackers can call when they lose their network.
3110 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3111 // whichever happens first. The timer is started by the first caller and not
3112 // restarted by subsequent callers.
3113 public void requestNetworkTransitionWakelock(String forWhom) {
3114 enforceConnectivityInternalPermission();
3115 synchronized (this) {
3116 if (mNetTransitionWakeLock.isHeld()) return;
3117 mNetTransitionWakeLockSerialNumber++;
3118 mNetTransitionWakeLock.acquire();
3119 mNetTransitionWakeLockCausedBy = forWhom;
3120 }
3121 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003122 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003123 mNetTransitionWakeLockSerialNumber, 0),
3124 mNetTransitionWakeLockTimeout);
3125 return;
3126 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003127
Robert Greenwalt986c7412010-09-08 15:24:47 -07003128 // 100 percent is full good, 0 is full bad.
3129 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003130 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003131 mContext.enforceCallingOrSelfPermission(
3132 android.Manifest.permission.STATUS_BAR,
3133 "ConnectivityService");
3134
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003135 if (DBG) {
3136 int pid = getCallingPid();
3137 int uid = getCallingUid();
3138 String s = pid + "(" + uid + ") reports inet is " +
3139 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3140 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3141 mInetLog.add(s);
3142 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3143 mInetLog.remove(0);
3144 }
3145 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003146 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003147 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3148 }
3149
3150 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003151 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003152 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003153 return;
3154 }
3155 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003156 if (DBG) log("handleInetConditionChange: net=" + netType +
3157 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003158 return;
3159 }
Wink Savillea7d56572011-09-21 11:05:43 -07003160 if (VDBG) {
3161 log("handleInetConditionChange: net=" +
3162 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003163 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003164 }
Wink Saville151eaa62013-01-31 00:30:13 +00003165 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003166 int delay;
3167 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003168 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003169 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003170 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003171 delay = Settings.Global.getInt(mContext.getContentResolver(),
3172 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003173 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003174 delay = Settings.Global.getInt(mContext.getContentResolver(),
3175 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003176 }
3177 mInetConditionChangeInFlight = true;
3178 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003179 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003180 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003181 // we've set the new condition, when this hold ends that will get picked up
3182 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003183 }
3184 }
3185
Wink Saville151eaa62013-01-31 00:30:13 +00003186 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003187 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003188 log("handleInetConditionHoldEnd: net=" + netType +
3189 ", condition=" + mDefaultInetCondition +
3190 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003191 }
3192 mInetConditionChangeInFlight = false;
3193
3194 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003195 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003196 return;
3197 }
3198 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003199 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003200 return;
3201 }
Wink Saville151eaa62013-01-31 00:30:13 +00003202 // TODO: Figure out why this optimization sometimes causes a
3203 // change in mDefaultInetCondition to be missed and the
3204 // UI to not be updated.
3205 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3206 // if (DBG) log("no change in condition - aborting");
3207 // return;
3208 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003209 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3210 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003211 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003212 return;
3213 }
Wink Saville151eaa62013-01-31 00:30:13 +00003214 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003215 sendInetConditionBroadcast(networkInfo);
3216 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003217 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003218
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003219 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003220 // this information is already available as a world read/writable jvm property
3221 // so this API change wouldn't have a benifit. It also breaks the passing
3222 // of proxy info to all the JVMs.
3223 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003224 synchronized (mProxyLock) {
3225 if (mGlobalProxy != null) return mGlobalProxy;
3226 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003227 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003228 }
3229
3230 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003231 enforceConnectivityInternalPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003232 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003233 if (proxyProperties == mGlobalProxy) return;
3234 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3235 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3236
3237 String host = "";
3238 int port = 0;
3239 String exclList = "";
3240 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3241 mGlobalProxy = new ProxyProperties(proxyProperties);
3242 host = mGlobalProxy.getHost();
3243 port = mGlobalProxy.getPort();
3244 exclList = mGlobalProxy.getExclusionList();
3245 } else {
3246 mGlobalProxy = null;
3247 }
3248 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003249 final long token = Binder.clearCallingIdentity();
3250 try {
3251 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3252 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3253 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3254 exclList);
3255 } finally {
3256 Binder.restoreCallingIdentity(token);
3257 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003258 }
3259
3260 if (mGlobalProxy == null) {
3261 proxyProperties = mDefaultProxy;
3262 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003263 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003264 }
3265
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003266 private void loadGlobalProxy() {
3267 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003268 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3269 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3270 String exclList = Settings.Global.getString(res,
3271 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003272 if (!TextUtils.isEmpty(host)) {
3273 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003274 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003275 mGlobalProxy = proxyProperties;
3276 }
3277 }
3278 }
3279
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003280 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003281 // this information is already available as a world read/writable jvm property
3282 // so this API change wouldn't have a benifit. It also breaks the passing
3283 // of proxy info to all the JVMs.
3284 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003285 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003286 return mGlobalProxy;
3287 }
3288 }
3289
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003290 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3291 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3292 proxy = null;
3293 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003294 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003295 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003296 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003297 mDefaultProxy = proxy;
3298
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003299 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003300 if (!mDefaultProxyDisabled) {
3301 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003302 }
3303 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003304 }
3305
3306 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003307 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3308 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003309 if (!TextUtils.isEmpty(proxy)) {
3310 String data[] = proxy.split(":");
3311 String proxyHost = data[0];
3312 int proxyPort = 8080;
3313 if (data.length > 1) {
3314 try {
3315 proxyPort = Integer.parseInt(data[1]);
3316 } catch (NumberFormatException e) {
3317 return;
3318 }
3319 }
3320 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3321 setGlobalProxy(p);
3322 }
3323 }
3324
3325 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003326 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003327 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003328 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003329 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3330 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003331 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003332 final long ident = Binder.clearCallingIdentity();
3333 try {
3334 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3335 } finally {
3336 Binder.restoreCallingIdentity(ident);
3337 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003338 }
3339
3340 private static class SettingsObserver extends ContentObserver {
3341 private int mWhat;
3342 private Handler mHandler;
3343 SettingsObserver(Handler handler, int what) {
3344 super(handler);
3345 mHandler = handler;
3346 mWhat = what;
3347 }
3348
3349 void observe(Context context) {
3350 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003351 resolver.registerContentObserver(Settings.Global.getUriFor(
3352 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003353 }
3354
3355 @Override
3356 public void onChange(boolean selfChange) {
3357 mHandler.obtainMessage(mWhat).sendToTarget();
3358 }
3359 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003360
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003361 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003362 Slog.d(TAG, s);
3363 }
3364
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003365 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003366 Slog.e(TAG, s);
3367 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003368
repo syncf5de5572011-07-29 23:55:49 -07003369 int convertFeatureToNetworkType(int networkType, String feature) {
3370 int usedNetworkType = networkType;
3371
3372 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3373 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3374 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3375 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3376 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3377 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3378 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3379 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3380 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3381 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3382 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3383 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3384 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3385 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3386 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3387 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3388 } else {
3389 Slog.e(TAG, "Can't match any mobile netTracker!");
3390 }
3391 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3392 if (TextUtils.equals(feature, "p2p")) {
3393 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3394 } else {
3395 Slog.e(TAG, "Can't match any wifi netTracker!");
3396 }
3397 } else {
3398 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003399 }
repo syncf5de5572011-07-29 23:55:49 -07003400 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003401 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003402
3403 private static <T> T checkNotNull(T value, String message) {
3404 if (value == null) {
3405 throw new NullPointerException(message);
3406 }
3407 return value;
3408 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003409
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003410 /**
3411 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003412 * VpnBuilder and not available in ConnectivityManager. Permissions
3413 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003414 * @hide
3415 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003416 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003417 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003418 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003419 try {
3420 int type = mActiveDefaultNetwork;
Robert Greenwalt15a41532012-08-21 19:27:00 -07003421 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003422 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3423 return true;
3424 }
3425 } catch (Exception e) {
3426 // ignore
3427 } finally {
3428 try {
3429 socket.close();
3430 } catch (Exception e) {
3431 // ignore
3432 }
3433 }
3434 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003435 }
3436
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003437 /**
3438 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003439 * and not available in ConnectivityManager. Permissions are checked
3440 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003441 * @hide
3442 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003443 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003444 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003445 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003446 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003447 }
3448
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003449 /**
3450 * Configure a TUN interface and return its file descriptor. Parameters
3451 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003452 * and not available in ConnectivityManager. Permissions are checked in
3453 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003454 * @hide
3455 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003456 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003457 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003458 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003459 return mVpn.establish(config);
3460 }
3461
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003462 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003463 * Start legacy VPN, controlling native daemons as needed. Creates a
3464 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003465 */
3466 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003467 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003468 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003469 final LinkProperties egress = getActiveLinkProperties();
3470 if (egress == null) {
3471 throw new IllegalStateException("Missing active network connection");
3472 }
3473 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003474 }
3475
3476 /**
3477 * Return the information of the ongoing legacy VPN. This method is used
3478 * by VpnSettings and not available in ConnectivityManager. Permissions
3479 * are checked in Vpn class.
3480 * @hide
3481 */
3482 @Override
3483 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003484 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003485 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003486 }
3487
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003488 /**
3489 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3490 * through NetworkStateTracker since it works differently. For example, it
3491 * needs to override DNS servers but never takes the default routes. It
3492 * relies on another data network, and it could keep existing connections
3493 * alive after reconnecting, switching between networks, or even resuming
3494 * from deep sleep. Calls from applications should be done synchronously
3495 * to avoid race conditions. As these are all hidden APIs, refactoring can
3496 * be done whenever a better abstraction is developed.
3497 */
3498 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003499 private VpnCallback() {
3500 }
3501
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003502 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003503 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003504 }
3505
Chia-chi Yehcc844502011-07-14 18:01:57 -07003506 public void override(List<String> dnsServers, List<String> searchDomains) {
3507 if (dnsServers == null) {
3508 restore();
3509 return;
3510 }
3511
3512 // Convert DNS servers into addresses.
3513 List<InetAddress> addresses = new ArrayList<InetAddress>();
3514 for (String address : dnsServers) {
3515 // Double check the addresses and remove invalid ones.
3516 try {
3517 addresses.add(InetAddress.parseNumericAddress(address));
3518 } catch (Exception e) {
3519 // ignore
3520 }
3521 }
3522 if (addresses.isEmpty()) {
3523 restore();
3524 return;
3525 }
3526
3527 // Concatenate search domains into a string.
3528 StringBuilder buffer = new StringBuilder();
3529 if (searchDomains != null) {
3530 for (String domain : searchDomains) {
3531 buffer.append(domain).append(' ');
3532 }
3533 }
3534 String domains = buffer.toString().trim();
3535
3536 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003537 synchronized (mDnsLock) {
Mattias Falkd697aa22011-08-23 14:15:13 +02003538 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003539 mDnsOverridden = true;
3540 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003541
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003542 // Temporarily disable the default proxy (not global).
3543 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003544 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003545 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003546 sendProxyBroadcast(null);
3547 }
3548 }
3549
3550 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003551 }
3552
Chia-chi Yehcc844502011-07-14 18:01:57 -07003553 public void restore() {
3554 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003555 if (mDnsOverridden) {
3556 mDnsOverridden = false;
3557 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003558 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003559 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003560 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003561 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003562 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003563 sendProxyBroadcast(mDefaultProxy);
3564 }
3565 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003566 }
3567 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003568
3569 @Override
3570 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003571 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3572 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3573 return false;
3574 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003575
3576 // Tear down existing lockdown if profile was removed
3577 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3578 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003579 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003580 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3581 return false;
3582 }
3583
3584 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3585 final VpnProfile profile = VpnProfile.decode(
3586 profileName, mKeyStore.get(Credentials.VPN + profileName));
3587 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3588 } else {
3589 setLockdownTracker(null);
3590 }
3591
3592 return true;
3593 }
3594
3595 /**
3596 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3597 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3598 */
3599 private void setLockdownTracker(LockdownVpnTracker tracker) {
3600 // Shutdown any existing tracker
3601 final LockdownVpnTracker existing = mLockdownTracker;
3602 mLockdownTracker = null;
3603 if (existing != null) {
3604 existing.shutdown();
3605 }
3606
3607 try {
3608 if (tracker != null) {
3609 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003610 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003611 mLockdownTracker = tracker;
3612 mLockdownTracker.init();
3613 } else {
3614 mNetd.setFirewallEnabled(false);
3615 }
3616 } catch (RemoteException e) {
3617 // ignored; NMS lives inside system_server
3618 }
3619 }
3620
3621 private void throwIfLockdownEnabled() {
3622 if (mLockdownEnabled) {
3623 throw new IllegalStateException("Unavailable in lockdown mode");
3624 }
3625 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003626
3627 public void supplyMessenger(int networkType, Messenger messenger) {
3628 enforceConnectivityInternalPermission();
3629
3630 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3631 mNetTrackers[networkType].supplyMessenger(messenger);
3632 }
3633 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003634
3635 public int findConnectionTypeForIface(String iface) {
3636 enforceConnectivityInternalPermission();
3637
3638 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3639 for (NetworkStateTracker tracker : mNetTrackers) {
3640 if (tracker != null) {
3641 LinkProperties lp = tracker.getLinkProperties();
3642 if (lp != null && iface.equals(lp.getInterfaceName())) {
3643 return tracker.getNetworkInfo().getType();
3644 }
3645 }
3646 }
3647 return ConnectivityManager.TYPE_NONE;
3648 }
Wink Saville32506bc2013-06-29 21:10:57 -07003649
3650 /**
3651 * Have mobile data fail fast if enabled.
3652 *
3653 * @param enabled DctConstants.ENABLED/DISABLED
3654 */
3655 private void setEnableFailFastMobileData(int enabled) {
3656 int tag;
3657
3658 if (enabled == DctConstants.ENABLED) {
3659 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3660 } else {
3661 tag = mEnableFailFastMobileDataTag.get();
3662 }
3663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3664 enabled));
3665 }
3666
Wink Savilled23fa092013-08-16 17:17:28 -07003667 private boolean isMobileDataStateTrackerReady() {
3668 MobileDataStateTracker mdst =
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003669 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilled23fa092013-08-16 17:17:28 -07003670 return (mdst != null) && (mdst.isReady());
3671 }
3672
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003673 /**
3674 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3675 */
3676
3677 /**
3678 * No connection was possible to the network.
3679 */
3680 public static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
3681
3682 /**
3683 * A connection was made to the internet, all is well.
3684 */
3685 public static final int CMP_RESULT_CODE_CONNECTABLE = 1;
3686
3687 /**
3688 * A connection was made but there was a redirection, we appear to be in walled garden.
3689 * This is an indication of a warm sim on a mobile network.
3690 */
3691 public static final int CMP_RESULT_CODE_REDIRECTED = 2;
3692
3693 /**
3694 * A connection was made but no dns server was available to resolve a name to address.
3695 * This is an indication of a warm sim on a mobile network.
3696 */
3697 public static final int CMP_RESULT_CODE_NO_DNS = 3;
3698
3699 /**
3700 * A connection was made but could not open a TCP connection.
3701 * This is an indication of a warm sim on a mobile network.
3702 */
3703 public static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 4;
3704
3705 /**
3706 * The mobile network is a provisioning network.
3707 * This is an indication of a warm sim on a mobile network.
3708 */
3709 public static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
3710
3711 AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
3712
Wink Saville32506bc2013-06-29 21:10:57 -07003713 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003714 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3715 int timeOutMs = -1;
3716 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3717 enforceConnectivityInternalPermission();
Wink Savilled469c472013-07-02 10:55:14 -07003718
Wink Saville32506bc2013-06-29 21:10:57 -07003719 final long token = Binder.clearCallingIdentity();
3720 try {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003721 timeOutMs = suggestedTimeOutMs;
3722 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3723 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3724 }
3725
3726 // Check that mobile networks are supported
3727 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3728 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3729 if (DBG) log("checkMobileProvisioning: X no mobile network");
3730 return timeOutMs;
3731 }
3732
3733 // If we're already checking don't do it again
3734 // TODO: Add a queue of results...
3735 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3736 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3737 return timeOutMs;
3738 }
3739
3740 // Start off with notification off
3741 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
3742
3743 // See if we've alreadying determined if we've got a provsioning connection
3744 // if so we don't need to do anything active
3745 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
3746 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3747 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
3748
3749 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
3750 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3751 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
3752
3753 if (isDefaultProvisioning || isHipriProvisioning) {
3754 if (mIsNotificationVisible) {
3755 if (DBG) {
3756 log("checkMobileProvisioning: provisioning-ignore notification is visible");
3757 }
3758 } else {
3759 NetworkInfo ni = null;
3760 if (isDefaultProvisioning) {
3761 ni = mdstDefault.getNetworkInfo();
3762 }
3763 if (isHipriProvisioning) {
3764 ni = mdstHipri.getNetworkInfo();
3765 }
3766 String url = getMobileProvisioningUrl();
3767 if ((ni != null) && (!TextUtils.isEmpty(url))) {
3768 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(), url);
3769 } else {
3770 if (DBG) log("checkMobileProvisioning: provisioning but no url, ignore");
3771 }
3772 }
3773 mIsCheckingMobileProvisioning.set(false);
3774 return timeOutMs;
3775 }
3776
Wink Saville32506bc2013-06-29 21:10:57 -07003777 CheckMp checkMp = new CheckMp(mContext, this);
3778 CheckMp.CallBack cb = new CheckMp.CallBack() {
3779 @Override
3780 void onComplete(Integer result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003781 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07003782 NetworkInfo ni =
3783 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3784 switch(result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003785 case CMP_RESULT_CODE_CONNECTABLE:
3786 case CMP_RESULT_CODE_NO_CONNECTION: {
3787 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville32506bc2013-06-29 21:10:57 -07003788 break;
3789 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003790 case CMP_RESULT_CODE_REDIRECTED: {
3791 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt39d56012013-07-16 12:06:09 -07003792 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07003793 if (TextUtils.isEmpty(url)) {
Robert Greenwalt39d56012013-07-16 12:06:09 -07003794 url = getMobileRedirectedProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07003795 }
3796 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003797 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
3798 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
3799 url);
Wink Saville32506bc2013-06-29 21:10:57 -07003800 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003801 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07003802 }
3803 break;
3804 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003805 case CMP_RESULT_CODE_NO_DNS:
3806 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalt39d56012013-07-16 12:06:09 -07003807 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07003808 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003809 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
3810 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
3811 url);
Wink Saville32506bc2013-06-29 21:10:57 -07003812 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003813 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07003814 }
3815 break;
3816 }
3817 default: {
3818 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3819 break;
3820 }
3821 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003822 mIsCheckingMobileProvisioning.set(false);
Wink Saville32506bc2013-06-29 21:10:57 -07003823 }
3824 };
3825 CheckMp.Params params =
3826 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003827 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville32506bc2013-06-29 21:10:57 -07003828 checkMp.execute(params);
3829 } finally {
3830 Binder.restoreCallingIdentity(token);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003831 if (DBG) log("checkMobileProvisioning: X");
Wink Saville32506bc2013-06-29 21:10:57 -07003832 }
3833 return timeOutMs;
3834 }
3835
3836 static class CheckMp extends
3837 AsyncTask<CheckMp.Params, Void, Integer> {
3838 private static final String CHECKMP_TAG = "CheckMp";
3839 public static final int MAX_TIMEOUT_MS = 60000;
3840 private static final int SOCKET_TIMEOUT_MS = 5000;
3841 private Context mContext;
3842 private ConnectivityService mCs;
3843 private TelephonyManager mTm;
3844 private Params mParams;
3845
3846 /**
3847 * Parameters for AsyncTask.execute
3848 */
3849 static class Params {
3850 private String mUrl;
3851 private long mTimeOutMs;
3852 private CallBack mCb;
3853
3854 Params(String url, long timeOutMs, CallBack cb) {
3855 mUrl = url;
3856 mTimeOutMs = timeOutMs;
3857 mCb = cb;
3858 }
3859
3860 @Override
3861 public String toString() {
3862 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3863 }
3864 }
3865
3866 /**
3867 * The call back object passed in Params. onComplete will be called
3868 * on the main thread.
3869 */
3870 abstract static class CallBack {
3871 // Called on the main thread.
3872 abstract void onComplete(Integer result);
3873 }
3874
3875 public CheckMp(Context context, ConnectivityService cs) {
3876 mContext = context;
3877 mCs = cs;
3878
3879 // Setup access to TelephonyService we'll be using.
3880 mTm = (TelephonyManager) mContext.getSystemService(
3881 Context.TELEPHONY_SERVICE);
3882 }
3883
3884 /**
3885 * Get the default url to use for the test.
3886 */
3887 public String getDefaultUrl() {
3888 // See http://go/clientsdns for usage approval
3889 String server = Settings.Global.getString(mContext.getContentResolver(),
3890 Settings.Global.CAPTIVE_PORTAL_SERVER);
3891 if (server == null) {
3892 server = "clients3.google.com";
3893 }
3894 return "http://" + server + "/generate_204";
3895 }
3896
3897 /**
3898 * Detect if its possible to connect to the http url. DNS based detection techniques
3899 * do not work at all hotspots. The best way to check is to perform a request to
3900 * a known address that fetches the data we expect.
3901 */
3902 private synchronized Integer isMobileOk(Params params) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003903 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07003904 Uri orgUri = Uri.parse(params.mUrl);
3905 Random rand = new Random();
3906 mParams = params;
3907
Wink Saville54c5e162013-08-13 12:41:06 -07003908 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3909 log("isMobileOk: not mobile capable");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003910 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville54c5e162013-08-13 12:41:06 -07003911 return result;
3912 }
Wink Saville32506bc2013-06-29 21:10:57 -07003913
Wink Saville54c5e162013-08-13 12:41:06 -07003914 try {
Wink Saville32506bc2013-06-29 21:10:57 -07003915 // Continue trying to connect until time has run out
3916 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville15f12922013-08-07 11:02:57 -07003917
Wink Savilled23fa092013-08-16 17:17:28 -07003918 if (!mCs.isMobileDataStateTrackerReady()) {
3919 // Wait for MobileDataStateTracker to be ready.
3920 if (DBG) log("isMobileOk: mdst is not ready");
3921 while(SystemClock.elapsedRealtime() < endTime) {
3922 if (mCs.isMobileDataStateTrackerReady()) {
3923 // Enable fail fast as we'll do retries here and use a
3924 // hipri connection so the default connection stays active.
3925 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
3926 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3927 break;
3928 }
3929 sleep(1);
3930 }
3931 }
3932
3933 log("isMobileOk: start hipri url=" + params.mUrl);
3934
Wink Saville15f12922013-08-07 11:02:57 -07003935 // First wait until we can start using hipri
3936 Binder binder = new Binder();
3937 while(SystemClock.elapsedRealtime() < endTime) {
3938 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3939 Phone.FEATURE_ENABLE_HIPRI, binder);
3940 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3941 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3942 log("isMobileOk: hipri started");
3943 break;
3944 }
3945 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003946 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville15f12922013-08-07 11:02:57 -07003947 sleep(1);
3948 }
3949
3950 // Continue trying to connect until time has run out
Wink Saville32506bc2013-06-29 21:10:57 -07003951 while(SystemClock.elapsedRealtime() < endTime) {
3952 try {
3953 // Wait for hipri to connect.
3954 // TODO: Don't poll and handle situation where hipri fails
3955 // because default is retrying. See b/9569540
3956 NetworkInfo.State state = mCs
3957 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3958 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003959 if (true/*VDBG*/) {
Wink Saville15f12922013-08-07 11:02:57 -07003960 log("isMobileOk: not connected ni=" +
Wink Saville32506bc2013-06-29 21:10:57 -07003961 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville15f12922013-08-07 11:02:57 -07003962 }
Wink Saville32506bc2013-06-29 21:10:57 -07003963 sleep(1);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003964 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07003965 continue;
3966 }
3967
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003968 // Hipri has started check if this is a provisioning url
3969 MobileDataStateTracker mdst = (MobileDataStateTracker)
3970 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3971 if (mdst.isProvisioningNetwork()) {
3972 if (DBG) log("isMobileOk: isProvisioningNetwork is true, no TCP conn");
3973 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
3974 return result;
3975 } else {
3976 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
3977 }
3978
Wink Saville32506bc2013-06-29 21:10:57 -07003979 // Get of the addresses associated with the url host. We need to use the
3980 // address otherwise HttpURLConnection object will use the name to get
3981 // the addresses and is will try every address but that will bypass the
3982 // route to host we setup and the connection could succeed as the default
3983 // interface might be connected to the internet via wifi or other interface.
3984 InetAddress[] addresses;
3985 try {
3986 addresses = InetAddress.getAllByName(orgUri.getHost());
3987 } catch (UnknownHostException e) {
3988 log("isMobileOk: UnknownHostException");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003989 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville32506bc2013-06-29 21:10:57 -07003990 return result;
3991 }
3992 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3993
3994 // Get the type of addresses supported by this link
3995 LinkProperties lp = mCs.getLinkProperties(
3996 ConnectivityManager.TYPE_MOBILE_HIPRI);
3997 boolean linkHasIpv4 = hasIPv4Address(lp);
3998 boolean linkHasIpv6 = hasIPv6Address(lp);
3999 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4000 + " linkHasIpv6=" + linkHasIpv6);
4001
4002 // Loop through at most 3 valid addresses or all of the address or until
4003 // we run out of time
4004 int loops = Math.min(3, addresses.length);
4005 for(int validAddr=0, addrTried=0;
4006 (validAddr < loops) && (addrTried < addresses.length)
4007 && (SystemClock.elapsedRealtime() < endTime);
4008 addrTried ++) {
4009
4010 // Choose the address at random but make sure its type is supported
4011 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4012 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4013 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4014 // Valid address, so use it
4015 validAddr += 1;
4016 } else {
4017 // Invalid address so try next address
4018 continue;
4019 }
4020
4021 // Make a route to host so we check the specific interface.
4022 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4023 hostAddr.getAddress())) {
4024 // Wait a short time to be sure the route is established ??
4025 log("isMobileOk:"
4026 + " wait to establish route to hostAddr=" + hostAddr);
4027 sleep(3);
4028 } else {
4029 log("isMobileOk:"
4030 + " could not establish route to hostAddr=" + hostAddr);
4031 continue;
4032 }
4033
4034 // Rewrite the url to have numeric address to use the specific route.
4035 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4036 // is used which is useless in this case.
4037 URL newUrl = new URL(orgUri.getScheme() + "://"
4038 + hostAddr.getHostAddress() + orgUri.getPath());
4039 log("isMobileOk: newUrl=" + newUrl);
4040
4041 HttpURLConnection urlConn = null;
4042 try {
4043 // Open the connection set the request header and get the response
4044 urlConn = (HttpURLConnection) newUrl.openConnection(
4045 java.net.Proxy.NO_PROXY);
4046 urlConn.setInstanceFollowRedirects(false);
4047 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4048 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4049 urlConn.setUseCaches(false);
4050 urlConn.setAllowUserInteraction(false);
4051 urlConn.setRequestProperty("Connection", "close");
4052 int responseCode = urlConn.getResponseCode();
4053 if (responseCode == 204) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004054 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville32506bc2013-06-29 21:10:57 -07004055 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004056 result = CMP_RESULT_CODE_REDIRECTED;
Wink Saville32506bc2013-06-29 21:10:57 -07004057 }
4058 log("isMobileOk: connected responseCode=" + responseCode);
4059 urlConn.disconnect();
4060 urlConn = null;
4061 return result;
4062 } catch (Exception e) {
4063 log("isMobileOk: HttpURLConnection Exception e=" + e);
4064 if (urlConn != null) {
4065 urlConn.disconnect();
4066 urlConn = null;
4067 }
4068 }
4069 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004070 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004071 log("isMobileOk: loops|timed out");
4072 return result;
4073 } catch (Exception e) {
4074 log("isMobileOk: Exception e=" + e);
4075 continue;
4076 }
4077 }
4078 log("isMobileOk: timed out");
4079 } finally {
4080 log("isMobileOk: F stop hipri");
4081 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4082 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4083 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004084
4085 // Wait for hipri to disconnect.
4086 long endTime = SystemClock.elapsedRealtime() + 5000;
4087
4088 while(SystemClock.elapsedRealtime() < endTime) {
4089 NetworkInfo.State state = mCs
4090 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4091 if (state != NetworkInfo.State.DISCONNECTED) {
4092 if (VDBG) {
4093 log("isMobileOk: connected ni=" +
4094 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4095 }
4096 sleep(1);
4097 continue;
4098 }
4099 }
4100
Wink Saville32506bc2013-06-29 21:10:57 -07004101 log("isMobileOk: X result=" + result);
4102 }
4103 return result;
4104 }
4105
4106 @Override
4107 protected Integer doInBackground(Params... params) {
4108 return isMobileOk(params[0]);
4109 }
4110
4111 @Override
4112 protected void onPostExecute(Integer result) {
4113 log("onPostExecute: result=" + result);
4114 if ((mParams != null) && (mParams.mCb != null)) {
4115 mParams.mCb.onComplete(result);
4116 }
4117 }
4118
4119 private String inetAddressesToString(InetAddress[] addresses) {
4120 StringBuffer sb = new StringBuffer();
4121 boolean firstTime = true;
4122 for(InetAddress addr : addresses) {
4123 if (firstTime) {
4124 firstTime = false;
4125 } else {
4126 sb.append(",");
4127 }
4128 sb.append(addr);
4129 }
4130 return sb.toString();
4131 }
4132
4133 private void printNetworkInfo() {
4134 boolean hasIccCard = mTm.hasIccCard();
4135 int simState = mTm.getSimState();
4136 log("hasIccCard=" + hasIccCard
4137 + " simState=" + simState);
4138 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4139 if (ni != null) {
4140 log("ni.length=" + ni.length);
4141 for (NetworkInfo netInfo: ni) {
4142 log("netInfo=" + netInfo.toString());
4143 }
4144 } else {
4145 log("no network info ni=null");
4146 }
4147 }
4148
4149 /**
4150 * Sleep for a few seconds then return.
4151 * @param seconds
4152 */
4153 private static void sleep(int seconds) {
4154 try {
4155 Thread.sleep(seconds * 1000);
4156 } catch (InterruptedException e) {
4157 e.printStackTrace();
4158 }
4159 }
4160
4161 public boolean hasIPv4Address(LinkProperties lp) {
4162 return lp.hasIPv4Address();
4163 }
4164
4165 // Not implemented in LinkProperties, do it here.
4166 public boolean hasIPv6Address(LinkProperties lp) {
4167 for (LinkAddress address : lp.getLinkAddresses()) {
4168 if (address.getAddress() instanceof Inet6Address) {
4169 return true;
4170 }
4171 }
4172 return false;
4173 }
4174
4175 private void log(String s) {
4176 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4177 }
4178 }
4179
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004180 // TODO: Move to ConnectivityManager and make public?
4181 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4182 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville32506bc2013-06-29 21:10:57 -07004183
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004184 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4185 @Override
4186 public void onReceive(Context context, Intent intent) {
4187 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4188 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4189 }
4190 }
4191 };
4192
4193 private void handleMobileProvisioningAction(String url) {
4194 // Notication mark notification as not visible
4195 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
4196
4197 // If provisioning network handle as a special case,
4198 // otherwise launch browser with the intent directly.
4199 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Savilleb1a32022013-09-05 12:02:25 -07004200 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004201 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4202 MobileDataStateTracker mdst = (MobileDataStateTracker)
4203 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4204 mdst.enableMobileProvisioning(url);
4205 } else {
4206 if (DBG) log("handleMobileProvisioningAction: on default network");
4207 Intent newIntent =
4208 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4209 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4210 Intent.FLAG_ACTIVITY_NEW_TASK);
4211 try {
4212 mContext.startActivity(newIntent);
4213 } catch (ActivityNotFoundException e) {
4214 loge("handleMobileProvisioningAction: startActivity failed" + e);
4215 }
4216 }
4217 }
4218
4219 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4220 private volatile boolean mIsNotificationVisible = false;
4221
4222 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4223 String url) {
4224 if (DBG) {
4225 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4226 + " extraInfo=" + extraInfo + " url=" + url);
4227 }
Wink Saville32506bc2013-06-29 21:10:57 -07004228
4229 Resources r = Resources.getSystem();
4230 NotificationManager notificationManager = (NotificationManager) mContext
4231 .getSystemService(Context.NOTIFICATION_SERVICE);
4232
4233 if (visible) {
4234 CharSequence title;
4235 CharSequence details;
4236 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004237 Intent intent;
4238 Notification notification = new Notification();
4239 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004240 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004241 title = r.getString(R.string.wifi_available_sign_in, 0);
4242 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004243 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004244 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004245 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4246 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4247 Intent.FLAG_ACTIVITY_NEW_TASK);
4248 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004249 break;
4250 case ConnectivityManager.TYPE_MOBILE:
4251 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004252 title = r.getString(R.string.network_available_sign_in, 0);
4253 // TODO: Change this to pull from NetworkInfo once a printable
4254 // name has been added to it
4255 details = mTelephonyManager.getNetworkOperatorName();
4256 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004257 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4258 intent.putExtra("EXTRA_URL", url);
4259 intent.setFlags(0);
4260 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004261 break;
4262 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004263 title = r.getString(R.string.network_available_sign_in, 0);
4264 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004265 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004266 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004267 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4268 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4269 Intent.FLAG_ACTIVITY_NEW_TASK);
4270 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004271 break;
4272 }
4273
Wink Saville32506bc2013-06-29 21:10:57 -07004274 notification.when = 0;
4275 notification.icon = icon;
4276 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004277 notification.tickerText = title;
4278 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4279
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004280 try {
4281 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4282 } catch (NullPointerException npe) {
4283 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4284 npe.printStackTrace();
4285 }
Wink Saville32506bc2013-06-29 21:10:57 -07004286 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004287 try {
4288 notificationManager.cancel(NOTIFICATION_ID, 1);
4289 } catch (NullPointerException npe) {
4290 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4291 npe.printStackTrace();
4292 }
Wink Saville32506bc2013-06-29 21:10:57 -07004293 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004294 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004295 }
4296
Robert Greenwalt39d56012013-07-16 12:06:09 -07004297 /** Location to an updatable file listing carrier provisioning urls.
4298 * An example:
4299 *
4300 * <?xml version="1.0" encoding="utf-8"?>
4301 * <provisioningUrls>
4302 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4303 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4304 * </provisioningUrls>
4305 */
4306 private static final String PROVISIONING_URL_PATH =
4307 "/data/misc/radio/provisioning_urls.xml";
4308 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004309
Robert Greenwalt39d56012013-07-16 12:06:09 -07004310 /** XML tag for root element. */
4311 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4312 /** XML tag for individual url */
4313 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4314 /** XML tag for redirected url */
4315 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4316 /** XML attribute for mcc */
4317 private static final String ATTR_MCC = "mcc";
4318 /** XML attribute for mnc */
4319 private static final String ATTR_MNC = "mnc";
4320
4321 private static final int REDIRECTED_PROVISIONING = 1;
4322 private static final int PROVISIONING = 2;
4323
4324 private String getProvisioningUrlBaseFromFile(int type) {
4325 FileReader fileReader = null;
4326 XmlPullParser parser = null;
4327 Configuration config = mContext.getResources().getConfiguration();
4328 String tagType;
4329
4330 switch (type) {
4331 case PROVISIONING:
4332 tagType = TAG_PROVISIONING_URL;
4333 break;
4334 case REDIRECTED_PROVISIONING:
4335 tagType = TAG_REDIRECTED_URL;
4336 break;
4337 default:
4338 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4339 type);
4340 }
4341
4342 try {
4343 fileReader = new FileReader(mProvisioningUrlFile);
4344 parser = Xml.newPullParser();
4345 parser.setInput(fileReader);
4346 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4347
4348 while (true) {
4349 XmlUtils.nextElement(parser);
4350
4351 String element = parser.getName();
4352 if (element == null) break;
4353
4354 if (element.equals(tagType)) {
4355 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4356 try {
4357 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4358 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4359 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4360 parser.next();
4361 if (parser.getEventType() == XmlPullParser.TEXT) {
4362 return parser.getText();
4363 }
4364 }
4365 }
4366 } catch (NumberFormatException e) {
4367 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4368 }
4369 }
4370 }
4371 return null;
4372 } catch (FileNotFoundException e) {
4373 loge("Carrier Provisioning Urls file not found");
4374 } catch (XmlPullParserException e) {
4375 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4376 } catch (IOException e) {
4377 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4378 } finally {
4379 if (fileReader != null) {
4380 try {
4381 fileReader.close();
4382 } catch (IOException e) {}
4383 }
4384 }
4385 return null;
4386 }
4387
Wink Saville8432cf42013-07-20 20:31:59 -07004388 @Override
4389 public String getMobileRedirectedProvisioningUrl() {
4390 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004391 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4392 if (TextUtils.isEmpty(url)) {
4393 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4394 }
4395 return url;
4396 }
4397
Wink Saville8432cf42013-07-20 20:31:59 -07004398 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004399 public String getMobileProvisioningUrl() {
4400 enforceConnectivityInternalPermission();
4401 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4402 if (TextUtils.isEmpty(url)) {
4403 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004404 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004405 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004406 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004407 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004408 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004409 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004410 String phoneNumber = mTelephonyManager.getLine1Number();
4411 if (TextUtils.isEmpty(phoneNumber)) {
4412 phoneNumber = "0000000000";
4413 }
Wink Saville32506bc2013-06-29 21:10:57 -07004414 url = String.format(url,
4415 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4416 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004417 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004418 }
4419
Wink Saville32506bc2013-06-29 21:10:57 -07004420 return url;
4421 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004422
4423 @Override
4424 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4425 String extraInfo, String url) {
4426 enforceConnectivityInternalPermission();
4427 setProvNotificationVisible(visible, networkType, extraInfo, url);
4428 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004429}