blob: ee23b13d3f191fed7f22970d2fef8006dd997080 [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()) {
893 if (ni.getDetailedState()
894 == NetworkInfo.DetailedState.CONNECTED_TO_PROVISIONING_NETWORK) {
895 provNi = ni;
896 break;
897 }
898 }
899 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
900 return provNi;
901 }
902
903 /**
904 * Find the first Provisioning network or the ActiveDefaultNetwork
905 * if there is no Provisioning network
906 *
907 * @return NetworkInfo or null if none.
908 */
909 @Override
910 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
911 enforceAccessPermission();
912
913 NetworkInfo provNi = getProvisioningNetworkInfo();
914 if (provNi == null) {
915 final int uid = Binder.getCallingUid();
916 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
917 }
918 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
919 return provNi;
920 }
921
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700922 public NetworkInfo getActiveNetworkInfoUnfiltered() {
923 enforceAccessPermission();
924 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
925 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
926 if (tracker != null) {
927 return tracker.getNetworkInfo();
928 }
929 }
930 return null;
931 }
932
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700933 @Override
934 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
935 enforceConnectivityInternalPermission();
936 return getNetworkInfo(mActiveDefaultNetwork, uid);
937 }
938
939 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800940 public NetworkInfo getNetworkInfo(int networkType) {
941 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700942 final int uid = Binder.getCallingUid();
943 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800944 }
945
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700946 private NetworkInfo getNetworkInfo(int networkType, int uid) {
947 NetworkInfo info = null;
948 if (isNetworkTypeValid(networkType)) {
949 final NetworkStateTracker tracker = mNetTrackers[networkType];
950 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700951 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 }
953 }
954 return info;
955 }
956
957 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800958 public NetworkInfo[] getAllNetworkInfo() {
959 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700960 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700961 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700962 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700963 for (NetworkStateTracker tracker : mNetTrackers) {
964 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700965 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700966 }
967 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800968 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700969 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800970 }
971
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700972 @Override
973 public boolean isNetworkSupported(int networkType) {
974 enforceAccessPermission();
975 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
976 }
977
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700978 /**
979 * Return LinkProperties for the active (i.e., connected) default
980 * network interface. It is assumed that at most one default network
981 * is active at a time. If more than one is active, it is indeterminate
982 * which will be returned.
983 * @return the ip properties for the active network, or {@code null} if
984 * none is active
985 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700986 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700987 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700988 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700989 }
990
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700991 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700992 public LinkProperties getLinkProperties(int networkType) {
993 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700994 if (isNetworkTypeValid(networkType)) {
995 final NetworkStateTracker tracker = mNetTrackers[networkType];
996 if (tracker != null) {
997 return tracker.getLinkProperties();
998 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700999 }
1000 return null;
1001 }
1002
Jeff Sharkey21062e72011-05-28 20:56:34 -07001003 @Override
1004 public NetworkState[] getAllNetworkState() {
1005 enforceAccessPermission();
1006 final int uid = Binder.getCallingUid();
1007 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001008 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001009 for (NetworkStateTracker tracker : mNetTrackers) {
1010 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001011 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001012 result.add(new NetworkState(
1013 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1014 }
1015 }
1016 }
1017 return result.toArray(new NetworkState[result.size()]);
1018 }
1019
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001020 private NetworkState getNetworkStateUnchecked(int networkType) {
1021 if (isNetworkTypeValid(networkType)) {
1022 final NetworkStateTracker tracker = mNetTrackers[networkType];
1023 if (tracker != null) {
1024 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1025 tracker.getLinkCapabilities());
1026 }
1027 }
1028 return null;
1029 }
1030
1031 @Override
1032 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1033 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001034
1035 final long token = Binder.clearCallingIdentity();
1036 try {
1037 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1038 if (state != null) {
1039 try {
1040 return mPolicyManager.getNetworkQuotaInfo(state);
1041 } catch (RemoteException e) {
1042 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001043 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001044 return null;
1045 } finally {
1046 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001047 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001048 }
1049
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001050 @Override
1051 public boolean isActiveNetworkMetered() {
1052 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001053 final long token = Binder.clearCallingIdentity();
1054 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001055 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001056 } finally {
1057 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001058 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001059 }
1060
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001061 private boolean isNetworkMeteredUnchecked(int networkType) {
1062 final NetworkState state = getNetworkStateUnchecked(networkType);
1063 if (state != null) {
1064 try {
1065 return mPolicyManager.isNetworkMetered(state);
1066 } catch (RemoteException e) {
1067 }
1068 }
1069 return false;
1070 }
1071
The Android Open Source Project28527d22009-03-03 19:31:44 -08001072 public boolean setRadios(boolean turnOn) {
1073 boolean result = true;
1074 enforceChangePermission();
1075 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001076 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001077 }
1078 return result;
1079 }
1080
1081 public boolean setRadio(int netType, boolean turnOn) {
1082 enforceChangePermission();
1083 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1084 return false;
1085 }
1086 NetworkStateTracker tracker = mNetTrackers[netType];
1087 return tracker != null && tracker.setRadio(turnOn);
1088 }
1089
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001090 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1091 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001092 public void interfaceClassDataActivityChanged(String label, boolean active) {
1093 int deviceType = Integer.parseInt(label);
1094 sendDataActivityBroadcast(deviceType, active);
1095 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001096 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001097
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001098 /**
1099 * Used to notice when the calling process dies so we can self-expire
1100 *
1101 * Also used to know if the process has cleaned up after itself when
1102 * our auto-expire timer goes off. The timer has a link to an object.
1103 *
1104 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001105 private class FeatureUser implements IBinder.DeathRecipient {
1106 int mNetworkType;
1107 String mFeature;
1108 IBinder mBinder;
1109 int mPid;
1110 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001111 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001112
1113 FeatureUser(int type, String feature, IBinder binder) {
1114 super();
1115 mNetworkType = type;
1116 mFeature = feature;
1117 mBinder = binder;
1118 mPid = getCallingPid();
1119 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001120 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001121
Robert Greenwalt2034b912009-08-12 16:08:25 -07001122 try {
1123 mBinder.linkToDeath(this, 0);
1124 } catch (RemoteException e) {
1125 binderDied();
1126 }
1127 }
1128
1129 void unlinkDeathRecipient() {
1130 mBinder.unlinkToDeath(this, 0);
1131 }
1132
1133 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001134 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001135 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1136 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001137 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001138 }
1139
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001140 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001141 if (VDBG) {
1142 log("ConnectivityService FeatureUser expire(" +
1143 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1144 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1145 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001146 stopUsingNetworkFeature(this, false);
1147 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001148
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001149 public boolean isSameUser(FeatureUser u) {
1150 if (u == null) return false;
1151
1152 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1153 }
1154
1155 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1156 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1157 TextUtils.equals(mFeature, feature)) {
1158 return true;
1159 }
1160 return false;
1161 }
1162
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001163 public String toString() {
1164 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1165 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1166 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001167 }
1168
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001169 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001170 public int startUsingNetworkFeature(int networkType, String feature,
1171 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001172 long startTime = 0;
1173 if (DBG) {
1174 startTime = SystemClock.elapsedRealtime();
1175 }
Wink Savillea7d56572011-09-21 11:05:43 -07001176 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001177 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1178 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001179 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001180 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001181 try {
1182 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1183 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001184 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001185 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001186
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001187 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001188
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001189 // TODO - move this into individual networktrackers
1190 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001191
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001192 if (mLockdownEnabled) {
1193 // Since carrier APNs usually aren't available from VPN
1194 // endpoint, mark them as unavailable.
1195 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1196 }
1197
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001198 if (mProtectedNetworks.contains(usedNetworkType)) {
1199 enforceConnectivityInternalPermission();
1200 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001201
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001202 // if UID is restricted, don't allow them to bring up metered APNs
1203 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1204 final int uidRules;
1205 synchronized (mRulesLock) {
1206 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1207 }
1208 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001209 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001210 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001211
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001212 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1213 if (network != null) {
1214 Integer currentPid = new Integer(getCallingPid());
1215 if (usedNetworkType != networkType) {
1216 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001217
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001218 if (ni.isAvailable() == false) {
1219 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1220 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001221 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001222 } else {
1223 // else make the attempt anyway - probably giving REQUEST_STARTED below
1224 if (DBG) {
1225 log("special network not available, but try anyway ni=" +
1226 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001227 }
1228 }
1229 }
1230
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001231 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001232
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001233 synchronized(this) {
1234 boolean addToList = true;
1235 if (restoreTimer < 0) {
1236 // In case there is no timer is specified for the feature,
1237 // make sure we don't add duplicate entry with the same request.
1238 for (FeatureUser u : mFeatureUsers) {
1239 if (u.isSameUser(f)) {
1240 // Duplicate user is found. Do not add.
1241 addToList = false;
1242 break;
1243 }
1244 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001245 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001246
1247 if (addToList) mFeatureUsers.add(f);
1248 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1249 // this gets used for per-pid dns when connected
1250 mNetRequestersPids[usedNetworkType].add(currentPid);
1251 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001252 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001253
1254 if (restoreTimer >= 0) {
1255 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1256 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1257 }
1258
1259 if ((ni.isConnectedOrConnecting() == true) &&
1260 !network.isTeardownRequested()) {
1261 if (ni.isConnected() == true) {
1262 final long token = Binder.clearCallingIdentity();
1263 try {
1264 // add the pid-specific dns
1265 handleDnsConfigurationChange(usedNetworkType);
1266 if (VDBG) log("special network already active");
1267 } finally {
1268 Binder.restoreCallingIdentity(token);
1269 }
Wink Saville64e3f782012-07-10 12:37:54 -07001270 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001271 }
1272 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001273 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001274 }
1275
1276 // check if the radio in play can make another contact
1277 // assume if cannot for now
1278
1279 if (DBG) {
1280 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1281 feature);
1282 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001283 if (network.reconnect()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001284 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001285 return PhoneConstants.APN_REQUEST_STARTED;
1286 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001287 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001288 return PhoneConstants.APN_REQUEST_FAILED;
1289 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001290 } else {
1291 // need to remember this unsupported request so we respond appropriately on stop
1292 synchronized(this) {
1293 mFeatureUsers.add(f);
1294 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1295 // this gets used for per-pid dns when connected
1296 mNetRequestersPids[usedNetworkType].add(currentPid);
1297 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001298 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001299 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001300 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001301 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001302 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001303 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001304 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001305 } finally {
1306 if (DBG) {
1307 final long execTime = SystemClock.elapsedRealtime() - startTime;
1308 if (execTime > 250) {
1309 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1310 } else {
1311 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1312 }
1313 }
1314 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001315 }
1316
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001317 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001318 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001319 enforceChangePermission();
1320
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001321 int pid = getCallingPid();
1322 int uid = getCallingUid();
1323
1324 FeatureUser u = null;
1325 boolean found = false;
1326
1327 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001328 for (FeatureUser x : mFeatureUsers) {
1329 if (x.isSameUser(pid, uid, networkType, feature)) {
1330 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001331 found = true;
1332 break;
1333 }
1334 }
1335 }
1336 if (found && u != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001337 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001338 // stop regardless of how many other time this proc had called start
1339 return stopUsingNetworkFeature(u, true);
1340 } else {
1341 // none found!
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001342 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001343 return 1;
1344 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001345 }
1346
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001347 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1348 int networkType = u.mNetworkType;
1349 String feature = u.mFeature;
1350 int pid = u.mPid;
1351 int uid = u.mUid;
1352
1353 NetworkStateTracker tracker = null;
1354 boolean callTeardown = false; // used to carry our decision outside of sync block
1355
Wink Savillea7d56572011-09-21 11:05:43 -07001356 if (VDBG) {
1357 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001358 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001359
The Android Open Source Project28527d22009-03-03 19:31:44 -08001360 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001361 if (DBG) {
1362 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1363 ", net is invalid");
1364 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001365 return -1;
1366 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001367
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001368 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1369 // sync block
1370 synchronized(this) {
1371 // check if this process still has an outstanding start request
1372 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001373 if (VDBG) {
1374 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1375 ", ignoring");
1376 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001377 return 1;
1378 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001379 u.unlinkDeathRecipient();
1380 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1381 // If we care about duplicate requests, check for that here.
1382 //
1383 // This is done to support the extension of a request - the app
1384 // can request we start the network feature again and renew the
1385 // auto-shutoff delay. Normal "stop" calls from the app though
1386 // do not pay attention to duplicate requests - in effect the
1387 // API does not refcount and a single stop will counter multiple starts.
1388 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001389 for (FeatureUser x : mFeatureUsers) {
1390 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001391 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001392 return 1;
1393 }
1394 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001395 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001396
repo syncf5de5572011-07-29 23:55:49 -07001397 // TODO - move to individual network trackers
1398 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1399
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001400 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001401 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001402 if (DBG) {
1403 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1404 " no known tracker for used net type " + usedNetworkType);
1405 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001406 return -1;
1407 }
1408 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001409 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001410 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001411
1412 final long token = Binder.clearCallingIdentity();
1413 try {
1414 reassessPidDns(pid, true);
1415 } finally {
1416 Binder.restoreCallingIdentity(token);
1417 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001418 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001419 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001420 if (VDBG) {
1421 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1422 " others still using it");
1423 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001424 return 1;
1425 }
1426 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001427 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001428 if (DBG) {
1429 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1430 " not a known feature - dropping");
1431 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001432 }
1433 }
Wink Savillea7d56572011-09-21 11:05:43 -07001434
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001435 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001436 if (DBG) {
1437 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1438 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001439 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001440 return 1;
1441 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001442 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001443 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001444 }
1445
1446 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001447 * @deprecated use requestRouteToHostAddress instead
1448 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001449 * Ensure that a network route exists to deliver traffic to the specified
1450 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001451 * @param networkType the type of the network over which traffic to the
1452 * specified host is to be routed
1453 * @param hostAddress the IP address of the host to which the route is
1454 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001455 * @return {@code true} on success, {@code false} on failure
1456 */
1457 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001458 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1459
1460 if (inetAddress == null) {
1461 return false;
1462 }
1463
1464 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1465 }
1466
1467 /**
1468 * Ensure that a network route exists to deliver traffic to the specified
1469 * host via the specified network interface.
1470 * @param networkType the type of the network over which traffic to the
1471 * specified host is to be routed
1472 * @param hostAddress the IP address of the host to which the route is
1473 * desired
1474 * @return {@code true} on success, {@code false} on failure
1475 */
1476 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001478 if (mProtectedNetworks.contains(networkType)) {
1479 enforceConnectivityInternalPermission();
1480 }
1481
The Android Open Source Project28527d22009-03-03 19:31:44 -08001482 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001483 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001484 return false;
1485 }
1486 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001487 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001488
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001489 if (tracker == null || (netState != DetailedState.CONNECTED &&
1490 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001491 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001492 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001493 log("requestRouteToHostAddress on down network "
1494 + "(" + networkType + ") - dropped"
1495 + " tracker=" + tracker
1496 + " netState=" + netState
1497 + " isTeardownRequested="
1498 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001499 }
1500 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001501 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001502 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001503 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001504 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001505 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001506 boolean ok = addRouteToAddress(lp, addr);
1507 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1508 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001509 } catch (UnknownHostException e) {
1510 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1511 } finally {
1512 Binder.restoreCallingIdentity(token);
1513 }
Wink Saville32506bc2013-06-29 21:10:57 -07001514 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001515 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001516 }
1517
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001518 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001519 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001520 }
1521
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001522 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001523 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001524 }
1525
Robert Greenwalt98107422011-07-22 11:55:33 -07001526 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001527 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001528 }
1529
1530 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001531 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001532 }
1533
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001534 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1535 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001536 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001537 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001538 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001539 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001540 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001541 if (bestRoute.getGateway().equals(addr)) {
1542 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001543 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001544 } else {
1545 // if we will connect to this through another route, add a direct route
1546 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001547 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001548 }
1549 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001550 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001551 }
1552
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001553 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1554 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001555 if ((lp == null) || (r == null)) {
1556 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001557 return false;
1558 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001559
1560 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001561 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001562 return false;
1563 }
1564
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001565 String ifaceName = r.getInterface();
1566 if(ifaceName == null) {
1567 loge("Error modifying route - no interface name");
1568 return false;
1569 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001570 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001571 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001572 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001573 if (bestRoute.getGateway().equals(r.getGateway())) {
1574 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001575 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001576 } else {
1577 // if we will connect to our gateway through another route, add a direct
1578 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001579 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1580 bestRoute.getGateway(),
1581 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001582 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001583 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001584 }
1585 }
1586 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001587 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001588 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001589 if (toDefaultTable) {
1590 mAddedRoutes.add(r); // only track default table - only one apps can effect
1591 mNetd.addRoute(ifaceName, r);
1592 } else {
1593 mNetd.addSecondaryRoute(ifaceName, r);
1594 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001595 } catch (Exception e) {
1596 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001597 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001598 return false;
1599 }
1600 } else {
1601 // if we remove this one and there are no more like it, then refcount==0 and
1602 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001603 if (toDefaultTable) {
1604 mAddedRoutes.remove(r);
1605 if (mAddedRoutes.contains(r) == false) {
1606 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1607 try {
1608 mNetd.removeRoute(ifaceName, r);
1609 } catch (Exception e) {
1610 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001611 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001612 return false;
1613 }
1614 } else {
1615 if (VDBG) log("not removing " + r + " as it's still in use");
1616 }
1617 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001618 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001619 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001620 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001621 } catch (Exception e) {
1622 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001623 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001624 return false;
1625 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001626 }
1627 }
1628 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001629 }
1630
1631 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001632 * @see ConnectivityManager#getMobileDataEnabled()
1633 */
1634 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001635 // TODO: This detail should probably be in DataConnectionTracker's
1636 // which is where we store the value and maybe make this
1637 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001638 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001639 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1640 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001641 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001642 return retVal;
1643 }
1644
Robert Greenwalt34848c02011-03-25 13:09:25 -07001645 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001646 enforceConnectivityInternalPermission();
1647
Robert Greenwalt34848c02011-03-25 13:09:25 -07001648 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1649 (met ? ENABLED : DISABLED), networkType));
1650 }
1651
1652 private void handleSetDependencyMet(int networkType, boolean met) {
1653 if (mNetTrackers[networkType] != null) {
1654 if (DBG) {
1655 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1656 }
1657 mNetTrackers[networkType].setDependencyMet(met);
1658 }
1659 }
1660
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001661 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1662 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001663 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001664 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001665 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001666 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001667 }
1668
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001669 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001670 // skip update when we've already applied rules
1671 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1672 if (oldRules == uidRules) return;
1673
1674 mUidRules.put(uid, uidRules);
1675 }
1676
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001677 // TODO: notify UID when it has requested targeted updates
1678 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001679
1680 @Override
1681 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001682 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001683 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001684 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001685 }
1686
1687 synchronized (mRulesLock) {
1688 mMeteredIfaces.clear();
1689 for (String iface : meteredIfaces) {
1690 mMeteredIfaces.add(iface);
1691 }
1692 }
1693 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001694
1695 @Override
1696 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1697 // caller is NPMS, since we only register with them
1698 if (LOGD_RULES) {
1699 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1700 }
1701
1702 // kick off connectivity change broadcast for active network, since
1703 // global background policy change is radical.
1704 final int networkType = mActiveDefaultNetwork;
1705 if (isNetworkTypeValid(networkType)) {
1706 final NetworkStateTracker tracker = mNetTrackers[networkType];
1707 if (tracker != null) {
1708 final NetworkInfo info = tracker.getNetworkInfo();
1709 if (info != null && info.isConnected()) {
1710 sendConnectedBroadcast(info);
1711 }
1712 }
1713 }
1714 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001715 };
1716
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001717 /**
1718 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1719 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001720 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001721 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001722 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001723
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001725 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001726 }
1727
1728 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001729 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001730 if (VDBG) {
1731 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001732 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001733 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1734 }
tk.mun5eee1042012-01-06 10:43:52 +09001735 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1736 if (VDBG) {
1737 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1738 }
1739 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1740 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001741 }
1742
1743 @Override
1744 public void setPolicyDataEnable(int networkType, boolean enabled) {
1745 // only someone like NPMS should only be calling us
1746 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1747
1748 mHandler.sendMessage(mHandler.obtainMessage(
1749 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1750 }
1751
1752 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1753 if (isNetworkTypeValid(networkType)) {
1754 final NetworkStateTracker tracker = mNetTrackers[networkType];
1755 if (tracker != null) {
1756 tracker.setPolicyDataEnable(enabled);
1757 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001758 }
1759 }
1760
The Android Open Source Project28527d22009-03-03 19:31:44 -08001761 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001762 mContext.enforceCallingOrSelfPermission(
1763 android.Manifest.permission.ACCESS_NETWORK_STATE,
1764 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001765 }
1766
1767 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001768 mContext.enforceCallingOrSelfPermission(
1769 android.Manifest.permission.CHANGE_NETWORK_STATE,
1770 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001771 }
1772
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001773 // TODO Make this a special check when it goes public
1774 private void enforceTetherChangePermission() {
1775 mContext.enforceCallingOrSelfPermission(
1776 android.Manifest.permission.CHANGE_NETWORK_STATE,
1777 "ConnectivityService");
1778 }
1779
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001780 private void enforceTetherAccessPermission() {
1781 mContext.enforceCallingOrSelfPermission(
1782 android.Manifest.permission.ACCESS_NETWORK_STATE,
1783 "ConnectivityService");
1784 }
1785
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001786 private void enforceConnectivityInternalPermission() {
1787 mContext.enforceCallingOrSelfPermission(
1788 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1789 "ConnectivityService");
1790 }
1791
The Android Open Source Project28527d22009-03-03 19:31:44 -08001792 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001793 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1794 * network, we ignore it. If it is for the active network, we send out a
1795 * broadcast. But first, we check whether it might be possible to connect
1796 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001797 * @param info the {@code NetworkInfo} for the network
1798 */
1799 private void handleDisconnect(NetworkInfo info) {
1800
Robert Greenwalt2034b912009-08-12 16:08:25 -07001801 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001802
Robert Greenwalt2034b912009-08-12 16:08:25 -07001803 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001804
1805 // Remove idletimer previously setup in {@code handleConnect}
1806 removeDataActivityTracking(prevNetType);
1807
The Android Open Source Project28527d22009-03-03 19:31:44 -08001808 /*
1809 * If the disconnected network is not the active one, then don't report
1810 * this as a loss of connectivity. What probably happened is that we're
1811 * getting the disconnect for a network that we explicitly disabled
1812 * in accordance with network preference policies.
1813 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001814 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001815 List<Integer> pids = mNetRequestersPids[prevNetType];
1816 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001817 // will remove them because the net's no longer connected
1818 // need to do this now as only now do we know the pids and
1819 // can properly null things that are no longer referenced.
1820 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001821 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001822 }
1823
The Android Open Source Project28527d22009-03-03 19:31:44 -08001824 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001825 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001826 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001827 if (info.isFailover()) {
1828 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1829 info.setFailover(false);
1830 }
1831 if (info.getReason() != null) {
1832 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1833 }
1834 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001835 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1836 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001837 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001838
Robert Greenwalt34848c02011-03-25 13:09:25 -07001839 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001840 tryFailover(prevNetType);
1841 if (mActiveDefaultNetwork != -1) {
1842 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001843 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1844 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001845 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001846 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1847 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001848 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001849 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001850
1851 // Reset interface if no other connections are using the same interface
1852 boolean doReset = true;
1853 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1854 if (linkProperties != null) {
1855 String oldIface = linkProperties.getInterfaceName();
1856 if (TextUtils.isEmpty(oldIface) == false) {
1857 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1858 if (networkStateTracker == null) continue;
1859 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1860 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1861 LinkProperties l = networkStateTracker.getLinkProperties();
1862 if (l == null) continue;
1863 if (oldIface.equals(l.getInterfaceName())) {
1864 doReset = false;
1865 break;
1866 }
1867 }
1868 }
1869 }
1870 }
1871
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001872 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001873 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001874
Jeff Sharkey971cd162011-08-29 16:02:57 -07001875 final Intent immediateIntent = new Intent(intent);
1876 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1877 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001878 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001879 /*
1880 * If the failover network is already connected, then immediately send
1881 * out a followup broadcast indicating successful failover
1882 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001883 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001884 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1885 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001886 }
1887 }
1888
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001889 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001890 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001891 * If this is a default network, check if other defaults are available.
1892 * Try to reconnect on all available and let them hash it out when
1893 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001894 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001895 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001896 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001897 if (DBG) {
1898 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
1899 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001900 mActiveDefaultNetwork = -1;
1901 }
1902
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001903 // don't signal a reconnect for anything lower or equal priority than our
1904 // current connected default
1905 // TODO - don't filter by priority now - nice optimization but risky
1906// int currentPriority = -1;
1907// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001908// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001909// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001910 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001911 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001912 if (mNetConfigs[checkType] == null) continue;
1913 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001914 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001915
1916// Enabling the isAvailable() optimization caused mobile to not get
1917// selected if it was in the middle of error handling. Specifically
1918// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1919// would not be available and we wouldn't get connected to anything.
1920// So removing the isAvailable() optimization below for now. TODO: This
1921// optimization should work and we need to investigate why it doesn't work.
1922// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1923// complete before it is really complete.
1924// if (!mNetTrackers[checkType].isAvailable()) continue;
1925
Robert Greenwalt34848c02011-03-25 13:09:25 -07001926// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001927
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001928 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1929 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1930 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1931 checkInfo.setFailover(true);
1932 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001933 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001934 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001935 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001936 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001937 }
1938
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001939 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001940 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001941 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1942 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001943 }
1944
Wink Saville4f0de1e2011-08-04 15:01:58 -07001945 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001946 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1947 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001948 }
1949
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001950 private void sendInetConditionBroadcast(NetworkInfo info) {
1951 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1952 }
1953
Wink Saville4f0de1e2011-08-04 15:01:58 -07001954 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001955 if (mLockdownTracker != null) {
1956 info = mLockdownTracker.augmentNetworkInfo(info);
1957 }
1958
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001959 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001960 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001961 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001962 if (info.isFailover()) {
1963 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1964 info.setFailover(false);
1965 }
1966 if (info.getReason() != null) {
1967 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1968 }
1969 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001970 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1971 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001972 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001973 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001974 return intent;
1975 }
1976
1977 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1978 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1979 }
1980
1981 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1982 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001983 }
1984
Haoyu Baib5da5752012-06-20 14:29:57 -07001985 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1986 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1987 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1988 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001989 final long ident = Binder.clearCallingIdentity();
1990 try {
1991 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1992 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1993 } finally {
1994 Binder.restoreCallingIdentity(ident);
1995 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001996 }
1997
The Android Open Source Project28527d22009-03-03 19:31:44 -08001998 /**
1999 * Called when an attempt to fail over to another network has failed.
2000 * @param info the {@link NetworkInfo} for the failed network
2001 */
2002 private void handleConnectionFailure(NetworkInfo info) {
2003 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002004
Robert Greenwalt2034b912009-08-12 16:08:25 -07002005 String reason = info.getReason();
2006 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002007
Robert Greenwalte981bc52010-10-08 16:35:52 -07002008 String reasonText;
2009 if (reason == null) {
2010 reasonText = ".";
2011 } else {
2012 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002013 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002014 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002015
2016 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002017 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002018 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002019 if (getActiveNetworkInfo() == null) {
2020 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2021 }
2022 if (reason != null) {
2023 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2024 }
2025 if (extraInfo != null) {
2026 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2027 }
2028 if (info.isFailover()) {
2029 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2030 info.setFailover(false);
2031 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002032
Robert Greenwalt34848c02011-03-25 13:09:25 -07002033 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002034 tryFailover(info.getType());
2035 if (mActiveDefaultNetwork != -1) {
2036 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002037 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2038 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002039 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002040 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2041 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002042 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002043
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002044 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002045
2046 final Intent immediateIntent = new Intent(intent);
2047 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2048 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002049 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002050 /*
2051 * If the failover network is already connected, then immediately send
2052 * out a followup broadcast indicating successful failover
2053 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002054 if (mActiveDefaultNetwork != -1) {
2055 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002056 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002057 }
2058
2059 private void sendStickyBroadcast(Intent intent) {
2060 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002061 if (!mSystemReady) {
2062 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002063 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002064 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002065 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002066 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002067 }
2068
Dianne Hackborne588ca12012-09-04 18:48:37 -07002069 final long ident = Binder.clearCallingIdentity();
2070 try {
2071 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2072 } finally {
2073 Binder.restoreCallingIdentity(ident);
2074 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002075 }
2076 }
2077
Wink Saville4f0de1e2011-08-04 15:01:58 -07002078 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2079 if (delayMs <= 0) {
2080 sendStickyBroadcast(intent);
2081 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002082 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002083 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2084 + intent.getAction());
2085 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002086 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2087 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2088 }
2089 }
2090
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002091 void systemReady() {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002092 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2093 loadGlobalProxy();
2094
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002095 synchronized(this) {
2096 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002097 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002098 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002099 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002100 }
2101 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002102 // load the global proxy at startup
2103 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002104
2105 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2106 // for user to unlock device.
2107 if (!updateLockdownVpn()) {
2108 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2109 mContext.registerReceiver(mUserPresentReceiver, filter);
2110 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002111 }
2112
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002113 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2114 @Override
2115 public void onReceive(Context context, Intent intent) {
2116 // Try creating lockdown tracker, since user present usually means
2117 // unlocked keystore.
2118 if (updateLockdownVpn()) {
2119 mContext.unregisterReceiver(this);
2120 }
2121 }
2122 };
2123
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002124 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002125 if (((type != mNetworkPreference)
2126 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2127 || (mNetworkPreference == mActiveDefaultNetwork)) {
2128 return false;
2129 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002130 return true;
2131 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002133 private void handleConnect(NetworkInfo info) {
2134 final int newNetType = info.getType();
2135
2136 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002137
The Android Open Source Project28527d22009-03-03 19:31:44 -08002138 // snapshot isFailover, because sendConnectedBroadcast() resets it
2139 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002140 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002141 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002142
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002143 if (VDBG) {
2144 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2145 + " isFailover" + isFailover);
2146 }
2147
Robert Greenwalt2034b912009-08-12 16:08:25 -07002148 // if this is a default net and other default is running
2149 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002150 if (mNetConfigs[newNetType].isDefault()) {
2151 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2152 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002153 // tear down the other
2154 NetworkStateTracker otherNet =
2155 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002156 if (DBG) {
2157 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002158 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002159 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002160 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002161 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002162 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002163 return;
2164 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002165 } else {
2166 // don't accept this one
2167 if (VDBG) {
2168 log("Not broadcasting CONNECT_ACTION " +
2169 "to torn down network " + info.getTypeName());
2170 }
2171 teardown(thisNet);
2172 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002173 }
2174 }
2175 synchronized (ConnectivityService.this) {
2176 // have a new default network, release the transition wakelock in a second
2177 // if it's held. The second pause is to allow apps to reconnect over the
2178 // new network
2179 if (mNetTransitionWakeLock.isHeld()) {
2180 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002181 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002182 mNetTransitionWakeLockSerialNumber, 0),
2183 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002184 }
2185 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002186 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002187 // this will cause us to come up initially as unconnected and switching
2188 // to connected after our normal pause unless somebody reports us as reall
2189 // disconnected
2190 mDefaultInetConditionPublished = 0;
2191 mDefaultConnectionSequence++;
2192 mInetConditionChangeInFlight = false;
2193 // Don't do this - if we never sign in stay, grey
2194 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002195 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002196 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002197 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002198 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002199 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002200
2201 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002202 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002203 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002204 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002205 } catch (RemoteException e) {
2206 // ignored; service lives in system_server
2207 }
2208 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002209 }
2210
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002211 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2212 if (DBG) log("Captive portal check " + info);
2213 int type = info.getType();
2214 final NetworkStateTracker thisNet = mNetTrackers[type];
2215 if (mNetConfigs[type].isDefault()) {
2216 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2217 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2218 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002219 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002220 return;
2221 } else {
2222 if (DBG) log("Tear down low priority net " + info.getTypeName());
2223 teardown(thisNet);
2224 return;
2225 }
2226 }
2227 }
2228
Wink Saville674777e2013-08-07 16:22:47 -07002229 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002230 thisNet.captivePortalCheckComplete();
2231 }
2232
2233 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002234 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002235 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002236 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002237 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002238 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002239 }
2240
Wink Saville674777e2013-08-07 16:22:47 -07002241 /** @hide */
2242 @Override
2243 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2244 enforceConnectivityInternalPermission();
2245 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2246 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2247 }
2248
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002250 * Setup data activity tracking for the given network interface.
2251 *
2252 * Every {@code setupDataActivityTracking} should be paired with a
2253 * {@link removeDataActivityTracking} for cleanup.
2254 */
2255 private void setupDataActivityTracking(int type) {
2256 final NetworkStateTracker thisNet = mNetTrackers[type];
2257 final String iface = thisNet.getLinkProperties().getInterfaceName();
2258
2259 final int timeout;
2260
2261 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002262 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2263 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002264 0);
2265 // Canonicalize mobile network type
2266 type = ConnectivityManager.TYPE_MOBILE;
2267 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002268 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2269 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002270 0);
2271 } else {
2272 // do not track any other networks
2273 timeout = 0;
2274 }
2275
2276 if (timeout > 0 && iface != null) {
2277 try {
2278 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2279 } catch (RemoteException e) {
2280 }
2281 }
2282 }
2283
2284 /**
2285 * Remove data activity tracking when network disconnects.
2286 */
2287 private void removeDataActivityTracking(int type) {
2288 final NetworkStateTracker net = mNetTrackers[type];
2289 final String iface = net.getLinkProperties().getInterfaceName();
2290
2291 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2292 ConnectivityManager.TYPE_WIFI == type)) {
2293 try {
2294 // the call fails silently if no idletimer setup for this interface
2295 mNetd.removeIdleTimer(iface);
2296 } catch (RemoteException e) {
2297 }
2298 }
2299 }
2300
2301 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002302 * After a change in the connectivity state of a network. We're mainly
2303 * concerned with making sure that the list of DNS servers is set up
2304 * according to which networks are connected, and ensuring that the
2305 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002306 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002307 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002308 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002309 if (VDBG) {
2310 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2311 + " resetMask=" + resetMask);
2312 }
Wink Saville051a6642011-07-13 13:44:13 -07002313
The Android Open Source Project28527d22009-03-03 19:31:44 -08002314 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002315 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002316 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002318 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002319
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002320 LinkProperties curLp = mCurrentLinkProperties[netType];
2321 LinkProperties newLp = null;
2322
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002323 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002324 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002325 if (VDBG) {
2326 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2327 " doReset=" + doReset + " resetMask=" + resetMask +
2328 "\n curLp=" + curLp +
2329 "\n newLp=" + newLp);
2330 }
2331
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002332 if (curLp != null) {
2333 if (curLp.isIdenticalInterfaceName(newLp)) {
2334 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2335 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2336 for (LinkAddress linkAddr : car.removed) {
2337 if (linkAddr.getAddress() instanceof Inet4Address) {
2338 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2339 }
2340 if (linkAddr.getAddress() instanceof Inet6Address) {
2341 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2342 }
Wink Saville051a6642011-07-13 13:44:13 -07002343 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002344 if (DBG) {
2345 log("handleConnectivityChange: addresses changed" +
2346 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2347 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002348 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002349 } else {
2350 if (DBG) {
2351 log("handleConnectivityChange: address are the same reset per doReset" +
2352 " linkProperty[" + netType + "]:" +
2353 " resetMask=" + resetMask);
2354 }
Wink Saville051a6642011-07-13 13:44:13 -07002355 }
2356 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002357 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002358 if (DBG) {
2359 log("handleConnectivityChange: interface not not equivalent reset both" +
2360 " linkProperty[" + netType + "]:" +
2361 " resetMask=" + resetMask);
2362 }
Wink Saville051a6642011-07-13 13:44:13 -07002363 }
Wink Saville051a6642011-07-13 13:44:13 -07002364 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002365 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002366 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002367 }
2368 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002369 if (VDBG) {
2370 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2371 " doReset=" + doReset + " resetMask=" + resetMask +
2372 "\n curLp=" + curLp +
2373 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002374 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002375 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002376 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002377 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002378
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002379 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002380 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002381 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002382 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002383 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002384 if (TextUtils.isEmpty(iface) == false) {
2385 if (resetMask != 0) {
2386 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2387 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002388
Lorenzo Colitti63839822013-03-20 19:22:58 +09002389 // Tell VPN the interface is down. It is a temporary
2390 // but effective fix to make VPN aware of the change.
2391 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2392 mVpn.interfaceStatusChanged(iface, false);
2393 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002394 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002395 if (resetDns) {
2396 flushVmDnsCache();
2397 if (VDBG) log("resetting DNS cache for " + iface);
2398 try {
2399 mNetd.flushInterfaceDnsCache(iface);
2400 } catch (Exception e) {
2401 // never crash - catch them all
2402 if (DBG) loge("Exception resetting dns cache: " + e);
2403 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002404 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002405 } else {
2406 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002407 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002408 }
2409 }
2410 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002411
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002412 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002413 NetworkStateTracker tracker = mNetTrackers[netType];
2414 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002415
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002416 // If the connection was previously using clat, but is not using it now, stop the clat
2417 // daemon. Normally, this happens automatically when the connection disconnects, but if
2418 // the disconnect is not reported, or if the connection's LinkProperties changed for
2419 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2420 // still be running. If it's not running, then stopping it is a no-op.
2421 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2422 mClat.stopClat();
2423 }
2424 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002425 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2426 mClat.startClat(tracker);
2427 } else {
2428 mClat.stopClat();
2429 }
2430 }
2431
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002432 // TODO: Temporary notifying upstread change to Tethering.
2433 // @see bug/4455071
2434 /** Notify TetheringService if interface name has been changed. */
2435 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002436 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002437 if (isTetheringSupported()) {
2438 mTethering.handleTetherIfaceChange();
2439 }
2440 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002441 }
2442
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002443 /**
2444 * Add and remove routes using the old properties (null if not previously connected),
2445 * new properties (null if becoming disconnected). May even be double null, which
2446 * is a noop.
2447 * Uses isLinkDefault to determine if default routes should be set or conversely if
2448 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002449 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002450 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002451 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2452 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002453 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002454 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2455 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002456 if (curLp != null) {
2457 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002458 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002459 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002460 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002461 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002462 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002463 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002464
Robert Greenwalt8d777252011-08-15 12:31:55 -07002465 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2466
Robert Greenwalt98107422011-07-22 11:55:33 -07002467 for (RouteInfo r : routeDiff.removed) {
2468 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002469 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002470 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2471 }
2472 if (isLinkDefault == false) {
2473 // remove from a secondary route table
2474 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002475 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002476 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002477
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002478 if (!isLinkDefault) {
2479 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002480 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002481 // routes changed - remove all old dns entries and add new
2482 if (curLp != null) {
2483 for (InetAddress oldDns : curLp.getDnses()) {
2484 removeRouteToAddress(curLp, oldDns);
2485 }
2486 }
2487 if (newLp != null) {
2488 for (InetAddress newDns : newLp.getDnses()) {
2489 addRouteToAddress(newLp, newDns);
2490 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002491 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002492 } else {
2493 // no change in routes, check for change in dns themselves
2494 for (InetAddress oldDns : dnsDiff.removed) {
2495 removeRouteToAddress(curLp, oldDns);
2496 }
2497 for (InetAddress newDns : dnsDiff.added) {
2498 addRouteToAddress(newLp, newDns);
2499 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002500 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002501 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002502
2503 for (RouteInfo r : routeDiff.added) {
2504 if (isLinkDefault || ! r.isDefaultRoute()) {
2505 addRoute(newLp, r, TO_DEFAULT_TABLE);
2506 } else {
2507 // add to a secondary route table
2508 addRoute(newLp, r, TO_SECONDARY_TABLE);
2509
2510 // many radios add a default route even when we don't want one.
2511 // remove the default route unless somebody else has asked for it
2512 String ifaceName = newLp.getInterfaceName();
2513 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002514 try {
2515 mNetd.removeRoute(ifaceName, r);
2516 } catch (Exception e) {
2517 // never crash - catch them all
2518 if (DBG) loge("Exception trying to remove a route: " + e);
2519 }
2520 }
2521 }
2522 }
2523
Robert Greenwalt8d777252011-08-15 12:31:55 -07002524 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002525 }
2526
2527
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002528 /**
2529 * Reads the network specific TCP buffer sizes from SystemProperties
2530 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2531 * wide use
2532 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002533 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002534 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002535 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002536
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002537 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002538 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002539
2540 // Setting to default values so we won't be stuck to previous values
2541 key = "net.tcp.buffersize.default";
2542 bufferSizes = SystemProperties.get(key);
2543 }
2544
2545 // Set values in kernel
2546 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002547 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002548 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002549 + "] which comes from [" + key + "]");
2550 }
2551 setBufferSize(bufferSizes);
2552 }
2553 }
2554
2555 /**
2556 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2557 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2558 *
2559 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2560 * writeMin, writeInitial, writeMax"
2561 */
2562 private void setBufferSize(String bufferSizes) {
2563 try {
2564 String[] values = bufferSizes.split(",");
2565
2566 if (values.length == 6) {
2567 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002568 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2569 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2570 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2571 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2572 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2573 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002574 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002575 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002576 }
2577 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002578 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002579 }
2580 }
2581
Robert Greenwalt2034b912009-08-12 16:08:25 -07002582 /**
2583 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2584 * on the highest priority active net which this process requested.
2585 * If there aren't any, clear it out
2586 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002587 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002588 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002589 if (VDBG) log("reassessPidDns for pid " + pid);
2590 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002591 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002592 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002593 continue;
2594 }
2595 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002596 if (nt.getNetworkInfo().isConnected() &&
2597 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002598 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002599 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002600 if (mNetRequestersPids[i].contains(myPid)) {
2601 try {
2602 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2603 } catch (Exception e) {
2604 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002605 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002606 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002607 }
2608 }
2609 }
2610 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002611 try {
2612 mNetd.clearDnsInterfaceForPid(pid);
2613 } catch (Exception e) {
2614 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002615 }
2616 }
2617
Mattias Falkd697aa22011-08-23 14:15:13 +02002618 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002619 /*
2620 * Tell the VMs to toss their DNS caches
2621 */
2622 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2623 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002624 /*
2625 * Connectivity events can happen before boot has completed ...
2626 */
2627 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002628 final long ident = Binder.clearCallingIdentity();
2629 try {
2630 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2631 } finally {
2632 Binder.restoreCallingIdentity(ident);
2633 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002634 }
2635
Chia-chi Yehcc844502011-07-14 18:01:57 -07002636 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002637 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002638 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002639 int last = 0;
2640 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002641 dnses = new ArrayList();
2642 dnses.add(mDefaultDns);
2643 if (DBG) {
2644 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002645 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002646 }
2647
Mattias Falkd697aa22011-08-23 14:15:13 +02002648 try {
2649 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2650 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002651 for (InetAddress dns : dnses) {
2652 ++last;
2653 String key = "net.dns" + last;
2654 String value = dns.getHostAddress();
2655 SystemProperties.set(key, value);
2656 }
2657 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2658 String key = "net.dns" + i;
2659 SystemProperties.set(key, "");
2660 }
2661 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002662 } catch (Exception e) {
2663 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002664 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002665 }
2666
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002667 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002668 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002669 NetworkStateTracker nt = mNetTrackers[netType];
2670 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002671 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002672 if (p == null) return;
2673 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002674 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002675 String network = nt.getNetworkInfo().getTypeName();
2676 synchronized (mDnsLock) {
2677 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002678 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002679 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002680 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002681 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002682 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002683 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002684 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002685 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002686 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002687 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002688 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002689 List<Integer> pids = mNetRequestersPids[netType];
2690 for (Integer pid : pids) {
2691 try {
2692 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2693 } catch (Exception e) {
2694 Slog.e(TAG, "exception setting interface for pid: " + e);
2695 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002696 }
2697 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002698 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002699 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002700 }
2701
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002702 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002703 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2704 NETWORK_RESTORE_DELAY_PROP_NAME);
2705 if(restoreDefaultNetworkDelayStr != null &&
2706 restoreDefaultNetworkDelayStr.length() != 0) {
2707 try {
2708 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2709 } catch (NumberFormatException e) {
2710 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002711 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002712 // if the system property isn't set, use the value for the apn type
2713 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2714
2715 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2716 (mNetConfigs[networkType] != null)) {
2717 ret = mNetConfigs[networkType].restoreTime;
2718 }
2719 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002720 }
2721
2722 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002723 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2724 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002725 if (mContext.checkCallingOrSelfPermission(
2726 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002727 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002728 pw.println("Permission Denial: can't dump ConnectivityService " +
2729 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2730 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002731 return;
2732 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002733
2734 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002735 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002736 for (int i = 0; i < mNetTrackers.length; i++) {
2737 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002738 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002739 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2740 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002741 if (nst.getNetworkInfo().isConnected()) {
2742 pw.println("Active network: " + nst.getNetworkInfo().
2743 getTypeName());
2744 }
2745 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002746 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002747 pw.println(nst);
2748 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002749 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002750 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002751 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002752
2753 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002754 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002755 for (int net : mPriorityList) {
2756 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002757 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002758 pidString = pidString + pid.toString() + ", ";
2759 }
2760 pw.println(pidString);
2761 }
2762 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002763 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002764
2765 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002766 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002767 for (Object requester : mFeatureUsers) {
2768 pw.println(requester.toString());
2769 }
2770 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002771 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002772
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002773 synchronized (this) {
2774 pw.println("NetworkTranstionWakeLock is currently " +
2775 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2776 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2777 }
2778 pw.println();
2779
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002780 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002781
2782 if (mInetLog != null) {
2783 pw.println();
2784 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002785 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002786 for(int i = 0; i < mInetLog.size(); i++) {
2787 pw.println(mInetLog.get(i));
2788 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002789 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002790 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002791 }
2792
Robert Greenwalt2034b912009-08-12 16:08:25 -07002793 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002794 private class NetworkStateTrackerHandler extends Handler {
2795 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002796 super(looper);
2797 }
2798
The Android Open Source Project28527d22009-03-03 19:31:44 -08002799 @Override
2800 public void handleMessage(Message msg) {
2801 NetworkInfo info;
2802 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002803 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002804 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002805 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002806
Wink Savillea7d56572011-09-21 11:05:43 -07002807 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2808 (state == NetworkInfo.State.DISCONNECTED)) {
2809 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))
2823 && (state == NetworkInfo.State.CONNECTED)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002824 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002825 }
2826
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002827 EventLogTags.writeConnectivityStateChanged(
2828 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002829
2830 if (info.getDetailedState() ==
2831 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002832 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002833 } else if (info.getDetailedState() ==
2834 DetailedState.CAPTIVE_PORTAL_CHECK) {
2835 handleCaptivePortalTrackerCheck(info);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002836 } else if (info.getDetailedState() ==
2837 DetailedState.CONNECTED_TO_PROVISIONING_NETWORK) {
2838 /**
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();
4200 if ((ni != null) && ni.getDetailedState() ==
4201 NetworkInfo.DetailedState.CONNECTED_TO_PROVISIONING_NETWORK) {
4202 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4203 MobileDataStateTracker mdst = (MobileDataStateTracker)
4204 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4205 mdst.enableMobileProvisioning(url);
4206 } else {
4207 if (DBG) log("handleMobileProvisioningAction: on default network");
4208 Intent newIntent =
4209 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4210 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4211 Intent.FLAG_ACTIVITY_NEW_TASK);
4212 try {
4213 mContext.startActivity(newIntent);
4214 } catch (ActivityNotFoundException e) {
4215 loge("handleMobileProvisioningAction: startActivity failed" + e);
4216 }
4217 }
4218 }
4219
4220 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4221 private volatile boolean mIsNotificationVisible = false;
4222
4223 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4224 String url) {
4225 if (DBG) {
4226 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4227 + " extraInfo=" + extraInfo + " url=" + url);
4228 }
Wink Saville32506bc2013-06-29 21:10:57 -07004229
4230 Resources r = Resources.getSystem();
4231 NotificationManager notificationManager = (NotificationManager) mContext
4232 .getSystemService(Context.NOTIFICATION_SERVICE);
4233
4234 if (visible) {
4235 CharSequence title;
4236 CharSequence details;
4237 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004238 Intent intent;
4239 Notification notification = new Notification();
4240 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004241 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004242 title = r.getString(R.string.wifi_available_sign_in, 0);
4243 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004244 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004245 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004246 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4247 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4248 Intent.FLAG_ACTIVITY_NEW_TASK);
4249 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004250 break;
4251 case ConnectivityManager.TYPE_MOBILE:
4252 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004253 title = r.getString(R.string.network_available_sign_in, 0);
4254 // TODO: Change this to pull from NetworkInfo once a printable
4255 // name has been added to it
4256 details = mTelephonyManager.getNetworkOperatorName();
4257 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004258 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4259 intent.putExtra("EXTRA_URL", url);
4260 intent.setFlags(0);
4261 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004262 break;
4263 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004264 title = r.getString(R.string.network_available_sign_in, 0);
4265 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004266 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004267 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004268 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4269 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4270 Intent.FLAG_ACTIVITY_NEW_TASK);
4271 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004272 break;
4273 }
4274
Wink Saville32506bc2013-06-29 21:10:57 -07004275 notification.when = 0;
4276 notification.icon = icon;
4277 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004278 notification.tickerText = title;
4279 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4280
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004281 try {
4282 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4283 } catch (NullPointerException npe) {
4284 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4285 npe.printStackTrace();
4286 }
Wink Saville32506bc2013-06-29 21:10:57 -07004287 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004288 try {
4289 notificationManager.cancel(NOTIFICATION_ID, 1);
4290 } catch (NullPointerException npe) {
4291 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4292 npe.printStackTrace();
4293 }
Wink Saville32506bc2013-06-29 21:10:57 -07004294 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004295 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004296 }
4297
Robert Greenwalt39d56012013-07-16 12:06:09 -07004298 /** Location to an updatable file listing carrier provisioning urls.
4299 * An example:
4300 *
4301 * <?xml version="1.0" encoding="utf-8"?>
4302 * <provisioningUrls>
4303 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4304 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4305 * </provisioningUrls>
4306 */
4307 private static final String PROVISIONING_URL_PATH =
4308 "/data/misc/radio/provisioning_urls.xml";
4309 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004310
Robert Greenwalt39d56012013-07-16 12:06:09 -07004311 /** XML tag for root element. */
4312 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4313 /** XML tag for individual url */
4314 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4315 /** XML tag for redirected url */
4316 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4317 /** XML attribute for mcc */
4318 private static final String ATTR_MCC = "mcc";
4319 /** XML attribute for mnc */
4320 private static final String ATTR_MNC = "mnc";
4321
4322 private static final int REDIRECTED_PROVISIONING = 1;
4323 private static final int PROVISIONING = 2;
4324
4325 private String getProvisioningUrlBaseFromFile(int type) {
4326 FileReader fileReader = null;
4327 XmlPullParser parser = null;
4328 Configuration config = mContext.getResources().getConfiguration();
4329 String tagType;
4330
4331 switch (type) {
4332 case PROVISIONING:
4333 tagType = TAG_PROVISIONING_URL;
4334 break;
4335 case REDIRECTED_PROVISIONING:
4336 tagType = TAG_REDIRECTED_URL;
4337 break;
4338 default:
4339 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4340 type);
4341 }
4342
4343 try {
4344 fileReader = new FileReader(mProvisioningUrlFile);
4345 parser = Xml.newPullParser();
4346 parser.setInput(fileReader);
4347 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4348
4349 while (true) {
4350 XmlUtils.nextElement(parser);
4351
4352 String element = parser.getName();
4353 if (element == null) break;
4354
4355 if (element.equals(tagType)) {
4356 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4357 try {
4358 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4359 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4360 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4361 parser.next();
4362 if (parser.getEventType() == XmlPullParser.TEXT) {
4363 return parser.getText();
4364 }
4365 }
4366 }
4367 } catch (NumberFormatException e) {
4368 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4369 }
4370 }
4371 }
4372 return null;
4373 } catch (FileNotFoundException e) {
4374 loge("Carrier Provisioning Urls file not found");
4375 } catch (XmlPullParserException e) {
4376 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4377 } catch (IOException e) {
4378 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4379 } finally {
4380 if (fileReader != null) {
4381 try {
4382 fileReader.close();
4383 } catch (IOException e) {}
4384 }
4385 }
4386 return null;
4387 }
4388
Wink Saville8432cf42013-07-20 20:31:59 -07004389 @Override
4390 public String getMobileRedirectedProvisioningUrl() {
4391 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004392 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4393 if (TextUtils.isEmpty(url)) {
4394 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4395 }
4396 return url;
4397 }
4398
Wink Saville8432cf42013-07-20 20:31:59 -07004399 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004400 public String getMobileProvisioningUrl() {
4401 enforceConnectivityInternalPermission();
4402 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4403 if (TextUtils.isEmpty(url)) {
4404 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004405 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004406 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004407 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004408 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004409 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004410 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004411 String phoneNumber = mTelephonyManager.getLine1Number();
4412 if (TextUtils.isEmpty(phoneNumber)) {
4413 phoneNumber = "0000000000";
4414 }
Wink Saville32506bc2013-06-29 21:10:57 -07004415 url = String.format(url,
4416 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4417 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004418 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004419 }
4420
Wink Saville32506bc2013-06-29 21:10:57 -07004421 return url;
4422 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004423
4424 @Override
4425 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4426 String extraInfo, String url) {
4427 enforceConnectivityInternalPermission();
4428 setProvNotificationVisible(visible, networkType, extraInfo, url);
4429 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004430}