blob: b148b9121938bf5e9ea8ce6b0246a747cf82f468 [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;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090041import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090045import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070046import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070047import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080049import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080050import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070056import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080057import android.net.LinkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -070058import android.net.Uri;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Wink Saville32506bc2013-06-29 21:10:57 -070064import android.net.NetworkInfo.State;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070066import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080067import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070069import android.net.Proxy;
70import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070071import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090073import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070074import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070087import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070088import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080089import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070092import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -070096import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070097import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080098import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070099import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100
Wink Saville32506bc2013-06-29 21:10:57 -0700101import com.android.internal.R;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700102import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700103import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700106import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700107import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700108import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400110import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900111import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800112import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700113import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700114import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700115import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700116import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700117import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700118
tk.mun093f55c2011-10-13 22:51:57 +0900119import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700120
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700122import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900124import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700125import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700126import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700127import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700128import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700129import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700130import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700131import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700132import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700133import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700134import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700135import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700136import java.util.List;
Wink Saville32506bc2013-06-29 21:10:57 -0700137import java.util.Random;
138import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139
140/**
141 * @hide
142 */
143public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700144 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700146 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700147 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800148
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700149 private static final boolean LOGD_RULES = false;
150
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700151 // TODO: create better separation between radio types and network types
152
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153 // how long to wait before switching back to a radio's default network
154 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
155 // system property that can override the above value
156 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
157 "android.telephony.apn-restore";
158
Wink Saville32506bc2013-06-29 21:10:57 -0700159 // Default value if FAIL_FAST_TIME_MS is not set
160 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
161 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
162 private static final String FAIL_FAST_TIME_MS =
163 "persist.radio.fail_fast_time_ms";
164
Robert Greenwaltbd492212011-05-06 17:10:53 -0700165 // used in recursive route setting to add gateways for the host for which
166 // a host route was requested.
167 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
168
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800169 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800170 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800171
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700172 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700173
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700174 private Vpn mVpn;
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700175 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700176
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700177 private boolean mLockdownEnabled;
178 private LockdownVpnTracker mLockdownTracker;
179
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900180 private Nat464Xlat mClat;
181
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700182 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
183 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700184 /** Currently active network rules by UID. */
185 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700186 /** Set of ifaces that are costly. */
187 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700188
The Android Open Source Project28527d22009-03-03 19:31:44 -0800189 /**
190 * Sometimes we want to refer to the individual network state
191 * trackers separately, and sometimes we just want to treat them
192 * abstractly.
193 */
194 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700195
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700196 /* Handles captive portal check on a network */
197 private CaptivePortalTracker mCaptivePortalTracker;
198
Robert Greenwalt2034b912009-08-12 16:08:25 -0700199 /**
Wink Saville051a6642011-07-13 13:44:13 -0700200 * The link properties that define the current links
201 */
202 private LinkProperties mCurrentLinkProperties[];
203
204 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700205 * A per Net list of the PID's that requested access to the net
206 * used both as a refcount and for per-PID DNS selection
207 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200208 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700209
Robert Greenwalt2034b912009-08-12 16:08:25 -0700210 // priority order of the nettrackers
211 // (excluding dynamically set mNetworkPreference)
212 // TODO - move mNetworkTypePreference into this
213 private int[] mPriorityList;
214
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215 private Context mContext;
216 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700217 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700218 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000219 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700220 private int mDefaultInetConditionPublished = 0;
221 private boolean mInetConditionChangeInFlight = false;
222 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223
Chia-chi Yehcc844502011-07-14 18:01:57 -0700224 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800225 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700226 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227
228 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700229 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230
Robert Greenwalt355205c2011-05-10 15:05:02 -0700231 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700232 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700233
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700234 private static final int ENABLED = 1;
235 private static final int DISABLED = 0;
236
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700237 private static final boolean ADD = true;
238 private static final boolean REMOVE = false;
239
240 private static final boolean TO_DEFAULT_TABLE = true;
241 private static final boolean TO_SECONDARY_TABLE = false;
242
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700243 /**
244 * used internally as a delayed event to make us switch back to the
245 * default network
246 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700247 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700248
249 /**
250 * used internally to change our mobile data enabled flag
251 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700252 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700253
254 /**
255 * used internally to change our network preference setting
256 * arg1 = networkType to prefer
257 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700258 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700259
260 /**
261 * used internally to synchronize inet condition reports
262 * arg1 = networkType
263 * arg2 = condition (0 bad, 100 good)
264 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700265 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700266
267 /**
268 * used internally to mark the end of inet condition hold periods
269 * arg1 = networkType
270 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700271 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700272
273 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700274 * used internally to set enable/disable cellular data
275 * arg1 = ENBALED or DISABLED
276 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700277 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700278
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700279 /**
280 * used internally to clear a wakelock when transitioning
281 * from one net to another
282 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700283 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700284
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700285 /**
286 * used internally to reload global proxy settings
287 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700288 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700289
Robert Greenwalt34848c02011-03-25 13:09:25 -0700290 /**
291 * used internally to set external dependency met/unmet
292 * arg1 = ENABLED (met) or DISABLED (unmet)
293 * arg2 = NetworkType
294 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700295 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700296
Chia-chi Yehcc844502011-07-14 18:01:57 -0700297 /**
298 * used internally to restore DNS properties back to the
299 * default network
300 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700301 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700302
Wink Saville7e4333c2011-08-05 11:40:22 -0700303 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700304 * used internally to send a sticky broadcast delayed.
305 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700306 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700307
Jeff Sharkey805662d2011-08-19 02:24:24 -0700308 /**
309 * Used internally to
310 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
311 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700312 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700313
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700314 private static final int EVENT_VPN_STATE_CHANGED = 14;
315
Wink Saville32506bc2013-06-29 21:10:57 -0700316 /**
317 * Used internally to disable fail fast of mobile data
318 */
319 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
320
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700321 /** Handler used for internal events. */
322 private InternalHandler mHandler;
323 /** Handler used for incoming {@link NetworkStateTracker} events. */
324 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700325
326 // list of DeathRecipients used to make sure features are turned off when
327 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500328 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700329
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400330 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800331 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400332
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700333 private PowerManager.WakeLock mNetTransitionWakeLock;
334 private String mNetTransitionWakeLockCausedBy = "";
335 private int mNetTransitionWakeLockSerialNumber;
336 private int mNetTransitionWakeLockTimeout;
337
Robert Greenwalt94daa182010-09-01 11:34:05 -0700338 private InetAddress mDefaultDns;
339
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700340 // this collection is used to refcount the added routes - if there are none left
341 // it's time to remove the route from the route table
342 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
343
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700344 // used in DBG mode to track inet condition reports
345 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
346 private ArrayList mInetLog;
347
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700348 // track the current default http proxy - tell the world if we get a new one (real change)
349 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700350 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700351 private boolean mDefaultProxyDisabled = false;
352
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700353 // track the global proxy.
354 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700355
356 private SettingsObserver mSettingsObserver;
357
Robert Greenwalt34848c02011-03-25 13:09:25 -0700358 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700359 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360
Robert Greenwalt12c44552009-12-07 11:33:18 -0800361 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700362 public int mSimultaneity;
363 public int mType;
364 public RadioAttributes(String init) {
365 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700366 mType = Integer.parseInt(fragments[0]);
367 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700368 }
369 }
370 RadioAttributes[] mRadioAttributes;
371
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700372 // the set of network types that can only be enabled by system/sig apps
373 List mProtectedNetworks;
374
John Spurlock1f5cec72013-06-24 14:20:23 -0400375 private DataConnectionStats mDataConnectionStats;
Wink Saville32506bc2013-06-29 21:10:57 -0700376 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
377
378 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400379
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700380 public ConnectivityService(Context context, INetworkManagementService netd,
381 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700382 // Currently, omitting a NetworkFactory will create one internally
383 // TODO: create here when we have cleaner WiMAX support
384 this(context, netd, statsService, policyManager, null);
385 }
386
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700387 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700388 INetworkStatsService statsService, INetworkPolicyManager policyManager,
389 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800390 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800391
Wink Saville775aad62010-09-02 19:23:52 -0700392 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
393 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700394 mHandler = new InternalHandler(handlerThread.getLooper());
395 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700396
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700397 if (netFactory == null) {
398 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
399 }
400
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800401 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800402 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
403 String id = Settings.Secure.getString(context.getContentResolver(),
404 Settings.Secure.ANDROID_ID);
405 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700406 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800407 SystemProperties.set("net.hostname", name);
408 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800409 }
410
Robert Greenwalt94daa182010-09-01 11:34:05 -0700411 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700412 String dns = Settings.Global.getString(context.getContentResolver(),
413 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700414 if (dns == null || dns.length() == 0) {
415 dns = context.getResources().getString(
416 com.android.internal.R.string.config_default_dns_server);
417 }
418 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800419 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
420 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800421 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700422 }
423
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700424 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700425 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700426 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700427 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700428 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700429
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700430 try {
431 mPolicyManager.registerListener(mPolicyListener);
432 } catch (RemoteException e) {
433 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700434 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700435 }
436
437 final PowerManager powerManager = (PowerManager) context.getSystemService(
438 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700439 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
440 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
441 com.android.internal.R.integer.config_networkTransitionTimeout);
442
Robert Greenwalt2034b912009-08-12 16:08:25 -0700443 mNetTrackers = new NetworkStateTracker[
444 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700445 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700446
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700448 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700449
Robert Greenwalt2034b912009-08-12 16:08:25 -0700450 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700451 String[] raStrings = context.getResources().getStringArray(
452 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700453 for (String raString : raStrings) {
454 RadioAttributes r = new RadioAttributes(raString);
455 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800456 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700457 continue;
458 }
459 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800460 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700461 r.mType);
462 continue;
463 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700464 mRadioAttributes[r.mType] = r;
465 }
466
Wink Saville00fe5092013-04-23 14:26:51 -0700467 // TODO: What is the "correct" way to do determine if this is a wifi only device?
468 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
469 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700470 String[] naStrings = context.getResources().getStringArray(
471 com.android.internal.R.array.networkAttributes);
472 for (String naString : naStrings) {
473 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700474 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700475 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800476 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700477 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700478 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700479 }
Wink Saville00fe5092013-04-23 14:26:51 -0700480 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
481 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
482 n.type);
483 continue;
484 }
Wink Savillef2a62832011-04-07 14:23:45 -0700485 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800486 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700487 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700488 continue;
489 }
Wink Savillef2a62832011-04-07 14:23:45 -0700490 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800491 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700492 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700493 continue;
494 }
Wink Savillef2a62832011-04-07 14:23:45 -0700495 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700496 mNetworksDefined++;
497 } catch(Exception e) {
498 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700499 }
500 }
501
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700502 mProtectedNetworks = new ArrayList<Integer>();
503 int[] protectedNetworks = context.getResources().getIntArray(
504 com.android.internal.R.array.config_protectedNetworks);
505 for (int p : protectedNetworks) {
506 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
507 mProtectedNetworks.add(p);
508 } else {
509 if (DBG) loge("Ignoring protectedNetwork " + p);
510 }
511 }
512
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700513 // high priority first
514 mPriorityList = new int[mNetworksDefined];
515 {
516 int insertionPoint = mNetworksDefined-1;
517 int currentLowest = 0;
518 int nextLowest = 0;
519 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700520 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700521 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700522 if (na.priority < currentLowest) continue;
523 if (na.priority > currentLowest) {
524 if (na.priority < nextLowest || nextLowest == 0) {
525 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700526 }
527 continue;
528 }
Wink Savillef2a62832011-04-07 14:23:45 -0700529 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700530 }
531 currentLowest = nextLowest;
532 nextLowest = 0;
533 }
534 }
535
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800536 // Update mNetworkPreference according to user mannually first then overlay config.xml
537 mNetworkPreference = getPersistedNetworkPreference();
538 if (mNetworkPreference == -1) {
539 for (int n : mPriorityList) {
540 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
541 mNetworkPreference = n;
542 break;
543 }
544 }
545 if (mNetworkPreference == -1) {
546 throw new IllegalStateException(
547 "You should set at least one default Network in config.xml!");
548 }
549 }
550
Mattias Falkd697aa22011-08-23 14:15:13 +0200551 mNetRequestersPids =
552 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700553 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200554 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700555 }
556
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500557 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700559 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
560 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700561
562 // Create and start trackers for hard-coded networks
563 for (int targetNetworkType : mPriorityList) {
564 final NetworkConfig config = mNetConfigs[targetNetworkType];
565 final NetworkStateTracker tracker;
566 try {
567 tracker = netFactory.createTracker(targetNetworkType, config);
568 mNetTrackers[targetNetworkType] = tracker;
569 } catch (IllegalArgumentException e) {
570 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
571 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700572 continue;
573 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700574
575 tracker.startMonitoring(context, mTrackerHandler);
576 if (config.isDefault()) {
577 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800578 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700579 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800580
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700581 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700582 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700583 mTethering.getTetherableWifiRegexs().length != 0 ||
584 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700585 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800586
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -0700587 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700588 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700589
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900590 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
591
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700592 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700593 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700594 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900595 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700596 } catch (RemoteException e) {
597 loge("Error registering observer :" + e);
598 }
599
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700600 if (DBG) {
601 mInetLog = new ArrayList();
602 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700603
604 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
605 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800606
Irfan Sheriff32bed2c2012-09-20 09:32:41 -0700607 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800608 loadGlobalProxy();
John Spurlock1f5cec72013-06-24 14:20:23 -0400609
610 mDataConnectionStats = new DataConnectionStats(mContext);
611 mDataConnectionStats.startMonitoring();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800612 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700613
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700614 /**
615 * Factory that creates {@link NetworkStateTracker} instances using given
616 * {@link NetworkConfig}.
617 */
618 public interface NetworkFactory {
619 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
620 }
621
622 private static class DefaultNetworkFactory implements NetworkFactory {
623 private final Context mContext;
624 private final Handler mTrackerHandler;
625
626 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
627 mContext = context;
628 mTrackerHandler = trackerHandler;
629 }
630
631 @Override
632 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
633 switch (config.radio) {
634 case TYPE_WIFI:
635 return new WifiStateTracker(targetNetworkType, config.name);
636 case TYPE_MOBILE:
637 return new MobileDataStateTracker(targetNetworkType, config.name);
638 case TYPE_DUMMY:
639 return new DummyDataStateTracker(targetNetworkType, config.name);
640 case TYPE_BLUETOOTH:
641 return BluetoothTetheringDataTracker.getInstance();
642 case TYPE_WIMAX:
643 return makeWimaxStateTracker(mContext, mTrackerHandler);
644 case TYPE_ETHERNET:
645 return EthernetDataTracker.getInstance();
646 default:
647 throw new IllegalArgumentException(
648 "Trying to create a NetworkStateTracker for an unknown radio type: "
649 + config.radio);
650 }
651 }
652 }
653
654 /**
655 * Loads external WiMAX library and registers as system service, returning a
656 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
657 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
658 */
659 private static NetworkStateTracker makeWimaxStateTracker(
660 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700661 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900662 DexClassLoader wimaxClassLoader;
663 Class wimaxStateTrackerClass = null;
664 Class wimaxServiceClass = null;
665 Class wimaxManagerClass;
666 String wimaxJarLocation;
667 String wimaxLibLocation;
668 String wimaxManagerClassName;
669 String wimaxServiceClassName;
670 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800671
tk.mun093f55c2011-10-13 22:51:57 +0900672 NetworkStateTracker wimaxStateTracker = null;
673
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700674 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900675 com.android.internal.R.bool.config_wimaxEnabled);
676
677 if (isWimaxEnabled) {
678 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700679 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900680 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700681 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900682 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700683 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900684 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700685 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900686 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700687 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900688 com.android.internal.R.string.config_wimaxStateTrackerClassname);
689
Dianne Hackborndc456a62012-11-08 11:12:09 -0800690 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900691 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700692 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900693 wimaxLibLocation, ClassLoader.getSystemClassLoader());
694
695 try {
696 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
697 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
698 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
699 } catch (ClassNotFoundException ex) {
700 loge("Exception finding Wimax classes: " + ex.toString());
701 return null;
702 }
703 } catch(Resources.NotFoundException ex) {
704 loge("Wimax Resources does not exist!!! ");
705 return null;
706 }
707
708 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800709 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900710
711 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
712 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700713 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
714 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900715
716 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
717 (new Class[] {Context.class, wimaxStateTrackerClass});
718 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700719 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900720 wmxSrvConst.setAccessible(false);
721
722 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
723
724 } catch(Exception ex) {
725 loge("Exception creating Wimax classes: " + ex.toString());
726 return null;
727 }
728 } else {
729 loge("Wimax is not enabled or not added to the network attributes!!! ");
730 return null;
731 }
732
733 return wimaxStateTracker;
734 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700735
The Android Open Source Project28527d22009-03-03 19:31:44 -0800736 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700737 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800738 * @param preference the new preference
739 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700740 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800741 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700742
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700743 mHandler.sendMessage(
744 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800745 }
746
747 public int getNetworkPreference() {
748 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700749 int preference;
750 synchronized(this) {
751 preference = mNetworkPreference;
752 }
753 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800754 }
755
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700756 private void handleSetNetworkPreference(int preference) {
757 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700758 mNetConfigs[preference] != null &&
759 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700760 if (mNetworkPreference != preference) {
761 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700762 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700763 synchronized(this) {
764 mNetworkPreference = preference;
765 }
766 enforcePreference();
767 }
768 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800769 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700770
Wink Saville4f0de1e2011-08-04 15:01:58 -0700771 private int getConnectivityChangeDelay() {
772 final ContentResolver cr = mContext.getContentResolver();
773
774 /** Check system properties for the default value then use secure settings value, if any. */
775 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700776 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
777 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
778 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700779 defaultDelay);
780 }
781
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782 private int getPersistedNetworkPreference() {
783 final ContentResolver cr = mContext.getContentResolver();
784
Jeff Brownc67cf562012-09-25 15:03:20 -0700785 final int networkPrefSetting = Settings.Global
786 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800787
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800788 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700790
The Android Open Source Project28527d22009-03-03 19:31:44 -0800791 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700792 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800793 * In this method, we only tear down a non-preferred network. Establishing
794 * a connection to the preferred network is taken care of when we handle
795 * the disconnect event from the non-preferred network
796 * (see {@link #handleDisconnect(NetworkInfo)}).
797 */
798 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700799 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 return;
801
Robert Greenwalt2034b912009-08-12 16:08:25 -0700802 if (!mNetTrackers[mNetworkPreference].isAvailable())
803 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800804
Robert Greenwalt2034b912009-08-12 16:08:25 -0700805 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700806 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700808 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800809 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700810 " in enforcePreference");
811 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700812 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 }
814 }
815 }
816
817 private boolean teardown(NetworkStateTracker netTracker) {
818 if (netTracker.teardown()) {
819 netTracker.setTeardownRequested(true);
820 return true;
821 } else {
822 return false;
823 }
824 }
825
826 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700827 * Check if UID should be blocked from using the network represented by the
828 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700829 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700830 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
831 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700832
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700833 final boolean networkCostly;
834 final int uidRules;
835 synchronized (mRulesLock) {
836 networkCostly = mMeteredIfaces.contains(iface);
837 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700838 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700839
840 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
841 return true;
842 }
843
844 // no restrictive rules; network is visible
845 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700846 }
847
848 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700849 * Return a filtered {@link NetworkInfo}, potentially marked
850 * {@link DetailedState#BLOCKED} based on
851 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700852 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700853 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
854 NetworkInfo info = tracker.getNetworkInfo();
855 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700856 // network is blocked; clone and override state
857 info = new NetworkInfo(info);
858 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700859 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700860 if (mLockdownTracker != null) {
861 info = mLockdownTracker.augmentNetworkInfo(info);
862 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700863 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700864 }
865
866 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800867 * Return NetworkInfo for the active (i.e., connected) network interface.
868 * It is assumed that at most one network is active at a time. If more
869 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700870 * @return the info for the active network, or {@code null} if none is
871 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800872 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700873 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800874 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700875 enforceAccessPermission();
876 final int uid = Binder.getCallingUid();
877 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800878 }
879
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700880 public NetworkInfo getActiveNetworkInfoUnfiltered() {
881 enforceAccessPermission();
882 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
883 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
884 if (tracker != null) {
885 return tracker.getNetworkInfo();
886 }
887 }
888 return null;
889 }
890
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700891 @Override
892 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
893 enforceConnectivityInternalPermission();
894 return getNetworkInfo(mActiveDefaultNetwork, uid);
895 }
896
897 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800898 public NetworkInfo getNetworkInfo(int networkType) {
899 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700900 final int uid = Binder.getCallingUid();
901 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800902 }
903
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700904 private NetworkInfo getNetworkInfo(int networkType, int uid) {
905 NetworkInfo info = null;
906 if (isNetworkTypeValid(networkType)) {
907 final NetworkStateTracker tracker = mNetTrackers[networkType];
908 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700909 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700910 }
911 }
912 return info;
913 }
914
915 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800916 public NetworkInfo[] getAllNetworkInfo() {
917 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700918 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700919 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700920 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700921 for (NetworkStateTracker tracker : mNetTrackers) {
922 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700923 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700924 }
925 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800926 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700927 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800928 }
929
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700930 @Override
931 public boolean isNetworkSupported(int networkType) {
932 enforceAccessPermission();
933 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
934 }
935
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700936 /**
937 * Return LinkProperties for the active (i.e., connected) default
938 * network interface. It is assumed that at most one default network
939 * is active at a time. If more than one is active, it is indeterminate
940 * which will be returned.
941 * @return the ip properties for the active network, or {@code null} if
942 * none is active
943 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700944 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700945 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700946 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700947 }
948
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700949 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700950 public LinkProperties getLinkProperties(int networkType) {
951 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 if (isNetworkTypeValid(networkType)) {
953 final NetworkStateTracker tracker = mNetTrackers[networkType];
954 if (tracker != null) {
955 return tracker.getLinkProperties();
956 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700957 }
958 return null;
959 }
960
Jeff Sharkey21062e72011-05-28 20:56:34 -0700961 @Override
962 public NetworkState[] getAllNetworkState() {
963 enforceAccessPermission();
964 final int uid = Binder.getCallingUid();
965 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700966 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700967 for (NetworkStateTracker tracker : mNetTrackers) {
968 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700969 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700970 result.add(new NetworkState(
971 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
972 }
973 }
974 }
975 return result.toArray(new NetworkState[result.size()]);
976 }
977
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700978 private NetworkState getNetworkStateUnchecked(int networkType) {
979 if (isNetworkTypeValid(networkType)) {
980 final NetworkStateTracker tracker = mNetTrackers[networkType];
981 if (tracker != null) {
982 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
983 tracker.getLinkCapabilities());
984 }
985 }
986 return null;
987 }
988
989 @Override
990 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
991 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700992
993 final long token = Binder.clearCallingIdentity();
994 try {
995 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
996 if (state != null) {
997 try {
998 return mPolicyManager.getNetworkQuotaInfo(state);
999 } catch (RemoteException e) {
1000 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001001 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001002 return null;
1003 } finally {
1004 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001005 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001006 }
1007
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001008 @Override
1009 public boolean isActiveNetworkMetered() {
1010 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001011 final long token = Binder.clearCallingIdentity();
1012 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001013 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001014 } finally {
1015 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001016 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001017 }
1018
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001019 private boolean isNetworkMeteredUnchecked(int networkType) {
1020 final NetworkState state = getNetworkStateUnchecked(networkType);
1021 if (state != null) {
1022 try {
1023 return mPolicyManager.isNetworkMetered(state);
1024 } catch (RemoteException e) {
1025 }
1026 }
1027 return false;
1028 }
1029
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 public boolean setRadios(boolean turnOn) {
1031 boolean result = true;
1032 enforceChangePermission();
1033 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001034 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001035 }
1036 return result;
1037 }
1038
1039 public boolean setRadio(int netType, boolean turnOn) {
1040 enforceChangePermission();
1041 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1042 return false;
1043 }
1044 NetworkStateTracker tracker = mNetTrackers[netType];
1045 return tracker != null && tracker.setRadio(turnOn);
1046 }
1047
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001048 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1049 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001050 public void interfaceClassDataActivityChanged(String label, boolean active) {
1051 int deviceType = Integer.parseInt(label);
1052 sendDataActivityBroadcast(deviceType, active);
1053 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001054 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001055
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001056 /**
1057 * Used to notice when the calling process dies so we can self-expire
1058 *
1059 * Also used to know if the process has cleaned up after itself when
1060 * our auto-expire timer goes off. The timer has a link to an object.
1061 *
1062 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001063 private class FeatureUser implements IBinder.DeathRecipient {
1064 int mNetworkType;
1065 String mFeature;
1066 IBinder mBinder;
1067 int mPid;
1068 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001069 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001070
1071 FeatureUser(int type, String feature, IBinder binder) {
1072 super();
1073 mNetworkType = type;
1074 mFeature = feature;
1075 mBinder = binder;
1076 mPid = getCallingPid();
1077 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001078 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001079
Robert Greenwalt2034b912009-08-12 16:08:25 -07001080 try {
1081 mBinder.linkToDeath(this, 0);
1082 } catch (RemoteException e) {
1083 binderDied();
1084 }
1085 }
1086
1087 void unlinkDeathRecipient() {
1088 mBinder.unlinkToDeath(this, 0);
1089 }
1090
1091 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001092 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001093 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1094 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001095 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001096 }
1097
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001098 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001099 if (VDBG) {
1100 log("ConnectivityService FeatureUser expire(" +
1101 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1102 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1103 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001104 stopUsingNetworkFeature(this, false);
1105 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001106
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001107 public boolean isSameUser(FeatureUser u) {
1108 if (u == null) return false;
1109
1110 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1111 }
1112
1113 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1114 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1115 TextUtils.equals(mFeature, feature)) {
1116 return true;
1117 }
1118 return false;
1119 }
1120
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001121 public String toString() {
1122 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1123 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1124 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001125 }
1126
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001127 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001128 public int startUsingNetworkFeature(int networkType, String feature,
1129 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001130 long startTime = 0;
1131 if (DBG) {
1132 startTime = SystemClock.elapsedRealtime();
1133 }
Wink Savillea7d56572011-09-21 11:05:43 -07001134 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001135 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1136 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001137 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001138 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001139 try {
1140 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1141 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001142 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001143 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001144
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001145 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001146
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001147 // TODO - move this into individual networktrackers
1148 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001149
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001150 if (mLockdownEnabled) {
1151 // Since carrier APNs usually aren't available from VPN
1152 // endpoint, mark them as unavailable.
1153 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1154 }
1155
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001156 if (mProtectedNetworks.contains(usedNetworkType)) {
1157 enforceConnectivityInternalPermission();
1158 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001159
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001160 // if UID is restricted, don't allow them to bring up metered APNs
1161 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1162 final int uidRules;
1163 synchronized (mRulesLock) {
1164 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1165 }
1166 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001167 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001168 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001169
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001170 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1171 if (network != null) {
1172 Integer currentPid = new Integer(getCallingPid());
1173 if (usedNetworkType != networkType) {
1174 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001175
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001176 if (ni.isAvailable() == false) {
1177 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1178 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001179 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001180 } else {
1181 // else make the attempt anyway - probably giving REQUEST_STARTED below
1182 if (DBG) {
1183 log("special network not available, but try anyway ni=" +
1184 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001185 }
1186 }
1187 }
1188
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001189 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001190
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001191 synchronized(this) {
1192 boolean addToList = true;
1193 if (restoreTimer < 0) {
1194 // In case there is no timer is specified for the feature,
1195 // make sure we don't add duplicate entry with the same request.
1196 for (FeatureUser u : mFeatureUsers) {
1197 if (u.isSameUser(f)) {
1198 // Duplicate user is found. Do not add.
1199 addToList = false;
1200 break;
1201 }
1202 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001203 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001204
1205 if (addToList) mFeatureUsers.add(f);
1206 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1207 // this gets used for per-pid dns when connected
1208 mNetRequestersPids[usedNetworkType].add(currentPid);
1209 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001210 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001211
1212 if (restoreTimer >= 0) {
1213 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1214 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1215 }
1216
1217 if ((ni.isConnectedOrConnecting() == true) &&
1218 !network.isTeardownRequested()) {
1219 if (ni.isConnected() == true) {
1220 final long token = Binder.clearCallingIdentity();
1221 try {
1222 // add the pid-specific dns
1223 handleDnsConfigurationChange(usedNetworkType);
1224 if (VDBG) log("special network already active");
1225 } finally {
1226 Binder.restoreCallingIdentity(token);
1227 }
Wink Saville64e3f782012-07-10 12:37:54 -07001228 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001229 }
1230 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001231 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001232 }
1233
1234 // check if the radio in play can make another contact
1235 // assume if cannot for now
1236
1237 if (DBG) {
1238 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1239 feature);
1240 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001241 if (network.reconnect()) {
1242 return PhoneConstants.APN_REQUEST_STARTED;
1243 } else {
1244 return PhoneConstants.APN_REQUEST_FAILED;
1245 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001246 } else {
1247 // need to remember this unsupported request so we respond appropriately on stop
1248 synchronized(this) {
1249 mFeatureUsers.add(f);
1250 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1251 // this gets used for per-pid dns when connected
1252 mNetRequestersPids[usedNetworkType].add(currentPid);
1253 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001254 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001255 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001256 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001257 }
Wink Saville64e3f782012-07-10 12:37:54 -07001258 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001259 } finally {
1260 if (DBG) {
1261 final long execTime = SystemClock.elapsedRealtime() - startTime;
1262 if (execTime > 250) {
1263 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1264 } else {
1265 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1266 }
1267 }
1268 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001269 }
1270
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001271 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001272 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001273 enforceChangePermission();
1274
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001275 int pid = getCallingPid();
1276 int uid = getCallingUid();
1277
1278 FeatureUser u = null;
1279 boolean found = false;
1280
1281 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001282 for (FeatureUser x : mFeatureUsers) {
1283 if (x.isSameUser(pid, uid, networkType, feature)) {
1284 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001285 found = true;
1286 break;
1287 }
1288 }
1289 }
1290 if (found && u != null) {
1291 // stop regardless of how many other time this proc had called start
1292 return stopUsingNetworkFeature(u, true);
1293 } else {
1294 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001295 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001296 return 1;
1297 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001298 }
1299
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001300 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1301 int networkType = u.mNetworkType;
1302 String feature = u.mFeature;
1303 int pid = u.mPid;
1304 int uid = u.mUid;
1305
1306 NetworkStateTracker tracker = null;
1307 boolean callTeardown = false; // used to carry our decision outside of sync block
1308
Wink Savillea7d56572011-09-21 11:05:43 -07001309 if (VDBG) {
1310 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001311 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001312
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001314 if (DBG) {
1315 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1316 ", net is invalid");
1317 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001318 return -1;
1319 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001320
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001321 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1322 // sync block
1323 synchronized(this) {
1324 // check if this process still has an outstanding start request
1325 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001326 if (VDBG) {
1327 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1328 ", ignoring");
1329 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001330 return 1;
1331 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001332 u.unlinkDeathRecipient();
1333 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1334 // If we care about duplicate requests, check for that here.
1335 //
1336 // This is done to support the extension of a request - the app
1337 // can request we start the network feature again and renew the
1338 // auto-shutoff delay. Normal "stop" calls from the app though
1339 // do not pay attention to duplicate requests - in effect the
1340 // API does not refcount and a single stop will counter multiple starts.
1341 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001342 for (FeatureUser x : mFeatureUsers) {
1343 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001344 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001345 return 1;
1346 }
1347 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001348 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001349
repo syncf5de5572011-07-29 23:55:49 -07001350 // TODO - move to individual network trackers
1351 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1352
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001353 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001354 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001355 if (DBG) {
1356 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1357 " no known tracker for used net type " + usedNetworkType);
1358 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001359 return -1;
1360 }
1361 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001362 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001363 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001364
1365 final long token = Binder.clearCallingIdentity();
1366 try {
1367 reassessPidDns(pid, true);
1368 } finally {
1369 Binder.restoreCallingIdentity(token);
1370 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001371 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001372 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001373 if (VDBG) {
1374 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1375 " others still using it");
1376 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001377 return 1;
1378 }
1379 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001380 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001381 if (DBG) {
1382 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1383 " not a known feature - dropping");
1384 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001385 }
1386 }
Wink Savillea7d56572011-09-21 11:05:43 -07001387
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001388 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001389 if (DBG) {
1390 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1391 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001392 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001393 return 1;
1394 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001395 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001396 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001397 }
1398
1399 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001400 * @deprecated use requestRouteToHostAddress instead
1401 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001402 * Ensure that a network route exists to deliver traffic to the specified
1403 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001404 * @param networkType the type of the network over which traffic to the
1405 * specified host is to be routed
1406 * @param hostAddress the IP address of the host to which the route is
1407 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001408 * @return {@code true} on success, {@code false} on failure
1409 */
1410 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001411 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1412
1413 if (inetAddress == null) {
1414 return false;
1415 }
1416
1417 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1418 }
1419
1420 /**
1421 * Ensure that a network route exists to deliver traffic to the specified
1422 * host via the specified network interface.
1423 * @param networkType the type of the network over which traffic to the
1424 * specified host is to be routed
1425 * @param hostAddress the IP address of the host to which the route is
1426 * desired
1427 * @return {@code true} on success, {@code false} on failure
1428 */
1429 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001430 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001431 if (mProtectedNetworks.contains(networkType)) {
1432 enforceConnectivityInternalPermission();
1433 }
1434
The Android Open Source Project28527d22009-03-03 19:31:44 -08001435 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001436 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 return false;
1438 }
1439 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001440 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001441
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001442 if (tracker == null || (netState != DetailedState.CONNECTED &&
1443 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001444 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001445 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001446 log("requestRouteToHostAddress on down network "
1447 + "(" + networkType + ") - dropped"
1448 + " tracker=" + tracker
1449 + " netState=" + netState
1450 + " isTeardownRequested="
1451 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001452 }
1453 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001454 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001455 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001456 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001457 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001458 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001459 boolean ok = addRouteToAddress(lp, addr);
1460 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1461 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001462 } catch (UnknownHostException e) {
1463 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1464 } finally {
1465 Binder.restoreCallingIdentity(token);
1466 }
Wink Saville32506bc2013-06-29 21:10:57 -07001467 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001468 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001469 }
1470
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001471 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001472 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001473 }
1474
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001475 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001476 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001477 }
1478
Robert Greenwalt98107422011-07-22 11:55:33 -07001479 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001480 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001481 }
1482
1483 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001484 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001485 }
1486
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001487 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1488 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001489 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001490 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001491 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001492 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001493 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001494 if (bestRoute.getGateway().equals(addr)) {
1495 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001496 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001497 } else {
1498 // if we will connect to this through another route, add a direct route
1499 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001500 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001501 }
1502 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001503 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001504 }
1505
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001506 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1507 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001508 if ((lp == null) || (r == null)) {
1509 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001510 return false;
1511 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001512
1513 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001514 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001515 return false;
1516 }
1517
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001518 String ifaceName = r.getInterface();
1519 if(ifaceName == null) {
1520 loge("Error modifying route - no interface name");
1521 return false;
1522 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001523 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001524 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001525 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001526 if (bestRoute.getGateway().equals(r.getGateway())) {
1527 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001528 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001529 } else {
1530 // if we will connect to our gateway through another route, add a direct
1531 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001532 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1533 bestRoute.getGateway(),
1534 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001535 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001536 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001537 }
1538 }
1539 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001540 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001541 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001542 if (toDefaultTable) {
1543 mAddedRoutes.add(r); // only track default table - only one apps can effect
1544 mNetd.addRoute(ifaceName, r);
1545 } else {
1546 mNetd.addSecondaryRoute(ifaceName, r);
1547 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001548 } catch (Exception e) {
1549 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001550 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001551 return false;
1552 }
1553 } else {
1554 // if we remove this one and there are no more like it, then refcount==0 and
1555 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001556 if (toDefaultTable) {
1557 mAddedRoutes.remove(r);
1558 if (mAddedRoutes.contains(r) == false) {
1559 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1560 try {
1561 mNetd.removeRoute(ifaceName, r);
1562 } catch (Exception e) {
1563 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001564 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001565 return false;
1566 }
1567 } else {
1568 if (VDBG) log("not removing " + r + " as it's still in use");
1569 }
1570 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001571 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001572 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001573 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001574 } catch (Exception e) {
1575 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001576 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001577 return false;
1578 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001579 }
1580 }
1581 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001582 }
1583
1584 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001585 * @see ConnectivityManager#getMobileDataEnabled()
1586 */
1587 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001588 // TODO: This detail should probably be in DataConnectionTracker's
1589 // which is where we store the value and maybe make this
1590 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001591 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001592 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1593 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001594 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001595 return retVal;
1596 }
1597
Robert Greenwalt34848c02011-03-25 13:09:25 -07001598 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001599 enforceConnectivityInternalPermission();
1600
Robert Greenwalt34848c02011-03-25 13:09:25 -07001601 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1602 (met ? ENABLED : DISABLED), networkType));
1603 }
1604
1605 private void handleSetDependencyMet(int networkType, boolean met) {
1606 if (mNetTrackers[networkType] != null) {
1607 if (DBG) {
1608 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1609 }
1610 mNetTrackers[networkType].setDependencyMet(met);
1611 }
1612 }
1613
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001614 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1615 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001616 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001617 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001618 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001619 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001620 }
1621
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001622 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001623 // skip update when we've already applied rules
1624 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1625 if (oldRules == uidRules) return;
1626
1627 mUidRules.put(uid, uidRules);
1628 }
1629
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001630 // TODO: notify UID when it has requested targeted updates
1631 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001632
1633 @Override
1634 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001635 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001636 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001637 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001638 }
1639
1640 synchronized (mRulesLock) {
1641 mMeteredIfaces.clear();
1642 for (String iface : meteredIfaces) {
1643 mMeteredIfaces.add(iface);
1644 }
1645 }
1646 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001647
1648 @Override
1649 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1650 // caller is NPMS, since we only register with them
1651 if (LOGD_RULES) {
1652 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1653 }
1654
1655 // kick off connectivity change broadcast for active network, since
1656 // global background policy change is radical.
1657 final int networkType = mActiveDefaultNetwork;
1658 if (isNetworkTypeValid(networkType)) {
1659 final NetworkStateTracker tracker = mNetTrackers[networkType];
1660 if (tracker != null) {
1661 final NetworkInfo info = tracker.getNetworkInfo();
1662 if (info != null && info.isConnected()) {
1663 sendConnectedBroadcast(info);
1664 }
1665 }
1666 }
1667 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001668 };
1669
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001670 /**
1671 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1672 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001673 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001674 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001675 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001676
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001677 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001678 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001679 }
1680
1681 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001682 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001683 if (VDBG) {
1684 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001685 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001686 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1687 }
tk.mun5eee1042012-01-06 10:43:52 +09001688 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1689 if (VDBG) {
1690 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1691 }
1692 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1693 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001694 }
1695
1696 @Override
1697 public void setPolicyDataEnable(int networkType, boolean enabled) {
1698 // only someone like NPMS should only be calling us
1699 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1700
1701 mHandler.sendMessage(mHandler.obtainMessage(
1702 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1703 }
1704
1705 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1706 if (isNetworkTypeValid(networkType)) {
1707 final NetworkStateTracker tracker = mNetTrackers[networkType];
1708 if (tracker != null) {
1709 tracker.setPolicyDataEnable(enabled);
1710 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001711 }
1712 }
1713
The Android Open Source Project28527d22009-03-03 19:31:44 -08001714 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001715 mContext.enforceCallingOrSelfPermission(
1716 android.Manifest.permission.ACCESS_NETWORK_STATE,
1717 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001718 }
1719
1720 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001721 mContext.enforceCallingOrSelfPermission(
1722 android.Manifest.permission.CHANGE_NETWORK_STATE,
1723 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001724 }
1725
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001726 // TODO Make this a special check when it goes public
1727 private void enforceTetherChangePermission() {
1728 mContext.enforceCallingOrSelfPermission(
1729 android.Manifest.permission.CHANGE_NETWORK_STATE,
1730 "ConnectivityService");
1731 }
1732
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001733 private void enforceTetherAccessPermission() {
1734 mContext.enforceCallingOrSelfPermission(
1735 android.Manifest.permission.ACCESS_NETWORK_STATE,
1736 "ConnectivityService");
1737 }
1738
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001739 private void enforceConnectivityInternalPermission() {
1740 mContext.enforceCallingOrSelfPermission(
1741 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1742 "ConnectivityService");
1743 }
1744
The Android Open Source Project28527d22009-03-03 19:31:44 -08001745 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001746 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1747 * network, we ignore it. If it is for the active network, we send out a
1748 * broadcast. But first, we check whether it might be possible to connect
1749 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001750 * @param info the {@code NetworkInfo} for the network
1751 */
1752 private void handleDisconnect(NetworkInfo info) {
1753
Robert Greenwalt2034b912009-08-12 16:08:25 -07001754 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001755
Robert Greenwalt2034b912009-08-12 16:08:25 -07001756 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001757
1758 // Remove idletimer previously setup in {@code handleConnect}
1759 removeDataActivityTracking(prevNetType);
1760
The Android Open Source Project28527d22009-03-03 19:31:44 -08001761 /*
1762 * If the disconnected network is not the active one, then don't report
1763 * this as a loss of connectivity. What probably happened is that we're
1764 * getting the disconnect for a network that we explicitly disabled
1765 * in accordance with network preference policies.
1766 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001767 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001768 List<Integer> pids = mNetRequestersPids[prevNetType];
1769 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001770 // will remove them because the net's no longer connected
1771 // need to do this now as only now do we know the pids and
1772 // can properly null things that are no longer referenced.
1773 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001774 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001775 }
1776
The Android Open Source Project28527d22009-03-03 19:31:44 -08001777 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001778 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001779 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001780 if (info.isFailover()) {
1781 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1782 info.setFailover(false);
1783 }
1784 if (info.getReason() != null) {
1785 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1786 }
1787 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001788 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1789 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001790 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001791
Robert Greenwalt34848c02011-03-25 13:09:25 -07001792 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001793 tryFailover(prevNetType);
1794 if (mActiveDefaultNetwork != -1) {
1795 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001796 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1797 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001798 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001799 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1800 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001801 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001802 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001803
1804 // Reset interface if no other connections are using the same interface
1805 boolean doReset = true;
1806 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1807 if (linkProperties != null) {
1808 String oldIface = linkProperties.getInterfaceName();
1809 if (TextUtils.isEmpty(oldIface) == false) {
1810 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1811 if (networkStateTracker == null) continue;
1812 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1813 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1814 LinkProperties l = networkStateTracker.getLinkProperties();
1815 if (l == null) continue;
1816 if (oldIface.equals(l.getInterfaceName())) {
1817 doReset = false;
1818 break;
1819 }
1820 }
1821 }
1822 }
1823 }
1824
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001825 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001826 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001827
Jeff Sharkey971cd162011-08-29 16:02:57 -07001828 final Intent immediateIntent = new Intent(intent);
1829 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1830 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001831 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001832 /*
1833 * If the failover network is already connected, then immediately send
1834 * out a followup broadcast indicating successful failover
1835 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001836 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001837 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1838 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001839 }
1840 }
1841
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001842 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001843 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001844 * If this is a default network, check if other defaults are available.
1845 * Try to reconnect on all available and let them hash it out when
1846 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001847 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001848 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001849 if (mActiveDefaultNetwork == prevNetType) {
1850 mActiveDefaultNetwork = -1;
1851 }
1852
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001853 // don't signal a reconnect for anything lower or equal priority than our
1854 // current connected default
1855 // TODO - don't filter by priority now - nice optimization but risky
1856// int currentPriority = -1;
1857// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001858// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001859// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001860 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001861 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001862 if (mNetConfigs[checkType] == null) continue;
1863 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001864 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001865
1866// Enabling the isAvailable() optimization caused mobile to not get
1867// selected if it was in the middle of error handling. Specifically
1868// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1869// would not be available and we wouldn't get connected to anything.
1870// So removing the isAvailable() optimization below for now. TODO: This
1871// optimization should work and we need to investigate why it doesn't work.
1872// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1873// complete before it is really complete.
1874// if (!mNetTrackers[checkType].isAvailable()) continue;
1875
Robert Greenwalt34848c02011-03-25 13:09:25 -07001876// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001877
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001878 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1879 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1880 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1881 checkInfo.setFailover(true);
1882 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001883 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001884 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001885 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001886 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001887 }
1888
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001889 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001890 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001891 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1892 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001893 }
1894
Wink Saville4f0de1e2011-08-04 15:01:58 -07001895 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001896 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1897 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001898 }
1899
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001900 private void sendInetConditionBroadcast(NetworkInfo info) {
1901 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1902 }
1903
Wink Saville4f0de1e2011-08-04 15:01:58 -07001904 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001905 if (mLockdownTracker != null) {
1906 info = mLockdownTracker.augmentNetworkInfo(info);
1907 }
1908
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001909 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001910 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001911 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001912 if (info.isFailover()) {
1913 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1914 info.setFailover(false);
1915 }
1916 if (info.getReason() != null) {
1917 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1918 }
1919 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001920 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1921 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001923 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001924 return intent;
1925 }
1926
1927 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1928 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1929 }
1930
1931 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1932 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 }
1934
Haoyu Baib5da5752012-06-20 14:29:57 -07001935 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1936 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1937 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1938 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001939 final long ident = Binder.clearCallingIdentity();
1940 try {
1941 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1942 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1943 } finally {
1944 Binder.restoreCallingIdentity(ident);
1945 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001946 }
1947
The Android Open Source Project28527d22009-03-03 19:31:44 -08001948 /**
1949 * Called when an attempt to fail over to another network has failed.
1950 * @param info the {@link NetworkInfo} for the failed network
1951 */
1952 private void handleConnectionFailure(NetworkInfo info) {
1953 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001954
Robert Greenwalt2034b912009-08-12 16:08:25 -07001955 String reason = info.getReason();
1956 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001957
Robert Greenwalte981bc52010-10-08 16:35:52 -07001958 String reasonText;
1959 if (reason == null) {
1960 reasonText = ".";
1961 } else {
1962 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001963 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001964 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001965
1966 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001967 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001968 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001969 if (getActiveNetworkInfo() == null) {
1970 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1971 }
1972 if (reason != null) {
1973 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1974 }
1975 if (extraInfo != null) {
1976 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1977 }
1978 if (info.isFailover()) {
1979 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1980 info.setFailover(false);
1981 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001982
Robert Greenwalt34848c02011-03-25 13:09:25 -07001983 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001984 tryFailover(info.getType());
1985 if (mActiveDefaultNetwork != -1) {
1986 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001987 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1988 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001989 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001990 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1991 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001992 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001993
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001994 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001995
1996 final Intent immediateIntent = new Intent(intent);
1997 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1998 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001999 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002000 /*
2001 * If the failover network is already connected, then immediately send
2002 * out a followup broadcast indicating successful failover
2003 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002004 if (mActiveDefaultNetwork != -1) {
2005 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002006 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002007 }
2008
2009 private void sendStickyBroadcast(Intent intent) {
2010 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002011 if (!mSystemReady) {
2012 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002013 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002014 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002015 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002016 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002017 }
2018
Dianne Hackborne588ca12012-09-04 18:48:37 -07002019 final long ident = Binder.clearCallingIdentity();
2020 try {
2021 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002025 }
2026 }
2027
Wink Saville4f0de1e2011-08-04 15:01:58 -07002028 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2029 if (delayMs <= 0) {
2030 sendStickyBroadcast(intent);
2031 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002032 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002033 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2034 + intent.getAction());
2035 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002036 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2037 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2038 }
2039 }
2040
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002041 void systemReady() {
2042 synchronized(this) {
2043 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002044 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002045 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002046 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002047 }
2048 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002049 // load the global proxy at startup
2050 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002051
2052 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2053 // for user to unlock device.
2054 if (!updateLockdownVpn()) {
2055 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2056 mContext.registerReceiver(mUserPresentReceiver, filter);
2057 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002058 }
2059
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002060 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2061 @Override
2062 public void onReceive(Context context, Intent intent) {
2063 // Try creating lockdown tracker, since user present usually means
2064 // unlocked keystore.
2065 if (updateLockdownVpn()) {
2066 mContext.unregisterReceiver(this);
2067 }
2068 }
2069 };
2070
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002071 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2072 if ((type != mNetworkPreference &&
2073 mNetConfigs[mActiveDefaultNetwork].priority >
2074 mNetConfigs[type].priority) ||
2075 mNetworkPreference == mActiveDefaultNetwork) return false;
2076 return true;
2077 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002079 private void handleConnect(NetworkInfo info) {
2080 final int newNetType = info.getType();
2081
2082 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002083
The Android Open Source Project28527d22009-03-03 19:31:44 -08002084 // snapshot isFailover, because sendConnectedBroadcast() resets it
2085 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002086 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002087 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088
Robert Greenwalt2034b912009-08-12 16:08:25 -07002089 // if this is a default net and other default is running
2090 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002091 if (mNetConfigs[newNetType].isDefault()) {
2092 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2093 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002094 // tear down the other
2095 NetworkStateTracker otherNet =
2096 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002097 if (DBG) {
2098 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002099 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002100 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002101 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002102 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002103 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002104 return;
2105 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002106 } else {
2107 // don't accept this one
2108 if (VDBG) {
2109 log("Not broadcasting CONNECT_ACTION " +
2110 "to torn down network " + info.getTypeName());
2111 }
2112 teardown(thisNet);
2113 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002114 }
2115 }
2116 synchronized (ConnectivityService.this) {
2117 // have a new default network, release the transition wakelock in a second
2118 // if it's held. The second pause is to allow apps to reconnect over the
2119 // new network
2120 if (mNetTransitionWakeLock.isHeld()) {
2121 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002122 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002123 mNetTransitionWakeLockSerialNumber, 0),
2124 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002125 }
2126 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002127 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002128 // this will cause us to come up initially as unconnected and switching
2129 // to connected after our normal pause unless somebody reports us as reall
2130 // disconnected
2131 mDefaultInetConditionPublished = 0;
2132 mDefaultConnectionSequence++;
2133 mInetConditionChangeInFlight = false;
2134 // Don't do this - if we never sign in stay, grey
2135 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002136 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002137 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002138 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002139 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002140 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002141
2142 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002143 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002144 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002145 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002146 } catch (RemoteException e) {
2147 // ignored; service lives in system_server
2148 }
2149 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002150 }
2151
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002152 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2153 if (DBG) log("Captive portal check " + info);
2154 int type = info.getType();
2155 final NetworkStateTracker thisNet = mNetTrackers[type];
2156 if (mNetConfigs[type].isDefault()) {
2157 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2158 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2159 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002160 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002161 return;
2162 } else {
2163 if (DBG) log("Tear down low priority net " + info.getTypeName());
2164 teardown(thisNet);
2165 return;
2166 }
2167 }
2168 }
2169
2170 thisNet.captivePortalCheckComplete();
2171 }
2172
2173 /** @hide */
2174 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002175 enforceConnectivityInternalPermission();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002176 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002177 }
2178
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002180 * Setup data activity tracking for the given network interface.
2181 *
2182 * Every {@code setupDataActivityTracking} should be paired with a
2183 * {@link removeDataActivityTracking} for cleanup.
2184 */
2185 private void setupDataActivityTracking(int type) {
2186 final NetworkStateTracker thisNet = mNetTrackers[type];
2187 final String iface = thisNet.getLinkProperties().getInterfaceName();
2188
2189 final int timeout;
2190
2191 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002192 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2193 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002194 0);
2195 // Canonicalize mobile network type
2196 type = ConnectivityManager.TYPE_MOBILE;
2197 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002198 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2199 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002200 0);
2201 } else {
2202 // do not track any other networks
2203 timeout = 0;
2204 }
2205
2206 if (timeout > 0 && iface != null) {
2207 try {
2208 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2209 } catch (RemoteException e) {
2210 }
2211 }
2212 }
2213
2214 /**
2215 * Remove data activity tracking when network disconnects.
2216 */
2217 private void removeDataActivityTracking(int type) {
2218 final NetworkStateTracker net = mNetTrackers[type];
2219 final String iface = net.getLinkProperties().getInterfaceName();
2220
2221 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2222 ConnectivityManager.TYPE_WIFI == type)) {
2223 try {
2224 // the call fails silently if no idletimer setup for this interface
2225 mNetd.removeIdleTimer(iface);
2226 } catch (RemoteException e) {
2227 }
2228 }
2229 }
2230
2231 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002232 * After a change in the connectivity state of a network. We're mainly
2233 * concerned with making sure that the list of DNS servers is set up
2234 * according to which networks are connected, and ensuring that the
2235 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002236 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002237 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002238 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2239
The Android Open Source Project28527d22009-03-03 19:31:44 -08002240 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002241 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002242 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002243 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002244 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002245
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002246 LinkProperties curLp = mCurrentLinkProperties[netType];
2247 LinkProperties newLp = null;
2248
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002249 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002250 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002251 if (VDBG) {
2252 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2253 " doReset=" + doReset + " resetMask=" + resetMask +
2254 "\n curLp=" + curLp +
2255 "\n newLp=" + newLp);
2256 }
2257
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002258 if (curLp != null) {
2259 if (curLp.isIdenticalInterfaceName(newLp)) {
2260 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2261 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2262 for (LinkAddress linkAddr : car.removed) {
2263 if (linkAddr.getAddress() instanceof Inet4Address) {
2264 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2265 }
2266 if (linkAddr.getAddress() instanceof Inet6Address) {
2267 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2268 }
Wink Saville051a6642011-07-13 13:44:13 -07002269 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002270 if (DBG) {
2271 log("handleConnectivityChange: addresses changed" +
2272 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2273 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002274 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002275 } else {
2276 if (DBG) {
2277 log("handleConnectivityChange: address are the same reset per doReset" +
2278 " linkProperty[" + netType + "]:" +
2279 " resetMask=" + resetMask);
2280 }
Wink Saville051a6642011-07-13 13:44:13 -07002281 }
2282 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002283 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002284 if (DBG) {
2285 log("handleConnectivityChange: interface not not equivalent reset both" +
2286 " linkProperty[" + netType + "]:" +
2287 " resetMask=" + resetMask);
2288 }
Wink Saville051a6642011-07-13 13:44:13 -07002289 }
Wink Saville051a6642011-07-13 13:44:13 -07002290 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002291 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002292 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002293 }
2294 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002295 if (VDBG) {
2296 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2297 " doReset=" + doReset + " resetMask=" + resetMask +
2298 "\n curLp=" + curLp +
2299 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002300 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002301 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002302 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002303 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002304
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002305 if (resetMask != 0 || resetDns) {
Robert Greenwalt4398f342013-05-23 18:33:06 -07002306 if (curLp != null) {
2307 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002308 if (TextUtils.isEmpty(iface) == false) {
2309 if (resetMask != 0) {
2310 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2311 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002312
Lorenzo Colitti63839822013-03-20 19:22:58 +09002313 // Tell VPN the interface is down. It is a temporary
2314 // but effective fix to make VPN aware of the change.
2315 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2316 mVpn.interfaceStatusChanged(iface, false);
2317 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002318 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002319 if (resetDns) {
2320 flushVmDnsCache();
2321 if (VDBG) log("resetting DNS cache for " + iface);
2322 try {
2323 mNetd.flushInterfaceDnsCache(iface);
2324 } catch (Exception e) {
2325 // never crash - catch them all
2326 if (DBG) loge("Exception resetting dns cache: " + e);
2327 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002328 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002329 } else {
2330 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002331 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002332 }
2333 }
2334 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002335
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002336 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002337 NetworkStateTracker tracker = mNetTrackers[netType];
2338 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002339 // If the connection was previously using clat, but is not using it now, stop the clat
2340 // daemon. Normally, this happens automatically when the connection disconnects, but if
2341 // the disconnect is not reported, or if the connection's LinkProperties changed for
2342 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2343 // still be running. If it's not running, then stopping it is a no-op.
2344 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2345 mClat.stopClat();
2346 }
2347 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002348 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2349 mClat.startClat(tracker);
2350 } else {
2351 mClat.stopClat();
2352 }
2353 }
2354
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002355 // TODO: Temporary notifying upstread change to Tethering.
2356 // @see bug/4455071
2357 /** Notify TetheringService if interface name has been changed. */
2358 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002359 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002360 if (isTetheringSupported()) {
2361 mTethering.handleTetherIfaceChange();
2362 }
2363 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002364 }
2365
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002366 /**
2367 * Add and remove routes using the old properties (null if not previously connected),
2368 * new properties (null if becoming disconnected). May even be double null, which
2369 * is a noop.
2370 * Uses isLinkDefault to determine if default routes should be set or conversely if
2371 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002372 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002373 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002374 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2375 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002376 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002377 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2378 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002379 if (curLp != null) {
2380 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002381 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002382 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002383 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002384 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002385 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002386 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002387
Robert Greenwalt8d777252011-08-15 12:31:55 -07002388 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2389
Robert Greenwalt98107422011-07-22 11:55:33 -07002390 for (RouteInfo r : routeDiff.removed) {
2391 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002392 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2393 }
2394 if (isLinkDefault == false) {
2395 // remove from a secondary route table
2396 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002397 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002398 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002399
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002400 if (!isLinkDefault) {
2401 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002402 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002403 // routes changed - remove all old dns entries and add new
2404 if (curLp != null) {
2405 for (InetAddress oldDns : curLp.getDnses()) {
2406 removeRouteToAddress(curLp, oldDns);
2407 }
2408 }
2409 if (newLp != null) {
2410 for (InetAddress newDns : newLp.getDnses()) {
2411 addRouteToAddress(newLp, newDns);
2412 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002413 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002414 } else {
2415 // no change in routes, check for change in dns themselves
2416 for (InetAddress oldDns : dnsDiff.removed) {
2417 removeRouteToAddress(curLp, oldDns);
2418 }
2419 for (InetAddress newDns : dnsDiff.added) {
2420 addRouteToAddress(newLp, newDns);
2421 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002422 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002423 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002424
2425 for (RouteInfo r : routeDiff.added) {
2426 if (isLinkDefault || ! r.isDefaultRoute()) {
2427 addRoute(newLp, r, TO_DEFAULT_TABLE);
2428 } else {
2429 // add to a secondary route table
2430 addRoute(newLp, r, TO_SECONDARY_TABLE);
2431
2432 // many radios add a default route even when we don't want one.
2433 // remove the default route unless somebody else has asked for it
2434 String ifaceName = newLp.getInterfaceName();
2435 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2436 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2437 try {
2438 mNetd.removeRoute(ifaceName, r);
2439 } catch (Exception e) {
2440 // never crash - catch them all
2441 if (DBG) loge("Exception trying to remove a route: " + e);
2442 }
2443 }
2444 }
2445 }
2446
Robert Greenwalt8d777252011-08-15 12:31:55 -07002447 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002448 }
2449
2450
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002451 /**
2452 * Reads the network specific TCP buffer sizes from SystemProperties
2453 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2454 * wide use
2455 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002456 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002457 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002458 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002459
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002460 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002461 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002462
2463 // Setting to default values so we won't be stuck to previous values
2464 key = "net.tcp.buffersize.default";
2465 bufferSizes = SystemProperties.get(key);
2466 }
2467
2468 // Set values in kernel
2469 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002470 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002471 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002472 + "] which comes from [" + key + "]");
2473 }
2474 setBufferSize(bufferSizes);
2475 }
2476 }
2477
2478 /**
2479 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2480 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2481 *
2482 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2483 * writeMin, writeInitial, writeMax"
2484 */
2485 private void setBufferSize(String bufferSizes) {
2486 try {
2487 String[] values = bufferSizes.split(",");
2488
2489 if (values.length == 6) {
2490 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002491 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2492 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2493 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2494 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2495 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2496 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002497 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002498 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002499 }
2500 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002501 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002502 }
2503 }
2504
Robert Greenwalt2034b912009-08-12 16:08:25 -07002505 /**
2506 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2507 * on the highest priority active net which this process requested.
2508 * If there aren't any, clear it out
2509 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002510 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002511 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002512 if (VDBG) log("reassessPidDns for pid " + pid);
2513 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002514 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002515 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002516 continue;
2517 }
2518 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002519 if (nt.getNetworkInfo().isConnected() &&
2520 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002521 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002522 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002523 if (mNetRequestersPids[i].contains(myPid)) {
2524 try {
2525 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2526 } catch (Exception e) {
2527 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002528 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002529 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002530 }
2531 }
2532 }
2533 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002534 try {
2535 mNetd.clearDnsInterfaceForPid(pid);
2536 } catch (Exception e) {
2537 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002538 }
2539 }
2540
Mattias Falkd697aa22011-08-23 14:15:13 +02002541 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002542 /*
2543 * Tell the VMs to toss their DNS caches
2544 */
2545 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2546 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002547 /*
2548 * Connectivity events can happen before boot has completed ...
2549 */
2550 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002551 final long ident = Binder.clearCallingIdentity();
2552 try {
2553 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2554 } finally {
2555 Binder.restoreCallingIdentity(ident);
2556 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002557 }
2558
Chia-chi Yehcc844502011-07-14 18:01:57 -07002559 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002560 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002561 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002562 int last = 0;
2563 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002564 dnses = new ArrayList();
2565 dnses.add(mDefaultDns);
2566 if (DBG) {
2567 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002568 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002569 }
2570
Mattias Falkd697aa22011-08-23 14:15:13 +02002571 try {
2572 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2573 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002574 for (InetAddress dns : dnses) {
2575 ++last;
2576 String key = "net.dns" + last;
2577 String value = dns.getHostAddress();
2578 SystemProperties.set(key, value);
2579 }
2580 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2581 String key = "net.dns" + i;
2582 SystemProperties.set(key, "");
2583 }
2584 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002585 } catch (Exception e) {
2586 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002587 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002588 }
2589
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002590 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002591 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002592 NetworkStateTracker nt = mNetTrackers[netType];
2593 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002594 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002595 if (p == null) return;
2596 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002597 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002598 String network = nt.getNetworkInfo().getTypeName();
2599 synchronized (mDnsLock) {
2600 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002601 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002602 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002603 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002604 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002605 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002606 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002607 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002608 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002609 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002610 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002611 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002612 List<Integer> pids = mNetRequestersPids[netType];
2613 for (Integer pid : pids) {
2614 try {
2615 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2616 } catch (Exception e) {
2617 Slog.e(TAG, "exception setting interface for pid: " + e);
2618 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002619 }
2620 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002621 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002622 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002623 }
2624
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002625 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002626 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2627 NETWORK_RESTORE_DELAY_PROP_NAME);
2628 if(restoreDefaultNetworkDelayStr != null &&
2629 restoreDefaultNetworkDelayStr.length() != 0) {
2630 try {
2631 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2632 } catch (NumberFormatException e) {
2633 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002634 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002635 // if the system property isn't set, use the value for the apn type
2636 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2637
2638 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2639 (mNetConfigs[networkType] != null)) {
2640 ret = mNetConfigs[networkType].restoreTime;
2641 }
2642 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002643 }
2644
2645 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002646 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2647 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002648 if (mContext.checkCallingOrSelfPermission(
2649 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002650 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002651 pw.println("Permission Denial: can't dump ConnectivityService " +
2652 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2653 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002654 return;
2655 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002656
2657 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002658 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002659 for (int i = 0; i < mNetTrackers.length; i++) {
2660 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002661 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002662 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2663 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002664 if (nst.getNetworkInfo().isConnected()) {
2665 pw.println("Active network: " + nst.getNetworkInfo().
2666 getTypeName());
2667 }
2668 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002669 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002670 pw.println(nst);
2671 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002672 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002673 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002674 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002675
2676 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002677 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002678 for (int net : mPriorityList) {
2679 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002680 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002681 pidString = pidString + pid.toString() + ", ";
2682 }
2683 pw.println(pidString);
2684 }
2685 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002686 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002687
2688 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002689 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002690 for (Object requester : mFeatureUsers) {
2691 pw.println(requester.toString());
2692 }
2693 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002694 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002695
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002696 synchronized (this) {
2697 pw.println("NetworkTranstionWakeLock is currently " +
2698 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2699 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2700 }
2701 pw.println();
2702
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002703 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002704
2705 if (mInetLog != null) {
2706 pw.println();
2707 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002708 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002709 for(int i = 0; i < mInetLog.size(); i++) {
2710 pw.println(mInetLog.get(i));
2711 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002712 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002713 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002714 }
2715
Robert Greenwalt2034b912009-08-12 16:08:25 -07002716 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002717 private class NetworkStateTrackerHandler extends Handler {
2718 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002719 super(looper);
2720 }
2721
The Android Open Source Project28527d22009-03-03 19:31:44 -08002722 @Override
2723 public void handleMessage(Message msg) {
2724 NetworkInfo info;
2725 switch (msg.what) {
2726 case NetworkStateTracker.EVENT_STATE_CHANGED:
2727 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002728 int type = info.getType();
2729 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002730
Wink Savillea7d56572011-09-21 11:05:43 -07002731 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2732 (state == NetworkInfo.State.DISCONNECTED)) {
2733 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002734 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002735 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002736 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002737
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002738 EventLogTags.writeConnectivityStateChanged(
2739 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002740
2741 if (info.getDetailedState() ==
2742 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002743 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002744 } else if (info.getDetailedState() ==
2745 DetailedState.CAPTIVE_PORTAL_CHECK) {
2746 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002747 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002748 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002749 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002750 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002751 // the logic here is, handle SUSPENDED the same as
2752 // DISCONNECTED. The only difference being we are
2753 // broadcasting an intent with NetworkInfo that's
2754 // suspended. This allows the applications an
2755 // opportunity to handle DISCONNECTED and SUSPENDED
2756 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002757 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002758 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002759 handleConnect(info);
2760 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002761 if (mLockdownTracker != null) {
2762 mLockdownTracker.onNetworkInfoChanged(info);
2763 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002764 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002765 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002766 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002767 // TODO: Temporary allowing network configuration
2768 // change not resetting sockets.
2769 // @see bug/4455071
2770 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002771 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002772 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2773 info = (NetworkInfo) msg.obj;
2774 type = info.getType();
2775 updateNetworkSettings(mNetTrackers[type]);
2776 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002777 }
2778 }
2779 }
2780
2781 private class InternalHandler extends Handler {
2782 public InternalHandler(Looper looper) {
2783 super(looper);
2784 }
2785
2786 @Override
2787 public void handleMessage(Message msg) {
2788 NetworkInfo info;
2789 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002790 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002791 String causedBy = null;
2792 synchronized (ConnectivityService.this) {
2793 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2794 mNetTransitionWakeLock.isHeld()) {
2795 mNetTransitionWakeLock.release();
2796 causedBy = mNetTransitionWakeLockCausedBy;
2797 }
2798 }
2799 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002800 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002801 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002802 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002803 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002804 FeatureUser u = (FeatureUser)msg.obj;
2805 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002806 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002807 case EVENT_INET_CONDITION_CHANGE:
2808 {
2809 int netType = msg.arg1;
2810 int condition = msg.arg2;
2811 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002812 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002813 }
2814 case EVENT_INET_CONDITION_HOLD_END:
2815 {
2816 int netType = msg.arg1;
2817 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00002818 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002819 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002820 }
2821 case EVENT_SET_NETWORK_PREFERENCE:
2822 {
2823 int preference = msg.arg1;
2824 handleSetNetworkPreference(preference);
2825 break;
2826 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002827 case EVENT_SET_MOBILE_DATA:
2828 {
2829 boolean enabled = (msg.arg1 == ENABLED);
2830 handleSetMobileData(enabled);
2831 break;
2832 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002833 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2834 {
2835 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002836 break;
2837 }
2838 case EVENT_SET_DEPENDENCY_MET:
2839 {
2840 boolean met = (msg.arg1 == ENABLED);
2841 handleSetDependencyMet(msg.arg2, met);
2842 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002843 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002844 case EVENT_RESTORE_DNS:
2845 {
2846 if (mActiveDefaultNetwork != -1) {
2847 handleDnsConfigurationChange(mActiveDefaultNetwork);
2848 }
2849 break;
2850 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002851 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2852 {
2853 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002854 sendStickyBroadcast(intent);
2855 break;
2856 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002857 case EVENT_SET_POLICY_DATA_ENABLE: {
2858 final int networkType = msg.arg1;
2859 final boolean enabled = msg.arg2 == ENABLED;
2860 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002861 break;
2862 }
2863 case EVENT_VPN_STATE_CHANGED: {
2864 if (mLockdownTracker != null) {
2865 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2866 }
2867 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002868 }
Wink Saville32506bc2013-06-29 21:10:57 -07002869 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2870 int tag = mEnableFailFastMobileDataTag.get();
2871 if (msg.arg1 == tag) {
2872 MobileDataStateTracker mobileDst =
2873 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2874 if (mobileDst != null) {
2875 mobileDst.setEnableFailFastMobileData(msg.arg2);
2876 }
2877 } else {
2878 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2879 + " != tag:" + tag);
2880 }
2881 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002882 }
2883 }
2884 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002885
2886 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002887 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002888 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002889
2890 if (isTetheringSupported()) {
2891 return mTethering.tether(iface);
2892 } else {
2893 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2894 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002895 }
2896
2897 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002898 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002899 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002900
2901 if (isTetheringSupported()) {
2902 return mTethering.untether(iface);
2903 } else {
2904 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2905 }
2906 }
2907
2908 // javadoc from interface
2909 public int getLastTetherError(String iface) {
2910 enforceTetherAccessPermission();
2911
2912 if (isTetheringSupported()) {
2913 return mTethering.getLastTetherError(iface);
2914 } else {
2915 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2916 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002917 }
2918
2919 // TODO - proper iface API for selection by property, inspection, etc
2920 public String[] getTetherableUsbRegexs() {
2921 enforceTetherAccessPermission();
2922 if (isTetheringSupported()) {
2923 return mTethering.getTetherableUsbRegexs();
2924 } else {
2925 return new String[0];
2926 }
2927 }
2928
2929 public String[] getTetherableWifiRegexs() {
2930 enforceTetherAccessPermission();
2931 if (isTetheringSupported()) {
2932 return mTethering.getTetherableWifiRegexs();
2933 } else {
2934 return new String[0];
2935 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002936 }
2937
Danica Chang96567052010-08-11 14:54:43 -07002938 public String[] getTetherableBluetoothRegexs() {
2939 enforceTetherAccessPermission();
2940 if (isTetheringSupported()) {
2941 return mTethering.getTetherableBluetoothRegexs();
2942 } else {
2943 return new String[0];
2944 }
2945 }
2946
Mike Lockwooded4a1742011-07-19 13:04:47 -07002947 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002948 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002949 if (isTetheringSupported()) {
2950 return mTethering.setUsbTethering(enable);
2951 } else {
2952 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2953 }
2954 }
2955
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002956 // TODO - move iface listing, queries, etc to new module
2957 // javadoc from interface
2958 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002959 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002960 return mTethering.getTetherableIfaces();
2961 }
2962
2963 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002964 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002965 return mTethering.getTetheredIfaces();
2966 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002967
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002968 @Override
2969 public String[] getTetheredIfacePairs() {
2970 enforceTetherAccessPermission();
2971 return mTethering.getTetheredIfacePairs();
2972 }
2973
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002974 public String[] getTetheringErroredIfaces() {
2975 enforceTetherAccessPermission();
2976 return mTethering.getErroredIfaces();
2977 }
2978
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002979 // if ro.tether.denied = true we default to no tethering
2980 // gservices could set the secure setting to 1 though to enable it on a build where it
2981 // had previously been turned off.
2982 public boolean isTetheringSupported() {
2983 enforceTetherAccessPermission();
2984 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07002985 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2986 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002987 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002988 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002989
2990 // An API NetworkStateTrackers can call when they lose their network.
2991 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2992 // whichever happens first. The timer is started by the first caller and not
2993 // restarted by subsequent callers.
2994 public void requestNetworkTransitionWakelock(String forWhom) {
2995 enforceConnectivityInternalPermission();
2996 synchronized (this) {
2997 if (mNetTransitionWakeLock.isHeld()) return;
2998 mNetTransitionWakeLockSerialNumber++;
2999 mNetTransitionWakeLock.acquire();
3000 mNetTransitionWakeLockCausedBy = forWhom;
3001 }
3002 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003003 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003004 mNetTransitionWakeLockSerialNumber, 0),
3005 mNetTransitionWakeLockTimeout);
3006 return;
3007 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003008
Robert Greenwalt986c7412010-09-08 15:24:47 -07003009 // 100 percent is full good, 0 is full bad.
3010 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003011 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003012 mContext.enforceCallingOrSelfPermission(
3013 android.Manifest.permission.STATUS_BAR,
3014 "ConnectivityService");
3015
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003016 if (DBG) {
3017 int pid = getCallingPid();
3018 int uid = getCallingUid();
3019 String s = pid + "(" + uid + ") reports inet is " +
3020 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3021 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3022 mInetLog.add(s);
3023 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3024 mInetLog.remove(0);
3025 }
3026 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003027 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003028 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3029 }
3030
3031 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003032 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003033 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003034 return;
3035 }
3036 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003037 if (DBG) log("handleInetConditionChange: net=" + netType +
3038 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003039 return;
3040 }
Wink Savillea7d56572011-09-21 11:05:43 -07003041 if (VDBG) {
3042 log("handleInetConditionChange: net=" +
3043 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003044 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003045 }
Wink Saville151eaa62013-01-31 00:30:13 +00003046 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003047 int delay;
3048 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003049 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003050 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003051 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003052 delay = Settings.Global.getInt(mContext.getContentResolver(),
3053 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003054 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003055 delay = Settings.Global.getInt(mContext.getContentResolver(),
3056 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003057 }
3058 mInetConditionChangeInFlight = true;
3059 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003060 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003061 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003062 // we've set the new condition, when this hold ends that will get picked up
3063 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003064 }
3065 }
3066
Wink Saville151eaa62013-01-31 00:30:13 +00003067 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003068 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003069 log("handleInetConditionHoldEnd: net=" + netType +
3070 ", condition=" + mDefaultInetCondition +
3071 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003072 }
3073 mInetConditionChangeInFlight = false;
3074
3075 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003076 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003077 return;
3078 }
3079 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003080 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003081 return;
3082 }
Wink Saville151eaa62013-01-31 00:30:13 +00003083 // TODO: Figure out why this optimization sometimes causes a
3084 // change in mDefaultInetCondition to be missed and the
3085 // UI to not be updated.
3086 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3087 // if (DBG) log("no change in condition - aborting");
3088 // return;
3089 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003090 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3091 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003092 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003093 return;
3094 }
Wink Saville151eaa62013-01-31 00:30:13 +00003095 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003096 sendInetConditionBroadcast(networkInfo);
3097 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003098 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003099
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003100 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003101 // this information is already available as a world read/writable jvm property
3102 // so this API change wouldn't have a benifit. It also breaks the passing
3103 // of proxy info to all the JVMs.
3104 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003105 synchronized (mProxyLock) {
3106 if (mGlobalProxy != null) return mGlobalProxy;
3107 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003108 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003109 }
3110
3111 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003112 enforceConnectivityInternalPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003113 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003114 if (proxyProperties == mGlobalProxy) return;
3115 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3116 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3117
3118 String host = "";
3119 int port = 0;
3120 String exclList = "";
3121 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3122 mGlobalProxy = new ProxyProperties(proxyProperties);
3123 host = mGlobalProxy.getHost();
3124 port = mGlobalProxy.getPort();
3125 exclList = mGlobalProxy.getExclusionList();
3126 } else {
3127 mGlobalProxy = null;
3128 }
3129 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003130 final long token = Binder.clearCallingIdentity();
3131 try {
3132 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3133 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3134 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3135 exclList);
3136 } finally {
3137 Binder.restoreCallingIdentity(token);
3138 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003139 }
3140
3141 if (mGlobalProxy == null) {
3142 proxyProperties = mDefaultProxy;
3143 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003144 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003145 }
3146
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003147 private void loadGlobalProxy() {
3148 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003149 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3150 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3151 String exclList = Settings.Global.getString(res,
3152 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003153 if (!TextUtils.isEmpty(host)) {
3154 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003155 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003156 mGlobalProxy = proxyProperties;
3157 }
3158 }
3159 }
3160
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003161 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003162 // this information is already available as a world read/writable jvm property
3163 // so this API change wouldn't have a benifit. It also breaks the passing
3164 // of proxy info to all the JVMs.
3165 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003166 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003167 return mGlobalProxy;
3168 }
3169 }
3170
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003171 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3172 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3173 proxy = null;
3174 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003175 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003176 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003177 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003178 mDefaultProxy = proxy;
3179
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003180 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003181 if (!mDefaultProxyDisabled) {
3182 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003183 }
3184 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003185 }
3186
3187 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003188 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3189 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003190 if (!TextUtils.isEmpty(proxy)) {
3191 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003192 if (data.length == 0) {
3193 return;
3194 }
3195
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003196 String proxyHost = data[0];
3197 int proxyPort = 8080;
3198 if (data.length > 1) {
3199 try {
3200 proxyPort = Integer.parseInt(data[1]);
3201 } catch (NumberFormatException e) {
3202 return;
3203 }
3204 }
3205 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3206 setGlobalProxy(p);
Andreas Huber23bff232013-05-28 15:17:37 -07003207 } else {
3208 setGlobalProxy(null);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003209 }
3210 }
3211
3212 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003213 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003214 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003215 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003216 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3217 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003218 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003219 final long ident = Binder.clearCallingIdentity();
3220 try {
3221 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3222 } finally {
3223 Binder.restoreCallingIdentity(ident);
3224 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003225 }
3226
3227 private static class SettingsObserver extends ContentObserver {
3228 private int mWhat;
3229 private Handler mHandler;
3230 SettingsObserver(Handler handler, int what) {
3231 super(handler);
3232 mHandler = handler;
3233 mWhat = what;
3234 }
3235
3236 void observe(Context context) {
3237 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003238 resolver.registerContentObserver(Settings.Global.getUriFor(
3239 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003240 }
3241
3242 @Override
3243 public void onChange(boolean selfChange) {
3244 mHandler.obtainMessage(mWhat).sendToTarget();
3245 }
3246 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003247
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003248 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003249 Slog.d(TAG, s);
3250 }
3251
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003252 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003253 Slog.e(TAG, s);
3254 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003255
repo syncf5de5572011-07-29 23:55:49 -07003256 int convertFeatureToNetworkType(int networkType, String feature) {
3257 int usedNetworkType = networkType;
3258
3259 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3260 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3261 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3262 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3263 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3264 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3265 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3266 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3267 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3268 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3269 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3270 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3271 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3272 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3273 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3274 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3275 } else {
3276 Slog.e(TAG, "Can't match any mobile netTracker!");
3277 }
3278 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3279 if (TextUtils.equals(feature, "p2p")) {
3280 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3281 } else {
3282 Slog.e(TAG, "Can't match any wifi netTracker!");
3283 }
3284 } else {
3285 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003286 }
repo syncf5de5572011-07-29 23:55:49 -07003287 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003288 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003289
3290 private static <T> T checkNotNull(T value, String message) {
3291 if (value == null) {
3292 throw new NullPointerException(message);
3293 }
3294 return value;
3295 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003296
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003297 /**
3298 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003299 * VpnBuilder and not available in ConnectivityManager. Permissions
3300 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003301 * @hide
3302 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003303 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003304 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003305 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003306 try {
3307 int type = mActiveDefaultNetwork;
Robert Greenwalt15a41532012-08-21 19:27:00 -07003308 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003309 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3310 return true;
3311 }
3312 } catch (Exception e) {
3313 // ignore
3314 } finally {
3315 try {
3316 socket.close();
3317 } catch (Exception e) {
3318 // ignore
3319 }
3320 }
3321 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003322 }
3323
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003324 /**
3325 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003326 * and not available in ConnectivityManager. Permissions are checked
3327 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003328 * @hide
3329 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003330 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003331 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003332 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003333 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003334 }
3335
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003336 /**
3337 * Configure a TUN interface and return its file descriptor. Parameters
3338 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003339 * and not available in ConnectivityManager. Permissions are checked in
3340 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003341 * @hide
3342 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003343 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003344 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003345 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003346 return mVpn.establish(config);
3347 }
3348
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003349 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003350 * Start legacy VPN, controlling native daemons as needed. Creates a
3351 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003352 */
3353 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003354 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003355 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003356 final LinkProperties egress = getActiveLinkProperties();
3357 if (egress == null) {
3358 throw new IllegalStateException("Missing active network connection");
3359 }
3360 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003361 }
3362
3363 /**
3364 * Return the information of the ongoing legacy VPN. This method is used
3365 * by VpnSettings and not available in ConnectivityManager. Permissions
3366 * are checked in Vpn class.
3367 * @hide
3368 */
3369 @Override
3370 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003371 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003372 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003373 }
3374
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003375 /**
3376 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3377 * through NetworkStateTracker since it works differently. For example, it
3378 * needs to override DNS servers but never takes the default routes. It
3379 * relies on another data network, and it could keep existing connections
3380 * alive after reconnecting, switching between networks, or even resuming
3381 * from deep sleep. Calls from applications should be done synchronously
3382 * to avoid race conditions. As these are all hidden APIs, refactoring can
3383 * be done whenever a better abstraction is developed.
3384 */
3385 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003386 private VpnCallback() {
3387 }
3388
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003389 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003390 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003391 }
3392
Chia-chi Yehcc844502011-07-14 18:01:57 -07003393 public void override(List<String> dnsServers, List<String> searchDomains) {
3394 if (dnsServers == null) {
3395 restore();
3396 return;
3397 }
3398
3399 // Convert DNS servers into addresses.
3400 List<InetAddress> addresses = new ArrayList<InetAddress>();
3401 for (String address : dnsServers) {
3402 // Double check the addresses and remove invalid ones.
3403 try {
3404 addresses.add(InetAddress.parseNumericAddress(address));
3405 } catch (Exception e) {
3406 // ignore
3407 }
3408 }
3409 if (addresses.isEmpty()) {
3410 restore();
3411 return;
3412 }
3413
3414 // Concatenate search domains into a string.
3415 StringBuilder buffer = new StringBuilder();
3416 if (searchDomains != null) {
3417 for (String domain : searchDomains) {
3418 buffer.append(domain).append(' ');
3419 }
3420 }
3421 String domains = buffer.toString().trim();
3422
3423 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003424 synchronized (mDnsLock) {
Mattias Falkd697aa22011-08-23 14:15:13 +02003425 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003426 mDnsOverridden = true;
3427 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003428
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003429 // Temporarily disable the default proxy (not global).
3430 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003431 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003432 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003433 sendProxyBroadcast(null);
3434 }
3435 }
3436
3437 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003438 }
3439
Chia-chi Yehcc844502011-07-14 18:01:57 -07003440 public void restore() {
3441 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003442 if (mDnsOverridden) {
3443 mDnsOverridden = false;
3444 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003445 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003446 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003447 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003448 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003449 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003450 sendProxyBroadcast(mDefaultProxy);
3451 }
3452 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003453 }
3454 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003455
3456 @Override
3457 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003458 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3459 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3460 return false;
3461 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003462
3463 // Tear down existing lockdown if profile was removed
3464 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3465 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003466 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003467 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3468 return false;
3469 }
3470
3471 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3472 final VpnProfile profile = VpnProfile.decode(
3473 profileName, mKeyStore.get(Credentials.VPN + profileName));
3474 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3475 } else {
3476 setLockdownTracker(null);
3477 }
3478
3479 return true;
3480 }
3481
3482 /**
3483 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3484 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3485 */
3486 private void setLockdownTracker(LockdownVpnTracker tracker) {
3487 // Shutdown any existing tracker
3488 final LockdownVpnTracker existing = mLockdownTracker;
3489 mLockdownTracker = null;
3490 if (existing != null) {
3491 existing.shutdown();
3492 }
3493
3494 try {
3495 if (tracker != null) {
3496 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003497 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003498 mLockdownTracker = tracker;
3499 mLockdownTracker.init();
3500 } else {
3501 mNetd.setFirewallEnabled(false);
3502 }
3503 } catch (RemoteException e) {
3504 // ignored; NMS lives inside system_server
3505 }
3506 }
3507
3508 private void throwIfLockdownEnabled() {
3509 if (mLockdownEnabled) {
3510 throw new IllegalStateException("Unavailable in lockdown mode");
3511 }
3512 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003513
3514 public void supplyMessenger(int networkType, Messenger messenger) {
3515 enforceConnectivityInternalPermission();
3516
3517 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3518 mNetTrackers[networkType].supplyMessenger(messenger);
3519 }
3520 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003521
3522 public int findConnectionTypeForIface(String iface) {
3523 enforceConnectivityInternalPermission();
3524
3525 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3526 for (NetworkStateTracker tracker : mNetTrackers) {
3527 if (tracker != null) {
3528 LinkProperties lp = tracker.getLinkProperties();
3529 if (lp != null && iface.equals(lp.getInterfaceName())) {
3530 return tracker.getNetworkInfo().getType();
3531 }
3532 }
3533 }
3534 return ConnectivityManager.TYPE_NONE;
3535 }
Wink Saville32506bc2013-06-29 21:10:57 -07003536
3537 /**
3538 * Have mobile data fail fast if enabled.
3539 *
3540 * @param enabled DctConstants.ENABLED/DISABLED
3541 */
3542 private void setEnableFailFastMobileData(int enabled) {
3543 int tag;
3544
3545 if (enabled == DctConstants.ENABLED) {
3546 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3547 } else {
3548 tag = mEnableFailFastMobileDataTag.get();
3549 }
3550 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3551 enabled));
3552 }
3553
3554 @Override
3555 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3556 final ResultReceiver resultReceiver) {
3557 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3558 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3559 + " resultReceiver=" + resultReceiver);
3560 enforceChangePermission();
3561
3562 int timeOutMs = suggestedTimeOutMs;
3563 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3564 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3565 }
3566
Wink Savilled469c472013-07-02 10:55:14 -07003567 // Check that mobile networks are supported
3568 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3569 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3570 log("checkMobileProvisioning: X no mobile network");
3571 if (resultReceiver != null) {
3572 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3573 }
3574 return timeOutMs;
3575 }
3576
Wink Saville32506bc2013-06-29 21:10:57 -07003577 final long token = Binder.clearCallingIdentity();
3578 try {
3579 CheckMp checkMp = new CheckMp(mContext, this);
3580 CheckMp.CallBack cb = new CheckMp.CallBack() {
3581 @Override
3582 void onComplete(Integer result) {
3583 log("CheckMp.onComplete: result=" + result);
3584 if (resultReceiver != null) {
3585 log("CheckMp.onComplete: send result");
3586 resultReceiver.send(result, null);
3587 }
3588 NetworkInfo ni =
3589 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3590 switch(result) {
3591 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3592 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3593 log("CheckMp.onComplete: ignore, connected or no connection");
3594 break;
3595 }
3596 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3597 log("CheckMp.onComplete: warm sim");
3598 String url = getProvisioningUrl();
3599 if (TextUtils.isEmpty(url)) {
3600 url = mContext.getResources()
3601 .getString(R.string.mobile_redirected_provisioning_url);
3602 }
3603 if (TextUtils.isEmpty(url) == false) {
3604 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3605 setNotificationVisible(true, ni, url);
3606 } else {
3607 log("CheckMp.onComplete: warm sim (redirected), no url");
3608 }
3609 break;
3610 }
3611 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3612 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3613 String url = getProvisioningUrl();
3614 if (TextUtils.isEmpty(url) == false) {
3615 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3616 setNotificationVisible(true, ni, url);
3617 } else {
3618 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3619 }
3620 break;
3621 }
3622 default: {
3623 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3624 break;
3625 }
3626 }
3627 }
3628 };
3629 CheckMp.Params params =
3630 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3631 log("checkMobileProvisioning: params=" + params);
3632 setNotificationVisible(false, null, null);
3633 checkMp.execute(params);
3634 } finally {
3635 Binder.restoreCallingIdentity(token);
3636 log("checkMobileProvisioning: X");
3637 }
3638 return timeOutMs;
3639 }
3640
3641 static class CheckMp extends
3642 AsyncTask<CheckMp.Params, Void, Integer> {
3643 private static final String CHECKMP_TAG = "CheckMp";
3644 public static final int MAX_TIMEOUT_MS = 60000;
3645 private static final int SOCKET_TIMEOUT_MS = 5000;
3646 private Context mContext;
3647 private ConnectivityService mCs;
3648 private TelephonyManager mTm;
3649 private Params mParams;
3650
3651 /**
3652 * Parameters for AsyncTask.execute
3653 */
3654 static class Params {
3655 private String mUrl;
3656 private long mTimeOutMs;
3657 private CallBack mCb;
3658
3659 Params(String url, long timeOutMs, CallBack cb) {
3660 mUrl = url;
3661 mTimeOutMs = timeOutMs;
3662 mCb = cb;
3663 }
3664
3665 @Override
3666 public String toString() {
3667 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3668 }
3669 }
3670
3671 /**
3672 * The call back object passed in Params. onComplete will be called
3673 * on the main thread.
3674 */
3675 abstract static class CallBack {
3676 // Called on the main thread.
3677 abstract void onComplete(Integer result);
3678 }
3679
3680 public CheckMp(Context context, ConnectivityService cs) {
3681 mContext = context;
3682 mCs = cs;
3683
3684 // Setup access to TelephonyService we'll be using.
3685 mTm = (TelephonyManager) mContext.getSystemService(
3686 Context.TELEPHONY_SERVICE);
3687 }
3688
3689 /**
3690 * Get the default url to use for the test.
3691 */
3692 public String getDefaultUrl() {
3693 // See http://go/clientsdns for usage approval
3694 String server = Settings.Global.getString(mContext.getContentResolver(),
3695 Settings.Global.CAPTIVE_PORTAL_SERVER);
3696 if (server == null) {
3697 server = "clients3.google.com";
3698 }
3699 return "http://" + server + "/generate_204";
3700 }
3701
3702 /**
3703 * Detect if its possible to connect to the http url. DNS based detection techniques
3704 * do not work at all hotspots. The best way to check is to perform a request to
3705 * a known address that fetches the data we expect.
3706 */
3707 private synchronized Integer isMobileOk(Params params) {
3708 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3709 Uri orgUri = Uri.parse(params.mUrl);
3710 Random rand = new Random();
3711 mParams = params;
3712
3713 try {
3714 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3715 log("isMobileOk: not mobile capable");
3716 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3717 return result;
3718 }
3719
3720 // Enable fail fast as we'll do retries here and use a
3721 // hipri connection so the default connection stays active.
3722 log("isMobileOk: start hipri url=" + params.mUrl);
3723 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3724 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3725 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3726
3727 // Continue trying to connect until time has run out
3728 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3729 while(SystemClock.elapsedRealtime() < endTime) {
3730 try {
3731 // Wait for hipri to connect.
3732 // TODO: Don't poll and handle situation where hipri fails
3733 // because default is retrying. See b/9569540
3734 NetworkInfo.State state = mCs
3735 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3736 if (state != NetworkInfo.State.CONNECTED) {
3737 log("isMobileOk: not connected ni=" +
3738 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3739 sleep(1);
3740 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3741 continue;
3742 }
3743
3744 // Get of the addresses associated with the url host. We need to use the
3745 // address otherwise HttpURLConnection object will use the name to get
3746 // the addresses and is will try every address but that will bypass the
3747 // route to host we setup and the connection could succeed as the default
3748 // interface might be connected to the internet via wifi or other interface.
3749 InetAddress[] addresses;
3750 try {
3751 addresses = InetAddress.getAllByName(orgUri.getHost());
3752 } catch (UnknownHostException e) {
3753 log("isMobileOk: UnknownHostException");
3754 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3755 return result;
3756 }
3757 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3758
3759 // Get the type of addresses supported by this link
3760 LinkProperties lp = mCs.getLinkProperties(
3761 ConnectivityManager.TYPE_MOBILE_HIPRI);
3762 boolean linkHasIpv4 = hasIPv4Address(lp);
3763 boolean linkHasIpv6 = hasIPv6Address(lp);
3764 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3765 + " linkHasIpv6=" + linkHasIpv6);
3766
3767 // Loop through at most 3 valid addresses or all of the address or until
3768 // we run out of time
3769 int loops = Math.min(3, addresses.length);
3770 for(int validAddr=0, addrTried=0;
3771 (validAddr < loops) && (addrTried < addresses.length)
3772 && (SystemClock.elapsedRealtime() < endTime);
3773 addrTried ++) {
3774
3775 // Choose the address at random but make sure its type is supported
3776 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3777 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3778 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3779 // Valid address, so use it
3780 validAddr += 1;
3781 } else {
3782 // Invalid address so try next address
3783 continue;
3784 }
3785
3786 // Make a route to host so we check the specific interface.
3787 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3788 hostAddr.getAddress())) {
3789 // Wait a short time to be sure the route is established ??
3790 log("isMobileOk:"
3791 + " wait to establish route to hostAddr=" + hostAddr);
3792 sleep(3);
3793 } else {
3794 log("isMobileOk:"
3795 + " could not establish route to hostAddr=" + hostAddr);
3796 continue;
3797 }
3798
3799 // Rewrite the url to have numeric address to use the specific route.
3800 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3801 // is used which is useless in this case.
3802 URL newUrl = new URL(orgUri.getScheme() + "://"
3803 + hostAddr.getHostAddress() + orgUri.getPath());
3804 log("isMobileOk: newUrl=" + newUrl);
3805
3806 HttpURLConnection urlConn = null;
3807 try {
3808 // Open the connection set the request header and get the response
3809 urlConn = (HttpURLConnection) newUrl.openConnection(
3810 java.net.Proxy.NO_PROXY);
3811 urlConn.setInstanceFollowRedirects(false);
3812 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3813 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3814 urlConn.setUseCaches(false);
3815 urlConn.setAllowUserInteraction(false);
3816 urlConn.setRequestProperty("Connection", "close");
3817 int responseCode = urlConn.getResponseCode();
3818 if (responseCode == 204) {
3819 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3820 } else {
3821 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3822 }
3823 log("isMobileOk: connected responseCode=" + responseCode);
3824 urlConn.disconnect();
3825 urlConn = null;
3826 return result;
3827 } catch (Exception e) {
3828 log("isMobileOk: HttpURLConnection Exception e=" + e);
3829 if (urlConn != null) {
3830 urlConn.disconnect();
3831 urlConn = null;
3832 }
3833 }
3834 }
3835 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3836 log("isMobileOk: loops|timed out");
3837 return result;
3838 } catch (Exception e) {
3839 log("isMobileOk: Exception e=" + e);
3840 continue;
3841 }
3842 }
3843 log("isMobileOk: timed out");
3844 } finally {
3845 log("isMobileOk: F stop hipri");
3846 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3847 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3848 Phone.FEATURE_ENABLE_HIPRI);
3849 log("isMobileOk: X result=" + result);
3850 }
3851 return result;
3852 }
3853
3854 @Override
3855 protected Integer doInBackground(Params... params) {
3856 return isMobileOk(params[0]);
3857 }
3858
3859 @Override
3860 protected void onPostExecute(Integer result) {
3861 log("onPostExecute: result=" + result);
3862 if ((mParams != null) && (mParams.mCb != null)) {
3863 mParams.mCb.onComplete(result);
3864 }
3865 }
3866
3867 private String inetAddressesToString(InetAddress[] addresses) {
3868 StringBuffer sb = new StringBuffer();
3869 boolean firstTime = true;
3870 for(InetAddress addr : addresses) {
3871 if (firstTime) {
3872 firstTime = false;
3873 } else {
3874 sb.append(",");
3875 }
3876 sb.append(addr);
3877 }
3878 return sb.toString();
3879 }
3880
3881 private void printNetworkInfo() {
3882 boolean hasIccCard = mTm.hasIccCard();
3883 int simState = mTm.getSimState();
3884 log("hasIccCard=" + hasIccCard
3885 + " simState=" + simState);
3886 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3887 if (ni != null) {
3888 log("ni.length=" + ni.length);
3889 for (NetworkInfo netInfo: ni) {
3890 log("netInfo=" + netInfo.toString());
3891 }
3892 } else {
3893 log("no network info ni=null");
3894 }
3895 }
3896
3897 /**
3898 * Sleep for a few seconds then return.
3899 * @param seconds
3900 */
3901 private static void sleep(int seconds) {
3902 try {
3903 Thread.sleep(seconds * 1000);
3904 } catch (InterruptedException e) {
3905 e.printStackTrace();
3906 }
3907 }
3908
3909 public boolean hasIPv4Address(LinkProperties lp) {
3910 return lp.hasIPv4Address();
3911 }
3912
3913 // Not implemented in LinkProperties, do it here.
3914 public boolean hasIPv6Address(LinkProperties lp) {
3915 for (LinkAddress address : lp.getLinkAddresses()) {
3916 if (address.getAddress() instanceof Inet6Address) {
3917 return true;
3918 }
3919 }
3920 return false;
3921 }
3922
3923 private void log(String s) {
3924 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3925 }
3926 }
3927
3928 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3929
3930 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3931 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3932
3933 Resources r = Resources.getSystem();
3934 NotificationManager notificationManager = (NotificationManager) mContext
3935 .getSystemService(Context.NOTIFICATION_SERVICE);
3936
3937 if (visible) {
3938 CharSequence title;
3939 CharSequence details;
3940 int icon;
3941 switch (networkInfo.getType()) {
3942 case ConnectivityManager.TYPE_WIFI:
3943 log("setNotificationVisible: TYPE_WIFI");
3944 title = r.getString(R.string.wifi_available_sign_in, 0);
3945 details = r.getString(R.string.network_available_sign_in_detailed,
3946 networkInfo.getExtraInfo());
3947 icon = R.drawable.stat_notify_wifi_in_range;
3948 break;
3949 case ConnectivityManager.TYPE_MOBILE:
3950 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3951 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
3952 title = r.getString(R.string.network_available_sign_in, 0);
3953 // TODO: Change this to pull from NetworkInfo once a printable
3954 // name has been added to it
3955 details = mTelephonyManager.getNetworkOperatorName();
3956 icon = R.drawable.stat_notify_rssi_in_range;
3957 break;
3958 default:
3959 log("setNotificationVisible: other type=" + networkInfo.getType());
3960 title = r.getString(R.string.network_available_sign_in, 0);
3961 details = r.getString(R.string.network_available_sign_in_detailed,
3962 networkInfo.getExtraInfo());
3963 icon = R.drawable.stat_notify_rssi_in_range;
3964 break;
3965 }
3966
3967 Notification notification = new Notification();
3968 notification.when = 0;
3969 notification.icon = icon;
3970 notification.flags = Notification.FLAG_AUTO_CANCEL;
3971 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3972 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3973 Intent.FLAG_ACTIVITY_NEW_TASK);
3974 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3975 notification.tickerText = title;
3976 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3977
3978 log("setNotificaitionVisible: notify notificaiton=" + notification);
3979 notificationManager.notify(NOTIFICATION_ID, 1, notification);
3980 } else {
3981 log("setNotificaitionVisible: cancel");
3982 notificationManager.cancel(NOTIFICATION_ID, 1);
3983 }
3984 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
3985 }
3986
3987 private String getProvisioningUrl() {
3988 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillec118d7e2013-07-10 23:00:07 -07003989 log("getProvisioningUrl: mobile_provisioning_url=" + url);
Wink Saville32506bc2013-06-29 21:10:57 -07003990
Wink Savillec118d7e2013-07-10 23:00:07 -07003991 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07003992 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07003993 String phoneNumber = mTelephonyManager.getLine1Number();
3994 if (TextUtils.isEmpty(phoneNumber)) {
3995 phoneNumber = "0000000000";
3996 }
Wink Saville32506bc2013-06-29 21:10:57 -07003997 url = String.format(url,
3998 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3999 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004000 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004001 }
4002
Wink Saville32506bc2013-06-29 21:10:57 -07004003 return url;
4004 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004005}