blob: 10b1befdc5d677619523912dd2ff4faaa1e0843e [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;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900110import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800111import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700112import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700113import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700114import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700115import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700116import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700117
tk.mun093f55c2011-10-13 22:51:57 +0900118import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700119
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700121import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900123import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700124import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700125import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700126import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700127import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700128import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700129import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700130import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700131import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700132import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700133import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700134import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700135import java.util.List;
Wink Saville32506bc2013-06-29 21:10:57 -0700136import java.util.Random;
137import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800138
139/**
140 * @hide
141 */
142public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700143 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800144
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700145 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700146 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700148 private static final boolean LOGD_RULES = false;
149
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700150 // TODO: create better separation between radio types and network types
151
Robert Greenwalt2034b912009-08-12 16:08:25 -0700152 // how long to wait before switching back to a radio's default network
153 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
154 // system property that can override the above value
155 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
156 "android.telephony.apn-restore";
157
Wink Saville32506bc2013-06-29 21:10:57 -0700158 // Default value if FAIL_FAST_TIME_MS is not set
159 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
160 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
161 private static final String FAIL_FAST_TIME_MS =
162 "persist.radio.fail_fast_time_ms";
163
Robert Greenwaltbd492212011-05-06 17:10:53 -0700164 // used in recursive route setting to add gateways for the host for which
165 // a host route was requested.
166 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
167
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800168 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800169 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800170
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700171 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700172
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700173 private Vpn mVpn;
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700174 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700175
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700176 private boolean mLockdownEnabled;
177 private LockdownVpnTracker mLockdownTracker;
178
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900179 private Nat464Xlat mClat;
180
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700181 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
182 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700183 /** Currently active network rules by UID. */
184 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700185 /** Set of ifaces that are costly. */
186 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700187
The Android Open Source Project28527d22009-03-03 19:31:44 -0800188 /**
189 * Sometimes we want to refer to the individual network state
190 * trackers separately, and sometimes we just want to treat them
191 * abstractly.
192 */
193 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700194
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700195 /* Handles captive portal check on a network */
196 private CaptivePortalTracker mCaptivePortalTracker;
197
Robert Greenwalt2034b912009-08-12 16:08:25 -0700198 /**
Wink Saville051a6642011-07-13 13:44:13 -0700199 * The link properties that define the current links
200 */
201 private LinkProperties mCurrentLinkProperties[];
202
203 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700204 * A per Net list of the PID's that requested access to the net
205 * used both as a refcount and for per-PID DNS selection
206 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200207 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700208
Robert Greenwalt2034b912009-08-12 16:08:25 -0700209 // priority order of the nettrackers
210 // (excluding dynamically set mNetworkPreference)
211 // TODO - move mNetworkTypePreference into this
212 private int[] mPriorityList;
213
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 private Context mContext;
215 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700217 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000218 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700219 private int mDefaultInetConditionPublished = 0;
220 private boolean mInetConditionChangeInFlight = false;
221 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222
Chia-chi Yehcc844502011-07-14 18:01:57 -0700223 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800224 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700225 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226
227 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700228 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229
Robert Greenwalt355205c2011-05-10 15:05:02 -0700230 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700231 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700232
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700233 private static final int ENABLED = 1;
234 private static final int DISABLED = 0;
235
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700236 private static final boolean ADD = true;
237 private static final boolean REMOVE = false;
238
239 private static final boolean TO_DEFAULT_TABLE = true;
240 private static final boolean TO_SECONDARY_TABLE = false;
241
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700242 /**
243 * used internally as a delayed event to make us switch back to the
244 * default network
245 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700246 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700247
248 /**
249 * used internally to change our mobile data enabled flag
250 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700251 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700252
253 /**
254 * used internally to change our network preference setting
255 * arg1 = networkType to prefer
256 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700257 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700258
259 /**
260 * used internally to synchronize inet condition reports
261 * arg1 = networkType
262 * arg2 = condition (0 bad, 100 good)
263 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700264 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700265
266 /**
267 * used internally to mark the end of inet condition hold periods
268 * arg1 = networkType
269 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700270 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700271
272 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700273 * used internally to set enable/disable cellular data
274 * arg1 = ENBALED or DISABLED
275 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700276 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700277
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700278 /**
279 * used internally to clear a wakelock when transitioning
280 * from one net to another
281 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700282 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700283
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700284 /**
285 * used internally to reload global proxy settings
286 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700287 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700288
Robert Greenwalt34848c02011-03-25 13:09:25 -0700289 /**
290 * used internally to set external dependency met/unmet
291 * arg1 = ENABLED (met) or DISABLED (unmet)
292 * arg2 = NetworkType
293 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700294 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700295
Chia-chi Yehcc844502011-07-14 18:01:57 -0700296 /**
297 * used internally to restore DNS properties back to the
298 * default network
299 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700300 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700301
Wink Saville7e4333c2011-08-05 11:40:22 -0700302 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700303 * used internally to send a sticky broadcast delayed.
304 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700305 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700306
Jeff Sharkey805662d2011-08-19 02:24:24 -0700307 /**
308 * Used internally to
309 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
310 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700311 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700312
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700313 private static final int EVENT_VPN_STATE_CHANGED = 14;
314
Wink Saville32506bc2013-06-29 21:10:57 -0700315 /**
316 * Used internally to disable fail fast of mobile data
317 */
318 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
319
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700320 /** Handler used for internal events. */
321 private InternalHandler mHandler;
322 /** Handler used for incoming {@link NetworkStateTracker} events. */
323 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700324
325 // list of DeathRecipients used to make sure features are turned off when
326 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500327 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700328
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400329 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800330 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400331
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700332 private PowerManager.WakeLock mNetTransitionWakeLock;
333 private String mNetTransitionWakeLockCausedBy = "";
334 private int mNetTransitionWakeLockSerialNumber;
335 private int mNetTransitionWakeLockTimeout;
336
Robert Greenwalt94daa182010-09-01 11:34:05 -0700337 private InetAddress mDefaultDns;
338
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700339 // this collection is used to refcount the added routes - if there are none left
340 // it's time to remove the route from the route table
341 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
342
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700343 // used in DBG mode to track inet condition reports
344 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
345 private ArrayList mInetLog;
346
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700347 // track the current default http proxy - tell the world if we get a new one (real change)
348 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700349 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700350 private boolean mDefaultProxyDisabled = false;
351
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700352 // track the global proxy.
353 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700354
355 private SettingsObserver mSettingsObserver;
356
Robert Greenwalt34848c02011-03-25 13:09:25 -0700357 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700358 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359
Robert Greenwalt12c44552009-12-07 11:33:18 -0800360 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361 public int mSimultaneity;
362 public int mType;
363 public RadioAttributes(String init) {
364 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700365 mType = Integer.parseInt(fragments[0]);
366 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367 }
368 }
369 RadioAttributes[] mRadioAttributes;
370
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700371 // the set of network types that can only be enabled by system/sig apps
372 List mProtectedNetworks;
373
Wink Saville32506bc2013-06-29 21:10:57 -0700374 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
375
376 TelephonyManager mTelephonyManager;
377
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700378 public ConnectivityService(Context context, INetworkManagementService netd,
379 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700380 // Currently, omitting a NetworkFactory will create one internally
381 // TODO: create here when we have cleaner WiMAX support
382 this(context, netd, statsService, policyManager, null);
383 }
384
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700385 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700386 INetworkStatsService statsService, INetworkPolicyManager policyManager,
387 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800388 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800389
Wink Saville775aad62010-09-02 19:23:52 -0700390 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
391 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700392 mHandler = new InternalHandler(handlerThread.getLooper());
393 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700394
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700395 if (netFactory == null) {
396 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
397 }
398
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800399 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800400 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
401 String id = Settings.Secure.getString(context.getContentResolver(),
402 Settings.Secure.ANDROID_ID);
403 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700404 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800405 SystemProperties.set("net.hostname", name);
406 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800407 }
408
Robert Greenwalt94daa182010-09-01 11:34:05 -0700409 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700410 String dns = Settings.Global.getString(context.getContentResolver(),
411 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700412 if (dns == null || dns.length() == 0) {
413 dns = context.getResources().getString(
414 com.android.internal.R.string.config_default_dns_server);
415 }
416 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800417 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
418 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800419 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700420 }
421
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700422 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700423 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700424 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700425 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700426 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700427
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700428 try {
429 mPolicyManager.registerListener(mPolicyListener);
430 } catch (RemoteException e) {
431 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700432 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700433 }
434
435 final PowerManager powerManager = (PowerManager) context.getSystemService(
436 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700437 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
438 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
439 com.android.internal.R.integer.config_networkTransitionTimeout);
440
Robert Greenwalt2034b912009-08-12 16:08:25 -0700441 mNetTrackers = new NetworkStateTracker[
442 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700443 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700444
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700445 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700446 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447
Robert Greenwalt2034b912009-08-12 16:08:25 -0700448 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700449 String[] raStrings = context.getResources().getStringArray(
450 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700451 for (String raString : raStrings) {
452 RadioAttributes r = new RadioAttributes(raString);
453 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800454 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700455 continue;
456 }
457 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800458 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700459 r.mType);
460 continue;
461 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700462 mRadioAttributes[r.mType] = r;
463 }
464
Wink Saville00fe5092013-04-23 14:26:51 -0700465 // TODO: What is the "correct" way to do determine if this is a wifi only device?
466 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
467 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700468 String[] naStrings = context.getResources().getStringArray(
469 com.android.internal.R.array.networkAttributes);
470 for (String naString : naStrings) {
471 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700472 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700473 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800474 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700475 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700476 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700477 }
Wink Saville00fe5092013-04-23 14:26:51 -0700478 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
479 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
480 n.type);
481 continue;
482 }
Wink Savillef2a62832011-04-07 14:23:45 -0700483 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800484 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700485 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700486 continue;
487 }
Wink Savillef2a62832011-04-07 14:23:45 -0700488 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800489 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700490 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700491 continue;
492 }
Wink Savillef2a62832011-04-07 14:23:45 -0700493 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700494 mNetworksDefined++;
495 } catch(Exception e) {
496 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700497 }
498 }
499
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700500 mProtectedNetworks = new ArrayList<Integer>();
501 int[] protectedNetworks = context.getResources().getIntArray(
502 com.android.internal.R.array.config_protectedNetworks);
503 for (int p : protectedNetworks) {
504 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
505 mProtectedNetworks.add(p);
506 } else {
507 if (DBG) loge("Ignoring protectedNetwork " + p);
508 }
509 }
510
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 // high priority first
512 mPriorityList = new int[mNetworksDefined];
513 {
514 int insertionPoint = mNetworksDefined-1;
515 int currentLowest = 0;
516 int nextLowest = 0;
517 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700518 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700519 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700520 if (na.priority < currentLowest) continue;
521 if (na.priority > currentLowest) {
522 if (na.priority < nextLowest || nextLowest == 0) {
523 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700524 }
525 continue;
526 }
Wink Savillef2a62832011-04-07 14:23:45 -0700527 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700528 }
529 currentLowest = nextLowest;
530 nextLowest = 0;
531 }
532 }
533
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800534 // Update mNetworkPreference according to user mannually first then overlay config.xml
535 mNetworkPreference = getPersistedNetworkPreference();
536 if (mNetworkPreference == -1) {
537 for (int n : mPriorityList) {
538 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
539 mNetworkPreference = n;
540 break;
541 }
542 }
543 if (mNetworkPreference == -1) {
544 throw new IllegalStateException(
545 "You should set at least one default Network in config.xml!");
546 }
547 }
548
Mattias Falkd697aa22011-08-23 14:15:13 +0200549 mNetRequestersPids =
550 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700551 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200552 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553 }
554
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500555 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700557 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
558 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700559
560 // Create and start trackers for hard-coded networks
561 for (int targetNetworkType : mPriorityList) {
562 final NetworkConfig config = mNetConfigs[targetNetworkType];
563 final NetworkStateTracker tracker;
564 try {
565 tracker = netFactory.createTracker(targetNetworkType, config);
566 mNetTrackers[targetNetworkType] = tracker;
567 } catch (IllegalArgumentException e) {
568 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
569 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700570 continue;
571 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700572
573 tracker.startMonitoring(context, mTrackerHandler);
574 if (config.isDefault()) {
575 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800576 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700577 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800578
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700579 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700580 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700581 mTethering.getTetherableWifiRegexs().length != 0 ||
582 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700583 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800584
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -0700585 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700586 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700587
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900588 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
589
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700590 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700591 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700592 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900593 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700594 } catch (RemoteException e) {
595 loge("Error registering observer :" + e);
596 }
597
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700598 if (DBG) {
599 mInetLog = new ArrayList();
600 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700601
602 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
603 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800604
Irfan Sheriff32bed2c2012-09-20 09:32:41 -0700605 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800606 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800607 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700608
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700609 /**
610 * Factory that creates {@link NetworkStateTracker} instances using given
611 * {@link NetworkConfig}.
612 */
613 public interface NetworkFactory {
614 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
615 }
616
617 private static class DefaultNetworkFactory implements NetworkFactory {
618 private final Context mContext;
619 private final Handler mTrackerHandler;
620
621 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
622 mContext = context;
623 mTrackerHandler = trackerHandler;
624 }
625
626 @Override
627 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
628 switch (config.radio) {
629 case TYPE_WIFI:
630 return new WifiStateTracker(targetNetworkType, config.name);
631 case TYPE_MOBILE:
632 return new MobileDataStateTracker(targetNetworkType, config.name);
633 case TYPE_DUMMY:
634 return new DummyDataStateTracker(targetNetworkType, config.name);
635 case TYPE_BLUETOOTH:
636 return BluetoothTetheringDataTracker.getInstance();
637 case TYPE_WIMAX:
638 return makeWimaxStateTracker(mContext, mTrackerHandler);
639 case TYPE_ETHERNET:
640 return EthernetDataTracker.getInstance();
641 default:
642 throw new IllegalArgumentException(
643 "Trying to create a NetworkStateTracker for an unknown radio type: "
644 + config.radio);
645 }
646 }
647 }
648
649 /**
650 * Loads external WiMAX library and registers as system service, returning a
651 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
652 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
653 */
654 private static NetworkStateTracker makeWimaxStateTracker(
655 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700656 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900657 DexClassLoader wimaxClassLoader;
658 Class wimaxStateTrackerClass = null;
659 Class wimaxServiceClass = null;
660 Class wimaxManagerClass;
661 String wimaxJarLocation;
662 String wimaxLibLocation;
663 String wimaxManagerClassName;
664 String wimaxServiceClassName;
665 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800666
tk.mun093f55c2011-10-13 22:51:57 +0900667 NetworkStateTracker wimaxStateTracker = null;
668
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700669 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900670 com.android.internal.R.bool.config_wimaxEnabled);
671
672 if (isWimaxEnabled) {
673 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700674 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900675 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700676 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900677 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700678 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900679 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700680 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900681 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700682 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900683 com.android.internal.R.string.config_wimaxStateTrackerClassname);
684
Dianne Hackborndc456a62012-11-08 11:12:09 -0800685 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900686 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700687 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900688 wimaxLibLocation, ClassLoader.getSystemClassLoader());
689
690 try {
691 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
692 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
693 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
694 } catch (ClassNotFoundException ex) {
695 loge("Exception finding Wimax classes: " + ex.toString());
696 return null;
697 }
698 } catch(Resources.NotFoundException ex) {
699 loge("Wimax Resources does not exist!!! ");
700 return null;
701 }
702
703 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800704 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900705
706 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
707 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700708 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
709 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900710
711 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
712 (new Class[] {Context.class, wimaxStateTrackerClass});
713 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700714 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900715 wmxSrvConst.setAccessible(false);
716
717 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
718
719 } catch(Exception ex) {
720 loge("Exception creating Wimax classes: " + ex.toString());
721 return null;
722 }
723 } else {
724 loge("Wimax is not enabled or not added to the network attributes!!! ");
725 return null;
726 }
727
728 return wimaxStateTracker;
729 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700730
The Android Open Source Project28527d22009-03-03 19:31:44 -0800731 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700732 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800733 * @param preference the new preference
734 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700735 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800736 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700737
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700738 mHandler.sendMessage(
739 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800740 }
741
742 public int getNetworkPreference() {
743 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700744 int preference;
745 synchronized(this) {
746 preference = mNetworkPreference;
747 }
748 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800749 }
750
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700751 private void handleSetNetworkPreference(int preference) {
752 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700753 mNetConfigs[preference] != null &&
754 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700755 if (mNetworkPreference != preference) {
756 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700757 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700758 synchronized(this) {
759 mNetworkPreference = preference;
760 }
761 enforcePreference();
762 }
763 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800764 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700765
Wink Saville4f0de1e2011-08-04 15:01:58 -0700766 private int getConnectivityChangeDelay() {
767 final ContentResolver cr = mContext.getContentResolver();
768
769 /** Check system properties for the default value then use secure settings value, if any. */
770 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700771 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
772 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
773 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700774 defaultDelay);
775 }
776
The Android Open Source Project28527d22009-03-03 19:31:44 -0800777 private int getPersistedNetworkPreference() {
778 final ContentResolver cr = mContext.getContentResolver();
779
Jeff Brownc67cf562012-09-25 15:03:20 -0700780 final int networkPrefSetting = Settings.Global
781 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800783 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800784 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700785
The Android Open Source Project28527d22009-03-03 19:31:44 -0800786 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700787 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800788 * In this method, we only tear down a non-preferred network. Establishing
789 * a connection to the preferred network is taken care of when we handle
790 * the disconnect event from the non-preferred network
791 * (see {@link #handleDisconnect(NetworkInfo)}).
792 */
793 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700794 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800795 return;
796
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797 if (!mNetTrackers[mNetworkPreference].isAvailable())
798 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800799
Robert Greenwalt2034b912009-08-12 16:08:25 -0700800 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700801 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700802 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700803 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800804 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700805 " in enforcePreference");
806 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800808 }
809 }
810 }
811
812 private boolean teardown(NetworkStateTracker netTracker) {
813 if (netTracker.teardown()) {
814 netTracker.setTeardownRequested(true);
815 return true;
816 } else {
817 return false;
818 }
819 }
820
821 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700822 * Check if UID should be blocked from using the network represented by the
823 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700824 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700825 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
826 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700827
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700828 final boolean networkCostly;
829 final int uidRules;
830 synchronized (mRulesLock) {
831 networkCostly = mMeteredIfaces.contains(iface);
832 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700833 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700834
835 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
836 return true;
837 }
838
839 // no restrictive rules; network is visible
840 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700841 }
842
843 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700844 * Return a filtered {@link NetworkInfo}, potentially marked
845 * {@link DetailedState#BLOCKED} based on
846 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700847 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700848 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
849 NetworkInfo info = tracker.getNetworkInfo();
850 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700851 // network is blocked; clone and override state
852 info = new NetworkInfo(info);
853 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700854 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700855 if (mLockdownTracker != null) {
856 info = mLockdownTracker.augmentNetworkInfo(info);
857 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700858 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700859 }
860
861 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800862 * Return NetworkInfo for the active (i.e., connected) network interface.
863 * It is assumed that at most one network is active at a time. If more
864 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700865 * @return the info for the active network, or {@code null} if none is
866 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800867 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700868 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700870 enforceAccessPermission();
871 final int uid = Binder.getCallingUid();
872 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800873 }
874
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700875 public NetworkInfo getActiveNetworkInfoUnfiltered() {
876 enforceAccessPermission();
877 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
878 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
879 if (tracker != null) {
880 return tracker.getNetworkInfo();
881 }
882 }
883 return null;
884 }
885
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700886 @Override
887 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
888 enforceConnectivityInternalPermission();
889 return getNetworkInfo(mActiveDefaultNetwork, uid);
890 }
891
892 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800893 public NetworkInfo getNetworkInfo(int networkType) {
894 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700895 final int uid = Binder.getCallingUid();
896 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800897 }
898
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700899 private NetworkInfo getNetworkInfo(int networkType, int uid) {
900 NetworkInfo info = null;
901 if (isNetworkTypeValid(networkType)) {
902 final NetworkStateTracker tracker = mNetTrackers[networkType];
903 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700904 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700905 }
906 }
907 return info;
908 }
909
910 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800911 public NetworkInfo[] getAllNetworkInfo() {
912 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700913 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700914 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700915 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700916 for (NetworkStateTracker tracker : mNetTrackers) {
917 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700918 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700919 }
920 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800921 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700922 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 }
924
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700925 @Override
926 public boolean isNetworkSupported(int networkType) {
927 enforceAccessPermission();
928 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
929 }
930
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700931 /**
932 * Return LinkProperties for the active (i.e., connected) default
933 * network interface. It is assumed that at most one default network
934 * is active at a time. If more than one is active, it is indeterminate
935 * which will be returned.
936 * @return the ip properties for the active network, or {@code null} if
937 * none is active
938 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700939 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700940 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700941 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700942 }
943
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700944 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700945 public LinkProperties getLinkProperties(int networkType) {
946 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700947 if (isNetworkTypeValid(networkType)) {
948 final NetworkStateTracker tracker = mNetTrackers[networkType];
949 if (tracker != null) {
950 return tracker.getLinkProperties();
951 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700952 }
953 return null;
954 }
955
Jeff Sharkey21062e72011-05-28 20:56:34 -0700956 @Override
957 public NetworkState[] getAllNetworkState() {
958 enforceAccessPermission();
959 final int uid = Binder.getCallingUid();
960 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700961 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700962 for (NetworkStateTracker tracker : mNetTrackers) {
963 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700964 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700965 result.add(new NetworkState(
966 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
967 }
968 }
969 }
970 return result.toArray(new NetworkState[result.size()]);
971 }
972
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700973 private NetworkState getNetworkStateUnchecked(int networkType) {
974 if (isNetworkTypeValid(networkType)) {
975 final NetworkStateTracker tracker = mNetTrackers[networkType];
976 if (tracker != null) {
977 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
978 tracker.getLinkCapabilities());
979 }
980 }
981 return null;
982 }
983
984 @Override
985 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
986 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700987
988 final long token = Binder.clearCallingIdentity();
989 try {
990 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
991 if (state != null) {
992 try {
993 return mPolicyManager.getNetworkQuotaInfo(state);
994 } catch (RemoteException e) {
995 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700996 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700997 return null;
998 } finally {
999 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001000 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001001 }
1002
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001003 @Override
1004 public boolean isActiveNetworkMetered() {
1005 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001006 final long token = Binder.clearCallingIdentity();
1007 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001008 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001009 } finally {
1010 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001011 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001012 }
1013
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001014 private boolean isNetworkMeteredUnchecked(int networkType) {
1015 final NetworkState state = getNetworkStateUnchecked(networkType);
1016 if (state != null) {
1017 try {
1018 return mPolicyManager.isNetworkMetered(state);
1019 } catch (RemoteException e) {
1020 }
1021 }
1022 return false;
1023 }
1024
The Android Open Source Project28527d22009-03-03 19:31:44 -08001025 public boolean setRadios(boolean turnOn) {
1026 boolean result = true;
1027 enforceChangePermission();
1028 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001029 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 }
1031 return result;
1032 }
1033
1034 public boolean setRadio(int netType, boolean turnOn) {
1035 enforceChangePermission();
1036 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1037 return false;
1038 }
1039 NetworkStateTracker tracker = mNetTrackers[netType];
1040 return tracker != null && tracker.setRadio(turnOn);
1041 }
1042
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001043 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1044 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001045 public void interfaceClassDataActivityChanged(String label, boolean active) {
1046 int deviceType = Integer.parseInt(label);
1047 sendDataActivityBroadcast(deviceType, active);
1048 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001049 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001050
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001051 /**
1052 * Used to notice when the calling process dies so we can self-expire
1053 *
1054 * Also used to know if the process has cleaned up after itself when
1055 * our auto-expire timer goes off. The timer has a link to an object.
1056 *
1057 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001058 private class FeatureUser implements IBinder.DeathRecipient {
1059 int mNetworkType;
1060 String mFeature;
1061 IBinder mBinder;
1062 int mPid;
1063 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001064 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001065
1066 FeatureUser(int type, String feature, IBinder binder) {
1067 super();
1068 mNetworkType = type;
1069 mFeature = feature;
1070 mBinder = binder;
1071 mPid = getCallingPid();
1072 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001073 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001074
Robert Greenwalt2034b912009-08-12 16:08:25 -07001075 try {
1076 mBinder.linkToDeath(this, 0);
1077 } catch (RemoteException e) {
1078 binderDied();
1079 }
1080 }
1081
1082 void unlinkDeathRecipient() {
1083 mBinder.unlinkToDeath(this, 0);
1084 }
1085
1086 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001087 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001088 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1089 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001090 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001091 }
1092
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001093 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001094 if (VDBG) {
1095 log("ConnectivityService FeatureUser expire(" +
1096 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1097 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1098 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001099 stopUsingNetworkFeature(this, false);
1100 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001101
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001102 public boolean isSameUser(FeatureUser u) {
1103 if (u == null) return false;
1104
1105 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1106 }
1107
1108 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1109 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1110 TextUtils.equals(mFeature, feature)) {
1111 return true;
1112 }
1113 return false;
1114 }
1115
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001116 public String toString() {
1117 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1118 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1119 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001120 }
1121
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001122 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001123 public int startUsingNetworkFeature(int networkType, String feature,
1124 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001125 long startTime = 0;
1126 if (DBG) {
1127 startTime = SystemClock.elapsedRealtime();
1128 }
Wink Savillea7d56572011-09-21 11:05:43 -07001129 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001130 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1131 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001132 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001133 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001134 try {
1135 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1136 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001137 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001138 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001139
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001140 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001141
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001142 // TODO - move this into individual networktrackers
1143 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001144
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001145 if (mLockdownEnabled) {
1146 // Since carrier APNs usually aren't available from VPN
1147 // endpoint, mark them as unavailable.
1148 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1149 }
1150
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001151 if (mProtectedNetworks.contains(usedNetworkType)) {
1152 enforceConnectivityInternalPermission();
1153 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001154
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001155 // if UID is restricted, don't allow them to bring up metered APNs
1156 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1157 final int uidRules;
1158 synchronized (mRulesLock) {
1159 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1160 }
1161 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001162 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001163 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001164
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001165 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1166 if (network != null) {
1167 Integer currentPid = new Integer(getCallingPid());
1168 if (usedNetworkType != networkType) {
1169 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001170
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001171 if (ni.isAvailable() == false) {
1172 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1173 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001174 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001175 } else {
1176 // else make the attempt anyway - probably giving REQUEST_STARTED below
1177 if (DBG) {
1178 log("special network not available, but try anyway ni=" +
1179 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001180 }
1181 }
1182 }
1183
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001184 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001185
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001186 synchronized(this) {
1187 boolean addToList = true;
1188 if (restoreTimer < 0) {
1189 // In case there is no timer is specified for the feature,
1190 // make sure we don't add duplicate entry with the same request.
1191 for (FeatureUser u : mFeatureUsers) {
1192 if (u.isSameUser(f)) {
1193 // Duplicate user is found. Do not add.
1194 addToList = false;
1195 break;
1196 }
1197 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001198 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001199
1200 if (addToList) mFeatureUsers.add(f);
1201 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1202 // this gets used for per-pid dns when connected
1203 mNetRequestersPids[usedNetworkType].add(currentPid);
1204 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001205 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001206
1207 if (restoreTimer >= 0) {
1208 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1209 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1210 }
1211
1212 if ((ni.isConnectedOrConnecting() == true) &&
1213 !network.isTeardownRequested()) {
1214 if (ni.isConnected() == true) {
1215 final long token = Binder.clearCallingIdentity();
1216 try {
1217 // add the pid-specific dns
1218 handleDnsConfigurationChange(usedNetworkType);
1219 if (VDBG) log("special network already active");
1220 } finally {
1221 Binder.restoreCallingIdentity(token);
1222 }
Wink Saville64e3f782012-07-10 12:37:54 -07001223 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001224 }
1225 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001226 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001227 }
1228
1229 // check if the radio in play can make another contact
1230 // assume if cannot for now
1231
1232 if (DBG) {
1233 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1234 feature);
1235 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001236 if (network.reconnect()) {
1237 return PhoneConstants.APN_REQUEST_STARTED;
1238 } else {
1239 return PhoneConstants.APN_REQUEST_FAILED;
1240 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001241 } else {
1242 // need to remember this unsupported request so we respond appropriately on stop
1243 synchronized(this) {
1244 mFeatureUsers.add(f);
1245 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1246 // this gets used for per-pid dns when connected
1247 mNetRequestersPids[usedNetworkType].add(currentPid);
1248 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001249 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001250 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001251 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001252 }
Wink Saville64e3f782012-07-10 12:37:54 -07001253 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001254 } finally {
1255 if (DBG) {
1256 final long execTime = SystemClock.elapsedRealtime() - startTime;
1257 if (execTime > 250) {
1258 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1259 } else {
1260 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1261 }
1262 }
1263 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001264 }
1265
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001266 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001267 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001268 enforceChangePermission();
1269
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001270 int pid = getCallingPid();
1271 int uid = getCallingUid();
1272
1273 FeatureUser u = null;
1274 boolean found = false;
1275
1276 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001277 for (FeatureUser x : mFeatureUsers) {
1278 if (x.isSameUser(pid, uid, networkType, feature)) {
1279 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001280 found = true;
1281 break;
1282 }
1283 }
1284 }
1285 if (found && u != null) {
1286 // stop regardless of how many other time this proc had called start
1287 return stopUsingNetworkFeature(u, true);
1288 } else {
1289 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001290 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001291 return 1;
1292 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001293 }
1294
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001295 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1296 int networkType = u.mNetworkType;
1297 String feature = u.mFeature;
1298 int pid = u.mPid;
1299 int uid = u.mUid;
1300
1301 NetworkStateTracker tracker = null;
1302 boolean callTeardown = false; // used to carry our decision outside of sync block
1303
Wink Savillea7d56572011-09-21 11:05:43 -07001304 if (VDBG) {
1305 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001306 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001307
The Android Open Source Project28527d22009-03-03 19:31:44 -08001308 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001309 if (DBG) {
1310 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1311 ", net is invalid");
1312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 return -1;
1314 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001315
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001316 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1317 // sync block
1318 synchronized(this) {
1319 // check if this process still has an outstanding start request
1320 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001321 if (VDBG) {
1322 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1323 ", ignoring");
1324 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001325 return 1;
1326 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001327 u.unlinkDeathRecipient();
1328 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1329 // If we care about duplicate requests, check for that here.
1330 //
1331 // This is done to support the extension of a request - the app
1332 // can request we start the network feature again and renew the
1333 // auto-shutoff delay. Normal "stop" calls from the app though
1334 // do not pay attention to duplicate requests - in effect the
1335 // API does not refcount and a single stop will counter multiple starts.
1336 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001337 for (FeatureUser x : mFeatureUsers) {
1338 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001339 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001340 return 1;
1341 }
1342 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001343 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001344
repo syncf5de5572011-07-29 23:55:49 -07001345 // TODO - move to individual network trackers
1346 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1347
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001348 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001349 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001350 if (DBG) {
1351 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1352 " no known tracker for used net type " + usedNetworkType);
1353 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001354 return -1;
1355 }
1356 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001357 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001358 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001359
1360 final long token = Binder.clearCallingIdentity();
1361 try {
1362 reassessPidDns(pid, true);
1363 } finally {
1364 Binder.restoreCallingIdentity(token);
1365 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001366 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001367 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001368 if (VDBG) {
1369 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1370 " others still using it");
1371 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001372 return 1;
1373 }
1374 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001375 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001376 if (DBG) {
1377 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1378 " not a known feature - dropping");
1379 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001380 }
1381 }
Wink Savillea7d56572011-09-21 11:05:43 -07001382
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001383 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001384 if (DBG) {
1385 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1386 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001387 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001388 return 1;
1389 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001390 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001391 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001392 }
1393
1394 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001395 * @deprecated use requestRouteToHostAddress instead
1396 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001397 * Ensure that a network route exists to deliver traffic to the specified
1398 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001399 * @param networkType the type of the network over which traffic to the
1400 * specified host is to be routed
1401 * @param hostAddress the IP address of the host to which the route is
1402 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001403 * @return {@code true} on success, {@code false} on failure
1404 */
1405 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001406 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1407
1408 if (inetAddress == null) {
1409 return false;
1410 }
1411
1412 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1413 }
1414
1415 /**
1416 * Ensure that a network route exists to deliver traffic to the specified
1417 * host via the specified network interface.
1418 * @param networkType the type of the network over which traffic to the
1419 * specified host is to be routed
1420 * @param hostAddress the IP address of the host to which the route is
1421 * desired
1422 * @return {@code true} on success, {@code false} on failure
1423 */
1424 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001425 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001426 if (mProtectedNetworks.contains(networkType)) {
1427 enforceConnectivityInternalPermission();
1428 }
1429
The Android Open Source Project28527d22009-03-03 19:31:44 -08001430 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001431 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001432 return false;
1433 }
1434 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter0c6544b2013-11-07 22:08:24 -08001435 DetailedState netState = DetailedState.DISCONNECTED;
1436 if (tracker != null) {
1437 netState = tracker.getNetworkInfo().getDetailedState();
1438 }
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001439
Ken Mixter0c6544b2013-11-07 22:08:24 -08001440 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001441 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001442 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001443 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001444 log("requestRouteToHostAddress on down network "
1445 + "(" + networkType + ") - dropped"
1446 + " tracker=" + tracker
1447 + " netState=" + netState
1448 + " isTeardownRequested="
1449 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001450 }
1451 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001452 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001453 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001454 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001455 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001456 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001457 boolean ok = addRouteToAddress(lp, addr);
1458 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1459 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001460 } catch (UnknownHostException e) {
1461 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1462 } finally {
1463 Binder.restoreCallingIdentity(token);
1464 }
Wink Saville32506bc2013-06-29 21:10:57 -07001465 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001466 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001467 }
1468
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001469 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001470 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001471 }
1472
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001473 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001474 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001475 }
1476
Robert Greenwalt98107422011-07-22 11:55:33 -07001477 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001478 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001479 }
1480
1481 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001482 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001483 }
1484
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001485 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1486 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001487 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001488 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001489 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001490 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001491 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001492 if (bestRoute.getGateway().equals(addr)) {
1493 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001494 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001495 } else {
1496 // if we will connect to this through another route, add a direct route
1497 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001498 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001499 }
1500 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001501 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001502 }
1503
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001504 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1505 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001506 if ((lp == null) || (r == null)) {
1507 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001508 return false;
1509 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001510
1511 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001512 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001513 return false;
1514 }
1515
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001516 String ifaceName = r.getInterface();
1517 if(ifaceName == null) {
1518 loge("Error modifying route - no interface name");
1519 return false;
1520 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001521 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001522 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001523 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001524 if (bestRoute.getGateway().equals(r.getGateway())) {
1525 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001526 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001527 } else {
1528 // if we will connect to our gateway through another route, add a direct
1529 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001530 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1531 bestRoute.getGateway(),
1532 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001533 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001534 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001535 }
1536 }
1537 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001538 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001539 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001540 if (toDefaultTable) {
1541 mAddedRoutes.add(r); // only track default table - only one apps can effect
1542 mNetd.addRoute(ifaceName, r);
1543 } else {
1544 mNetd.addSecondaryRoute(ifaceName, r);
1545 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001546 } catch (Exception e) {
1547 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001548 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001549 return false;
1550 }
1551 } else {
1552 // if we remove this one and there are no more like it, then refcount==0 and
1553 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001554 if (toDefaultTable) {
1555 mAddedRoutes.remove(r);
1556 if (mAddedRoutes.contains(r) == false) {
1557 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1558 try {
1559 mNetd.removeRoute(ifaceName, r);
1560 } catch (Exception e) {
1561 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001562 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001563 return false;
1564 }
1565 } else {
1566 if (VDBG) log("not removing " + r + " as it's still in use");
1567 }
1568 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001569 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001570 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001571 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001572 } catch (Exception e) {
1573 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001574 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001575 return false;
1576 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001577 }
1578 }
1579 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001580 }
1581
1582 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001583 * @see ConnectivityManager#getMobileDataEnabled()
1584 */
1585 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001586 // TODO: This detail should probably be in DataConnectionTracker's
1587 // which is where we store the value and maybe make this
1588 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001589 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001590 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1591 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001592 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001593 return retVal;
1594 }
1595
Robert Greenwalt34848c02011-03-25 13:09:25 -07001596 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001597 enforceConnectivityInternalPermission();
1598
Robert Greenwalt34848c02011-03-25 13:09:25 -07001599 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1600 (met ? ENABLED : DISABLED), networkType));
1601 }
1602
1603 private void handleSetDependencyMet(int networkType, boolean met) {
1604 if (mNetTrackers[networkType] != null) {
1605 if (DBG) {
1606 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1607 }
1608 mNetTrackers[networkType].setDependencyMet(met);
1609 }
1610 }
1611
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001612 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1613 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001614 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001615 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001616 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001617 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001618 }
1619
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001620 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001621 // skip update when we've already applied rules
1622 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1623 if (oldRules == uidRules) return;
1624
1625 mUidRules.put(uid, uidRules);
1626 }
1627
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001628 // TODO: notify UID when it has requested targeted updates
1629 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001630
1631 @Override
1632 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001633 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001634 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001635 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001636 }
1637
1638 synchronized (mRulesLock) {
1639 mMeteredIfaces.clear();
1640 for (String iface : meteredIfaces) {
1641 mMeteredIfaces.add(iface);
1642 }
1643 }
1644 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001645
1646 @Override
1647 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1648 // caller is NPMS, since we only register with them
1649 if (LOGD_RULES) {
1650 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1651 }
1652
1653 // kick off connectivity change broadcast for active network, since
1654 // global background policy change is radical.
1655 final int networkType = mActiveDefaultNetwork;
1656 if (isNetworkTypeValid(networkType)) {
1657 final NetworkStateTracker tracker = mNetTrackers[networkType];
1658 if (tracker != null) {
1659 final NetworkInfo info = tracker.getNetworkInfo();
1660 if (info != null && info.isConnected()) {
1661 sendConnectedBroadcast(info);
1662 }
1663 }
1664 }
1665 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001666 };
1667
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001668 /**
1669 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1670 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001671 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001672 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001673 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001674
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001675 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001676 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001677 }
1678
1679 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001680 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001681 if (VDBG) {
1682 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001683 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001684 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1685 }
tk.mun5eee1042012-01-06 10:43:52 +09001686 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1687 if (VDBG) {
1688 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1689 }
1690 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1691 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001692 }
1693
1694 @Override
1695 public void setPolicyDataEnable(int networkType, boolean enabled) {
1696 // only someone like NPMS should only be calling us
1697 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1698
1699 mHandler.sendMessage(mHandler.obtainMessage(
1700 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1701 }
1702
1703 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1704 if (isNetworkTypeValid(networkType)) {
1705 final NetworkStateTracker tracker = mNetTrackers[networkType];
1706 if (tracker != null) {
1707 tracker.setPolicyDataEnable(enabled);
1708 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001709 }
1710 }
1711
The Android Open Source Project28527d22009-03-03 19:31:44 -08001712 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001713 mContext.enforceCallingOrSelfPermission(
1714 android.Manifest.permission.ACCESS_NETWORK_STATE,
1715 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001716 }
1717
1718 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001719 mContext.enforceCallingOrSelfPermission(
1720 android.Manifest.permission.CHANGE_NETWORK_STATE,
1721 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001722 }
1723
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001724 // TODO Make this a special check when it goes public
1725 private void enforceTetherChangePermission() {
1726 mContext.enforceCallingOrSelfPermission(
1727 android.Manifest.permission.CHANGE_NETWORK_STATE,
1728 "ConnectivityService");
1729 }
1730
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001731 private void enforceTetherAccessPermission() {
1732 mContext.enforceCallingOrSelfPermission(
1733 android.Manifest.permission.ACCESS_NETWORK_STATE,
1734 "ConnectivityService");
1735 }
1736
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001737 private void enforceConnectivityInternalPermission() {
1738 mContext.enforceCallingOrSelfPermission(
1739 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1740 "ConnectivityService");
1741 }
1742
The Android Open Source Project28527d22009-03-03 19:31:44 -08001743 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001744 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1745 * network, we ignore it. If it is for the active network, we send out a
1746 * broadcast. But first, we check whether it might be possible to connect
1747 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001748 * @param info the {@code NetworkInfo} for the network
1749 */
1750 private void handleDisconnect(NetworkInfo info) {
1751
Robert Greenwalt2034b912009-08-12 16:08:25 -07001752 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001753
Robert Greenwalt2034b912009-08-12 16:08:25 -07001754 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001755
1756 // Remove idletimer previously setup in {@code handleConnect}
1757 removeDataActivityTracking(prevNetType);
1758
The Android Open Source Project28527d22009-03-03 19:31:44 -08001759 /*
1760 * If the disconnected network is not the active one, then don't report
1761 * this as a loss of connectivity. What probably happened is that we're
1762 * getting the disconnect for a network that we explicitly disabled
1763 * in accordance with network preference policies.
1764 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001765 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001766 List<Integer> pids = mNetRequestersPids[prevNetType];
1767 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001768 // will remove them because the net's no longer connected
1769 // need to do this now as only now do we know the pids and
1770 // can properly null things that are no longer referenced.
1771 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001772 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001773 }
1774
The Android Open Source Project28527d22009-03-03 19:31:44 -08001775 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001776 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001777 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001778 if (info.isFailover()) {
1779 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1780 info.setFailover(false);
1781 }
1782 if (info.getReason() != null) {
1783 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1784 }
1785 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001786 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1787 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001788 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001789
Robert Greenwalt34848c02011-03-25 13:09:25 -07001790 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001791 tryFailover(prevNetType);
1792 if (mActiveDefaultNetwork != -1) {
1793 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001794 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1795 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001796 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001797 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1798 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001799 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001800 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001801
1802 // Reset interface if no other connections are using the same interface
1803 boolean doReset = true;
1804 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1805 if (linkProperties != null) {
1806 String oldIface = linkProperties.getInterfaceName();
1807 if (TextUtils.isEmpty(oldIface) == false) {
1808 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1809 if (networkStateTracker == null) continue;
1810 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1811 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1812 LinkProperties l = networkStateTracker.getLinkProperties();
1813 if (l == null) continue;
1814 if (oldIface.equals(l.getInterfaceName())) {
1815 doReset = false;
1816 break;
1817 }
1818 }
1819 }
1820 }
1821 }
1822
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001823 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001824 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001825
Jeff Sharkey971cd162011-08-29 16:02:57 -07001826 final Intent immediateIntent = new Intent(intent);
1827 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1828 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001829 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001830 /*
1831 * If the failover network is already connected, then immediately send
1832 * out a followup broadcast indicating successful failover
1833 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001834 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001835 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1836 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001837 }
1838 }
1839
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001840 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001841 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001842 * If this is a default network, check if other defaults are available.
1843 * Try to reconnect on all available and let them hash it out when
1844 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001845 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001846 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001847 if (mActiveDefaultNetwork == prevNetType) {
1848 mActiveDefaultNetwork = -1;
1849 }
1850
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001851 // don't signal a reconnect for anything lower or equal priority than our
1852 // current connected default
1853 // TODO - don't filter by priority now - nice optimization but risky
1854// int currentPriority = -1;
1855// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001856// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001857// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001858 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001859 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001860 if (mNetConfigs[checkType] == null) continue;
1861 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001862 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001863
1864// Enabling the isAvailable() optimization caused mobile to not get
1865// selected if it was in the middle of error handling. Specifically
1866// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1867// would not be available and we wouldn't get connected to anything.
1868// So removing the isAvailable() optimization below for now. TODO: This
1869// optimization should work and we need to investigate why it doesn't work.
1870// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1871// complete before it is really complete.
1872// if (!mNetTrackers[checkType].isAvailable()) continue;
1873
Robert Greenwalt34848c02011-03-25 13:09:25 -07001874// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001875
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001876 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1877 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1878 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1879 checkInfo.setFailover(true);
1880 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001881 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001882 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001883 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001884 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001885 }
1886
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001887 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001888 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001889 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1890 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001891 }
1892
Wink Saville4f0de1e2011-08-04 15:01:58 -07001893 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001894 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1895 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001896 }
1897
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001898 private void sendInetConditionBroadcast(NetworkInfo info) {
1899 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1900 }
1901
Wink Saville4f0de1e2011-08-04 15:01:58 -07001902 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001903 if (mLockdownTracker != null) {
1904 info = mLockdownTracker.augmentNetworkInfo(info);
1905 }
1906
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001907 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001908 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001909 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001910 if (info.isFailover()) {
1911 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1912 info.setFailover(false);
1913 }
1914 if (info.getReason() != null) {
1915 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1916 }
1917 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001918 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1919 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001920 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001921 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001922 return intent;
1923 }
1924
1925 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1926 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1927 }
1928
1929 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1930 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001931 }
1932
Haoyu Baib5da5752012-06-20 14:29:57 -07001933 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1934 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1935 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1936 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001937 final long ident = Binder.clearCallingIdentity();
1938 try {
1939 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1940 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1941 } finally {
1942 Binder.restoreCallingIdentity(ident);
1943 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001944 }
1945
The Android Open Source Project28527d22009-03-03 19:31:44 -08001946 /**
1947 * Called when an attempt to fail over to another network has failed.
1948 * @param info the {@link NetworkInfo} for the failed network
1949 */
1950 private void handleConnectionFailure(NetworkInfo info) {
1951 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001952
Robert Greenwalt2034b912009-08-12 16:08:25 -07001953 String reason = info.getReason();
1954 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001955
Robert Greenwalte981bc52010-10-08 16:35:52 -07001956 String reasonText;
1957 if (reason == null) {
1958 reasonText = ".";
1959 } else {
1960 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001961 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001962 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001963
1964 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001965 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001966 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001967 if (getActiveNetworkInfo() == null) {
1968 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1969 }
1970 if (reason != null) {
1971 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1972 }
1973 if (extraInfo != null) {
1974 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1975 }
1976 if (info.isFailover()) {
1977 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1978 info.setFailover(false);
1979 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001980
Robert Greenwalt34848c02011-03-25 13:09:25 -07001981 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001982 tryFailover(info.getType());
1983 if (mActiveDefaultNetwork != -1) {
1984 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001985 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1986 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001987 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001988 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1989 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001990 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001991
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001992 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001993
1994 final Intent immediateIntent = new Intent(intent);
1995 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1996 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001997 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001998 /*
1999 * If the failover network is already connected, then immediately send
2000 * out a followup broadcast indicating successful failover
2001 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002002 if (mActiveDefaultNetwork != -1) {
2003 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002004 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002005 }
2006
2007 private void sendStickyBroadcast(Intent intent) {
2008 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002009 if (!mSystemReady) {
2010 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002011 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002012 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002013 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002014 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002015 }
2016
Dianne Hackborne588ca12012-09-04 18:48:37 -07002017 final long ident = Binder.clearCallingIdentity();
2018 try {
2019 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2020 } finally {
2021 Binder.restoreCallingIdentity(ident);
2022 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002023 }
2024 }
2025
Wink Saville4f0de1e2011-08-04 15:01:58 -07002026 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2027 if (delayMs <= 0) {
2028 sendStickyBroadcast(intent);
2029 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002030 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002031 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2032 + intent.getAction());
2033 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002034 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2035 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2036 }
2037 }
2038
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002039 void systemReady() {
2040 synchronized(this) {
2041 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002042 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002043 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002044 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002045 }
2046 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002047 // load the global proxy at startup
2048 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002049
2050 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2051 // for user to unlock device.
2052 if (!updateLockdownVpn()) {
2053 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2054 mContext.registerReceiver(mUserPresentReceiver, filter);
2055 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002056 }
2057
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002058 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2059 @Override
2060 public void onReceive(Context context, Intent intent) {
2061 // Try creating lockdown tracker, since user present usually means
2062 // unlocked keystore.
2063 if (updateLockdownVpn()) {
2064 mContext.unregisterReceiver(this);
2065 }
2066 }
2067 };
2068
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002069 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2070 if ((type != mNetworkPreference &&
2071 mNetConfigs[mActiveDefaultNetwork].priority >
2072 mNetConfigs[type].priority) ||
2073 mNetworkPreference == mActiveDefaultNetwork) return false;
2074 return true;
2075 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002077 private void handleConnect(NetworkInfo info) {
2078 final int newNetType = info.getType();
2079
2080 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002081
The Android Open Source Project28527d22009-03-03 19:31:44 -08002082 // snapshot isFailover, because sendConnectedBroadcast() resets it
2083 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002084 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002085 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086
Robert Greenwalt2034b912009-08-12 16:08:25 -07002087 // if this is a default net and other default is running
2088 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002089 if (mNetConfigs[newNetType].isDefault()) {
2090 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2091 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002092 // tear down the other
2093 NetworkStateTracker otherNet =
2094 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002095 if (DBG) {
2096 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002097 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002098 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002099 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002100 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002101 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002102 return;
2103 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002104 } else {
2105 // don't accept this one
2106 if (VDBG) {
2107 log("Not broadcasting CONNECT_ACTION " +
2108 "to torn down network " + info.getTypeName());
2109 }
2110 teardown(thisNet);
2111 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002112 }
2113 }
2114 synchronized (ConnectivityService.this) {
2115 // have a new default network, release the transition wakelock in a second
2116 // if it's held. The second pause is to allow apps to reconnect over the
2117 // new network
2118 if (mNetTransitionWakeLock.isHeld()) {
2119 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002120 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002121 mNetTransitionWakeLockSerialNumber, 0),
2122 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002123 }
2124 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002125 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002126 // this will cause us to come up initially as unconnected and switching
2127 // to connected after our normal pause unless somebody reports us as reall
2128 // disconnected
2129 mDefaultInetConditionPublished = 0;
2130 mDefaultConnectionSequence++;
2131 mInetConditionChangeInFlight = false;
2132 // Don't do this - if we never sign in stay, grey
2133 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002134 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002135 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002136 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002137 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002138 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002139
2140 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002141 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002142 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002143 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002144 } catch (RemoteException e) {
2145 // ignored; service lives in system_server
2146 }
2147 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002148 }
2149
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002150 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2151 if (DBG) log("Captive portal check " + info);
2152 int type = info.getType();
2153 final NetworkStateTracker thisNet = mNetTrackers[type];
2154 if (mNetConfigs[type].isDefault()) {
2155 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2156 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2157 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002158 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002159 return;
2160 } else {
2161 if (DBG) log("Tear down low priority net " + info.getTypeName());
2162 teardown(thisNet);
2163 return;
2164 }
2165 }
2166 }
2167
2168 thisNet.captivePortalCheckComplete();
2169 }
2170
2171 /** @hide */
2172 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002173 enforceConnectivityInternalPermission();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002174 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002175 }
2176
The Android Open Source Project28527d22009-03-03 19:31:44 -08002177 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002178 * Setup data activity tracking for the given network interface.
2179 *
2180 * Every {@code setupDataActivityTracking} should be paired with a
2181 * {@link removeDataActivityTracking} for cleanup.
2182 */
2183 private void setupDataActivityTracking(int type) {
2184 final NetworkStateTracker thisNet = mNetTrackers[type];
2185 final String iface = thisNet.getLinkProperties().getInterfaceName();
2186
2187 final int timeout;
2188
2189 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002190 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2191 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002192 0);
2193 // Canonicalize mobile network type
2194 type = ConnectivityManager.TYPE_MOBILE;
2195 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002196 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2197 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002198 0);
2199 } else {
2200 // do not track any other networks
2201 timeout = 0;
2202 }
2203
2204 if (timeout > 0 && iface != null) {
2205 try {
2206 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2207 } catch (RemoteException e) {
2208 }
2209 }
2210 }
2211
2212 /**
2213 * Remove data activity tracking when network disconnects.
2214 */
2215 private void removeDataActivityTracking(int type) {
2216 final NetworkStateTracker net = mNetTrackers[type];
2217 final String iface = net.getLinkProperties().getInterfaceName();
2218
2219 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2220 ConnectivityManager.TYPE_WIFI == type)) {
2221 try {
2222 // the call fails silently if no idletimer setup for this interface
2223 mNetd.removeIdleTimer(iface);
2224 } catch (RemoteException e) {
2225 }
2226 }
2227 }
2228
2229 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002230 * After a change in the connectivity state of a network. We're mainly
2231 * concerned with making sure that the list of DNS servers is set up
2232 * according to which networks are connected, and ensuring that the
2233 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002234 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002235 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002236 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2237
The Android Open Source Project28527d22009-03-03 19:31:44 -08002238 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002239 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002240 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002241 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002242 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002243
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002244 LinkProperties curLp = mCurrentLinkProperties[netType];
2245 LinkProperties newLp = null;
2246
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002247 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002248 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002249 if (VDBG) {
2250 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2251 " doReset=" + doReset + " resetMask=" + resetMask +
2252 "\n curLp=" + curLp +
2253 "\n newLp=" + newLp);
2254 }
2255
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002256 if (curLp != null) {
2257 if (curLp.isIdenticalInterfaceName(newLp)) {
2258 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2259 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2260 for (LinkAddress linkAddr : car.removed) {
2261 if (linkAddr.getAddress() instanceof Inet4Address) {
2262 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2263 }
2264 if (linkAddr.getAddress() instanceof Inet6Address) {
2265 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2266 }
Wink Saville051a6642011-07-13 13:44:13 -07002267 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002268 if (DBG) {
2269 log("handleConnectivityChange: addresses changed" +
2270 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2271 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002272 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002273 } else {
2274 if (DBG) {
2275 log("handleConnectivityChange: address are the same reset per doReset" +
2276 " linkProperty[" + netType + "]:" +
2277 " resetMask=" + resetMask);
2278 }
Wink Saville051a6642011-07-13 13:44:13 -07002279 }
2280 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002281 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002282 if (DBG) {
2283 log("handleConnectivityChange: interface not not equivalent reset both" +
2284 " linkProperty[" + netType + "]:" +
2285 " resetMask=" + resetMask);
2286 }
Wink Saville051a6642011-07-13 13:44:13 -07002287 }
Wink Saville051a6642011-07-13 13:44:13 -07002288 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002289 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002290 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002291 }
2292 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002293 if (VDBG) {
2294 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2295 " doReset=" + doReset + " resetMask=" + resetMask +
2296 "\n curLp=" + curLp +
2297 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002298 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002300 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002301 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002302
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002303 if (resetMask != 0 || resetDns) {
Robert Greenwalt4398f342013-05-23 18:33:06 -07002304 if (curLp != null) {
2305 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002306 if (TextUtils.isEmpty(iface) == false) {
2307 if (resetMask != 0) {
2308 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2309 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002310
Lorenzo Colitti63839822013-03-20 19:22:58 +09002311 // Tell VPN the interface is down. It is a temporary
2312 // but effective fix to make VPN aware of the change.
2313 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2314 mVpn.interfaceStatusChanged(iface, false);
2315 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002316 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002317 if (resetDns) {
2318 flushVmDnsCache();
2319 if (VDBG) log("resetting DNS cache for " + iface);
2320 try {
2321 mNetd.flushInterfaceDnsCache(iface);
2322 } catch (Exception e) {
2323 // never crash - catch them all
2324 if (DBG) loge("Exception resetting dns cache: " + e);
2325 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002326 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002327 } else {
2328 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002329 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002330 }
2331 }
2332 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002333
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002334 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002335 NetworkStateTracker tracker = mNetTrackers[netType];
2336 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002337 // If the connection was previously using clat, but is not using it now, stop the clat
2338 // daemon. Normally, this happens automatically when the connection disconnects, but if
2339 // the disconnect is not reported, or if the connection's LinkProperties changed for
2340 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2341 // still be running. If it's not running, then stopping it is a no-op.
2342 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2343 mClat.stopClat();
2344 }
2345 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002346 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2347 mClat.startClat(tracker);
2348 } else {
2349 mClat.stopClat();
2350 }
2351 }
2352
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002353 // TODO: Temporary notifying upstread change to Tethering.
2354 // @see bug/4455071
2355 /** Notify TetheringService if interface name has been changed. */
2356 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002357 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002358 if (isTetheringSupported()) {
2359 mTethering.handleTetherIfaceChange();
2360 }
2361 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002362 }
2363
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002364 /**
2365 * Add and remove routes using the old properties (null if not previously connected),
2366 * new properties (null if becoming disconnected). May even be double null, which
2367 * is a noop.
2368 * Uses isLinkDefault to determine if default routes should be set or conversely if
2369 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002370 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002371 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002372 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2373 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002374 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002375 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2376 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002377 if (curLp != null) {
2378 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002379 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002380 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002381 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002382 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002383 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002384 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002385
Robert Greenwalt8d777252011-08-15 12:31:55 -07002386 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2387
Robert Greenwalt98107422011-07-22 11:55:33 -07002388 for (RouteInfo r : routeDiff.removed) {
2389 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002390 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2391 }
2392 if (isLinkDefault == false) {
2393 // remove from a secondary route table
2394 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002395 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002396 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002397
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002398 if (!isLinkDefault) {
2399 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002400 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002401 // routes changed - remove all old dns entries and add new
2402 if (curLp != null) {
2403 for (InetAddress oldDns : curLp.getDnses()) {
2404 removeRouteToAddress(curLp, oldDns);
2405 }
2406 }
2407 if (newLp != null) {
2408 for (InetAddress newDns : newLp.getDnses()) {
2409 addRouteToAddress(newLp, newDns);
2410 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002411 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002412 } else {
2413 // no change in routes, check for change in dns themselves
2414 for (InetAddress oldDns : dnsDiff.removed) {
2415 removeRouteToAddress(curLp, oldDns);
2416 }
2417 for (InetAddress newDns : dnsDiff.added) {
2418 addRouteToAddress(newLp, newDns);
2419 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002420 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002421 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002422
2423 for (RouteInfo r : routeDiff.added) {
2424 if (isLinkDefault || ! r.isDefaultRoute()) {
2425 addRoute(newLp, r, TO_DEFAULT_TABLE);
2426 } else {
2427 // add to a secondary route table
2428 addRoute(newLp, r, TO_SECONDARY_TABLE);
2429
2430 // many radios add a default route even when we don't want one.
2431 // remove the default route unless somebody else has asked for it
2432 String ifaceName = newLp.getInterfaceName();
2433 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2434 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2435 try {
2436 mNetd.removeRoute(ifaceName, r);
2437 } catch (Exception e) {
2438 // never crash - catch them all
2439 if (DBG) loge("Exception trying to remove a route: " + e);
2440 }
2441 }
2442 }
2443 }
2444
Robert Greenwalt8d777252011-08-15 12:31:55 -07002445 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002446 }
2447
2448
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002449 /**
2450 * Reads the network specific TCP buffer sizes from SystemProperties
2451 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2452 * wide use
2453 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002454 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002455 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002456 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002457
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002458 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002459 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002460
2461 // Setting to default values so we won't be stuck to previous values
2462 key = "net.tcp.buffersize.default";
2463 bufferSizes = SystemProperties.get(key);
2464 }
2465
2466 // Set values in kernel
2467 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002468 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002469 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002470 + "] which comes from [" + key + "]");
2471 }
2472 setBufferSize(bufferSizes);
2473 }
2474 }
2475
2476 /**
2477 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2478 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2479 *
2480 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2481 * writeMin, writeInitial, writeMax"
2482 */
2483 private void setBufferSize(String bufferSizes) {
2484 try {
2485 String[] values = bufferSizes.split(",");
2486
2487 if (values.length == 6) {
2488 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002489 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2490 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2491 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2492 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2493 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2494 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002495 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002496 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002497 }
2498 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002499 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002500 }
2501 }
2502
Robert Greenwalt2034b912009-08-12 16:08:25 -07002503 /**
2504 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2505 * on the highest priority active net which this process requested.
2506 * If there aren't any, clear it out
2507 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002508 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002509 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002510 if (VDBG) log("reassessPidDns for pid " + pid);
2511 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002512 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002513 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002514 continue;
2515 }
2516 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002517 if (nt.getNetworkInfo().isConnected() &&
2518 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002519 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002520 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002521 if (mNetRequestersPids[i].contains(myPid)) {
2522 try {
2523 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2524 } catch (Exception e) {
2525 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002526 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002527 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002528 }
2529 }
2530 }
2531 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002532 try {
2533 mNetd.clearDnsInterfaceForPid(pid);
2534 } catch (Exception e) {
2535 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002536 }
2537 }
2538
Mattias Falkd697aa22011-08-23 14:15:13 +02002539 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002540 /*
2541 * Tell the VMs to toss their DNS caches
2542 */
2543 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2544 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002545 /*
2546 * Connectivity events can happen before boot has completed ...
2547 */
2548 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002549 final long ident = Binder.clearCallingIdentity();
2550 try {
2551 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2552 } finally {
2553 Binder.restoreCallingIdentity(ident);
2554 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002555 }
2556
Chia-chi Yehcc844502011-07-14 18:01:57 -07002557 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002558 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002559 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002560 int last = 0;
2561 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002562 dnses = new ArrayList();
2563 dnses.add(mDefaultDns);
2564 if (DBG) {
2565 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002566 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002567 }
2568
Mattias Falkd697aa22011-08-23 14:15:13 +02002569 try {
2570 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2571 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002572 for (InetAddress dns : dnses) {
2573 ++last;
2574 String key = "net.dns" + last;
2575 String value = dns.getHostAddress();
2576 SystemProperties.set(key, value);
2577 }
2578 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2579 String key = "net.dns" + i;
2580 SystemProperties.set(key, "");
2581 }
2582 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002583 } catch (Exception e) {
2584 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002585 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002586 }
2587
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002588 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002589 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002590 NetworkStateTracker nt = mNetTrackers[netType];
2591 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002592 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002593 if (p == null) return;
2594 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002595 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002596 String network = nt.getNetworkInfo().getTypeName();
2597 synchronized (mDnsLock) {
2598 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002599 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002600 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002601 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002602 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002603 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002604 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002605 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002606 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002607 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002608 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002609 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002610 List<Integer> pids = mNetRequestersPids[netType];
2611 for (Integer pid : pids) {
2612 try {
2613 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2614 } catch (Exception e) {
2615 Slog.e(TAG, "exception setting interface for pid: " + e);
2616 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002617 }
2618 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002619 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002620 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002621 }
2622
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002623 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002624 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2625 NETWORK_RESTORE_DELAY_PROP_NAME);
2626 if(restoreDefaultNetworkDelayStr != null &&
2627 restoreDefaultNetworkDelayStr.length() != 0) {
2628 try {
2629 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2630 } catch (NumberFormatException e) {
2631 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002632 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002633 // if the system property isn't set, use the value for the apn type
2634 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2635
2636 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2637 (mNetConfigs[networkType] != null)) {
2638 ret = mNetConfigs[networkType].restoreTime;
2639 }
2640 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002641 }
2642
2643 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002644 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2645 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002646 if (mContext.checkCallingOrSelfPermission(
2647 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002648 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002649 pw.println("Permission Denial: can't dump ConnectivityService " +
2650 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2651 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002652 return;
2653 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002654
2655 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002656 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002657 for (int i = 0; i < mNetTrackers.length; i++) {
2658 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002659 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002660 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2661 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002662 if (nst.getNetworkInfo().isConnected()) {
2663 pw.println("Active network: " + nst.getNetworkInfo().
2664 getTypeName());
2665 }
2666 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002667 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002668 pw.println(nst);
2669 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002670 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002671 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002672 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002673
2674 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002675 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002676 for (int net : mPriorityList) {
2677 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002678 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002679 pidString = pidString + pid.toString() + ", ";
2680 }
2681 pw.println(pidString);
2682 }
2683 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002684 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002685
2686 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002687 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002688 for (Object requester : mFeatureUsers) {
2689 pw.println(requester.toString());
2690 }
2691 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002692 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002693
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002694 synchronized (this) {
2695 pw.println("NetworkTranstionWakeLock is currently " +
2696 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2697 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2698 }
2699 pw.println();
2700
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002701 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002702
2703 if (mInetLog != null) {
2704 pw.println();
2705 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002706 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002707 for(int i = 0; i < mInetLog.size(); i++) {
2708 pw.println(mInetLog.get(i));
2709 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002710 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002711 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002712 }
2713
Robert Greenwalt2034b912009-08-12 16:08:25 -07002714 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002715 private class NetworkStateTrackerHandler extends Handler {
2716 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002717 super(looper);
2718 }
2719
The Android Open Source Project28527d22009-03-03 19:31:44 -08002720 @Override
2721 public void handleMessage(Message msg) {
2722 NetworkInfo info;
2723 switch (msg.what) {
2724 case NetworkStateTracker.EVENT_STATE_CHANGED:
2725 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002726 int type = info.getType();
2727 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002728
Wink Savillea7d56572011-09-21 11:05:43 -07002729 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2730 (state == NetworkInfo.State.DISCONNECTED)) {
2731 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002732 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002733 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002734 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002735
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002736 EventLogTags.writeConnectivityStateChanged(
2737 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002738
2739 if (info.getDetailedState() ==
2740 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002741 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002742 } else if (info.getDetailedState() ==
2743 DetailedState.CAPTIVE_PORTAL_CHECK) {
2744 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002745 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002746 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002747 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002748 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002749 // the logic here is, handle SUSPENDED the same as
2750 // DISCONNECTED. The only difference being we are
2751 // broadcasting an intent with NetworkInfo that's
2752 // suspended. This allows the applications an
2753 // opportunity to handle DISCONNECTED and SUSPENDED
2754 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002755 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002756 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002757 handleConnect(info);
2758 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002759 if (mLockdownTracker != null) {
2760 mLockdownTracker.onNetworkInfoChanged(info);
2761 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002762 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002763 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002764 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002765 // TODO: Temporary allowing network configuration
2766 // change not resetting sockets.
2767 // @see bug/4455071
2768 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002769 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002770 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2771 info = (NetworkInfo) msg.obj;
2772 type = info.getType();
2773 updateNetworkSettings(mNetTrackers[type]);
2774 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002775 }
2776 }
2777 }
2778
2779 private class InternalHandler extends Handler {
2780 public InternalHandler(Looper looper) {
2781 super(looper);
2782 }
2783
2784 @Override
2785 public void handleMessage(Message msg) {
2786 NetworkInfo info;
2787 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002788 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002789 String causedBy = null;
2790 synchronized (ConnectivityService.this) {
2791 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2792 mNetTransitionWakeLock.isHeld()) {
2793 mNetTransitionWakeLock.release();
2794 causedBy = mNetTransitionWakeLockCausedBy;
2795 }
2796 }
2797 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002798 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002799 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002800 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002801 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002802 FeatureUser u = (FeatureUser)msg.obj;
2803 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002804 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002805 case EVENT_INET_CONDITION_CHANGE:
2806 {
2807 int netType = msg.arg1;
2808 int condition = msg.arg2;
2809 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002810 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002811 }
2812 case EVENT_INET_CONDITION_HOLD_END:
2813 {
2814 int netType = msg.arg1;
2815 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00002816 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002817 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002818 }
2819 case EVENT_SET_NETWORK_PREFERENCE:
2820 {
2821 int preference = msg.arg1;
2822 handleSetNetworkPreference(preference);
2823 break;
2824 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002825 case EVENT_SET_MOBILE_DATA:
2826 {
2827 boolean enabled = (msg.arg1 == ENABLED);
2828 handleSetMobileData(enabled);
2829 break;
2830 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002831 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2832 {
2833 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002834 break;
2835 }
2836 case EVENT_SET_DEPENDENCY_MET:
2837 {
2838 boolean met = (msg.arg1 == ENABLED);
2839 handleSetDependencyMet(msg.arg2, met);
2840 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002841 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002842 case EVENT_RESTORE_DNS:
2843 {
2844 if (mActiveDefaultNetwork != -1) {
2845 handleDnsConfigurationChange(mActiveDefaultNetwork);
2846 }
2847 break;
2848 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002849 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2850 {
2851 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002852 sendStickyBroadcast(intent);
2853 break;
2854 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002855 case EVENT_SET_POLICY_DATA_ENABLE: {
2856 final int networkType = msg.arg1;
2857 final boolean enabled = msg.arg2 == ENABLED;
2858 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002859 break;
2860 }
2861 case EVENT_VPN_STATE_CHANGED: {
2862 if (mLockdownTracker != null) {
2863 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2864 }
2865 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002866 }
Wink Saville32506bc2013-06-29 21:10:57 -07002867 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2868 int tag = mEnableFailFastMobileDataTag.get();
2869 if (msg.arg1 == tag) {
2870 MobileDataStateTracker mobileDst =
2871 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2872 if (mobileDst != null) {
2873 mobileDst.setEnableFailFastMobileData(msg.arg2);
2874 }
2875 } else {
2876 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2877 + " != tag:" + tag);
2878 }
2879 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002880 }
2881 }
2882 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002883
2884 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002885 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002886 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002887
2888 if (isTetheringSupported()) {
2889 return mTethering.tether(iface);
2890 } else {
2891 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2892 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002893 }
2894
2895 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002896 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002897 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002898
2899 if (isTetheringSupported()) {
2900 return mTethering.untether(iface);
2901 } else {
2902 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2903 }
2904 }
2905
2906 // javadoc from interface
2907 public int getLastTetherError(String iface) {
2908 enforceTetherAccessPermission();
2909
2910 if (isTetheringSupported()) {
2911 return mTethering.getLastTetherError(iface);
2912 } else {
2913 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2914 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002915 }
2916
2917 // TODO - proper iface API for selection by property, inspection, etc
2918 public String[] getTetherableUsbRegexs() {
2919 enforceTetherAccessPermission();
2920 if (isTetheringSupported()) {
2921 return mTethering.getTetherableUsbRegexs();
2922 } else {
2923 return new String[0];
2924 }
2925 }
2926
2927 public String[] getTetherableWifiRegexs() {
2928 enforceTetherAccessPermission();
2929 if (isTetheringSupported()) {
2930 return mTethering.getTetherableWifiRegexs();
2931 } else {
2932 return new String[0];
2933 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002934 }
2935
Danica Chang96567052010-08-11 14:54:43 -07002936 public String[] getTetherableBluetoothRegexs() {
2937 enforceTetherAccessPermission();
2938 if (isTetheringSupported()) {
2939 return mTethering.getTetherableBluetoothRegexs();
2940 } else {
2941 return new String[0];
2942 }
2943 }
2944
Mike Lockwooded4a1742011-07-19 13:04:47 -07002945 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002946 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002947 if (isTetheringSupported()) {
2948 return mTethering.setUsbTethering(enable);
2949 } else {
2950 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2951 }
2952 }
2953
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002954 // TODO - move iface listing, queries, etc to new module
2955 // javadoc from interface
2956 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002957 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002958 return mTethering.getTetherableIfaces();
2959 }
2960
2961 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002962 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002963 return mTethering.getTetheredIfaces();
2964 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002965
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002966 @Override
2967 public String[] getTetheredIfacePairs() {
2968 enforceTetherAccessPermission();
2969 return mTethering.getTetheredIfacePairs();
2970 }
2971
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002972 public String[] getTetheringErroredIfaces() {
2973 enforceTetherAccessPermission();
2974 return mTethering.getErroredIfaces();
2975 }
2976
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002977 // if ro.tether.denied = true we default to no tethering
2978 // gservices could set the secure setting to 1 though to enable it on a build where it
2979 // had previously been turned off.
2980 public boolean isTetheringSupported() {
2981 enforceTetherAccessPermission();
2982 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07002983 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2984 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002985 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002986 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002987
2988 // An API NetworkStateTrackers can call when they lose their network.
2989 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2990 // whichever happens first. The timer is started by the first caller and not
2991 // restarted by subsequent callers.
2992 public void requestNetworkTransitionWakelock(String forWhom) {
2993 enforceConnectivityInternalPermission();
2994 synchronized (this) {
2995 if (mNetTransitionWakeLock.isHeld()) return;
2996 mNetTransitionWakeLockSerialNumber++;
2997 mNetTransitionWakeLock.acquire();
2998 mNetTransitionWakeLockCausedBy = forWhom;
2999 }
3000 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003001 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003002 mNetTransitionWakeLockSerialNumber, 0),
3003 mNetTransitionWakeLockTimeout);
3004 return;
3005 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003006
Robert Greenwalt986c7412010-09-08 15:24:47 -07003007 // 100 percent is full good, 0 is full bad.
3008 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003009 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003010 mContext.enforceCallingOrSelfPermission(
3011 android.Manifest.permission.STATUS_BAR,
3012 "ConnectivityService");
3013
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003014 if (DBG) {
3015 int pid = getCallingPid();
3016 int uid = getCallingUid();
3017 String s = pid + "(" + uid + ") reports inet is " +
3018 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3019 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3020 mInetLog.add(s);
3021 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3022 mInetLog.remove(0);
3023 }
3024 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003025 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003026 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3027 }
3028
3029 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003030 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003031 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003032 return;
3033 }
3034 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003035 if (DBG) log("handleInetConditionChange: net=" + netType +
3036 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003037 return;
3038 }
Wink Savillea7d56572011-09-21 11:05:43 -07003039 if (VDBG) {
3040 log("handleInetConditionChange: net=" +
3041 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003042 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003043 }
Wink Saville151eaa62013-01-31 00:30:13 +00003044 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003045 int delay;
3046 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003047 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003048 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003049 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003050 delay = Settings.Global.getInt(mContext.getContentResolver(),
3051 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003052 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003053 delay = Settings.Global.getInt(mContext.getContentResolver(),
3054 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003055 }
3056 mInetConditionChangeInFlight = true;
3057 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003058 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003059 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003060 // we've set the new condition, when this hold ends that will get picked up
3061 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003062 }
3063 }
3064
Wink Saville151eaa62013-01-31 00:30:13 +00003065 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003066 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003067 log("handleInetConditionHoldEnd: net=" + netType +
3068 ", condition=" + mDefaultInetCondition +
3069 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003070 }
3071 mInetConditionChangeInFlight = false;
3072
3073 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003074 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003075 return;
3076 }
3077 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003078 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003079 return;
3080 }
Wink Saville151eaa62013-01-31 00:30:13 +00003081 // TODO: Figure out why this optimization sometimes causes a
3082 // change in mDefaultInetCondition to be missed and the
3083 // UI to not be updated.
3084 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3085 // if (DBG) log("no change in condition - aborting");
3086 // return;
3087 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003088 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3089 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003090 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003091 return;
3092 }
Wink Saville151eaa62013-01-31 00:30:13 +00003093 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003094 sendInetConditionBroadcast(networkInfo);
3095 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003096 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003097
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003098 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003099 // this information is already available as a world read/writable jvm property
3100 // so this API change wouldn't have a benifit. It also breaks the passing
3101 // of proxy info to all the JVMs.
3102 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003103 synchronized (mProxyLock) {
3104 if (mGlobalProxy != null) return mGlobalProxy;
3105 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003106 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003107 }
3108
3109 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003110 enforceConnectivityInternalPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003111 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003112 if (proxyProperties == mGlobalProxy) return;
3113 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3114 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3115
3116 String host = "";
3117 int port = 0;
3118 String exclList = "";
3119 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3120 mGlobalProxy = new ProxyProperties(proxyProperties);
3121 host = mGlobalProxy.getHost();
3122 port = mGlobalProxy.getPort();
3123 exclList = mGlobalProxy.getExclusionList();
3124 } else {
3125 mGlobalProxy = null;
3126 }
3127 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003128 final long token = Binder.clearCallingIdentity();
3129 try {
3130 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3131 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3132 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3133 exclList);
3134 } finally {
3135 Binder.restoreCallingIdentity(token);
3136 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003137 }
3138
3139 if (mGlobalProxy == null) {
3140 proxyProperties = mDefaultProxy;
3141 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003142 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003143 }
3144
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003145 private void loadGlobalProxy() {
3146 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003147 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3148 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3149 String exclList = Settings.Global.getString(res,
3150 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003151 if (!TextUtils.isEmpty(host)) {
3152 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003153 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003154 mGlobalProxy = proxyProperties;
3155 }
3156 }
3157 }
3158
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003159 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003160 // this information is already available as a world read/writable jvm property
3161 // so this API change wouldn't have a benifit. It also breaks the passing
3162 // of proxy info to all the JVMs.
3163 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003164 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003165 return mGlobalProxy;
3166 }
3167 }
3168
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003169 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3170 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3171 proxy = null;
3172 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003173 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003174 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003175 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003176 mDefaultProxy = proxy;
3177
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003178 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003179 if (!mDefaultProxyDisabled) {
3180 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003181 }
3182 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003183 }
3184
3185 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003186 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3187 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003188 if (!TextUtils.isEmpty(proxy)) {
3189 String data[] = proxy.split(":");
3190 String proxyHost = data[0];
3191 int proxyPort = 8080;
3192 if (data.length > 1) {
3193 try {
3194 proxyPort = Integer.parseInt(data[1]);
3195 } catch (NumberFormatException e) {
3196 return;
3197 }
3198 }
3199 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3200 setGlobalProxy(p);
3201 }
3202 }
3203
3204 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003205 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003206 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003207 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003208 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3209 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003210 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003211 final long ident = Binder.clearCallingIdentity();
3212 try {
3213 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3214 } finally {
3215 Binder.restoreCallingIdentity(ident);
3216 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003217 }
3218
3219 private static class SettingsObserver extends ContentObserver {
3220 private int mWhat;
3221 private Handler mHandler;
3222 SettingsObserver(Handler handler, int what) {
3223 super(handler);
3224 mHandler = handler;
3225 mWhat = what;
3226 }
3227
3228 void observe(Context context) {
3229 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003230 resolver.registerContentObserver(Settings.Global.getUriFor(
3231 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003232 }
3233
3234 @Override
3235 public void onChange(boolean selfChange) {
3236 mHandler.obtainMessage(mWhat).sendToTarget();
3237 }
3238 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003239
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003240 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003241 Slog.d(TAG, s);
3242 }
3243
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003244 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003245 Slog.e(TAG, s);
3246 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003247
repo syncf5de5572011-07-29 23:55:49 -07003248 int convertFeatureToNetworkType(int networkType, String feature) {
3249 int usedNetworkType = networkType;
3250
3251 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3252 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3253 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3254 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3255 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3256 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3257 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3258 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3259 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3260 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3261 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3262 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3263 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3264 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3265 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3266 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3267 } else {
3268 Slog.e(TAG, "Can't match any mobile netTracker!");
3269 }
3270 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3271 if (TextUtils.equals(feature, "p2p")) {
3272 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3273 } else {
3274 Slog.e(TAG, "Can't match any wifi netTracker!");
3275 }
3276 } else {
3277 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003278 }
repo syncf5de5572011-07-29 23:55:49 -07003279 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003280 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003281
3282 private static <T> T checkNotNull(T value, String message) {
3283 if (value == null) {
3284 throw new NullPointerException(message);
3285 }
3286 return value;
3287 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003288
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003289 /**
3290 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003291 * VpnBuilder and not available in ConnectivityManager. Permissions
3292 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003293 * @hide
3294 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003295 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003296 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003297 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003298 try {
3299 int type = mActiveDefaultNetwork;
Robert Greenwalt15a41532012-08-21 19:27:00 -07003300 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003301 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3302 return true;
3303 }
3304 } catch (Exception e) {
3305 // ignore
3306 } finally {
3307 try {
3308 socket.close();
3309 } catch (Exception e) {
3310 // ignore
3311 }
3312 }
3313 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003314 }
3315
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003316 /**
3317 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003318 * and not available in ConnectivityManager. Permissions are checked
3319 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003320 * @hide
3321 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003322 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003323 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003324 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003325 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003326 }
3327
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003328 /**
3329 * Configure a TUN interface and return its file descriptor. Parameters
3330 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003331 * and not available in ConnectivityManager. Permissions are checked in
3332 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003333 * @hide
3334 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003335 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003336 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003337 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003338 return mVpn.establish(config);
3339 }
3340
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003341 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003342 * Start legacy VPN, controlling native daemons as needed. Creates a
3343 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003344 */
3345 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003346 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003347 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003348 final LinkProperties egress = getActiveLinkProperties();
3349 if (egress == null) {
3350 throw new IllegalStateException("Missing active network connection");
3351 }
3352 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003353 }
3354
3355 /**
3356 * Return the information of the ongoing legacy VPN. This method is used
3357 * by VpnSettings and not available in ConnectivityManager. Permissions
3358 * are checked in Vpn class.
3359 * @hide
3360 */
3361 @Override
3362 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003363 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003364 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003365 }
3366
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003367 /**
3368 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3369 * through NetworkStateTracker since it works differently. For example, it
3370 * needs to override DNS servers but never takes the default routes. It
3371 * relies on another data network, and it could keep existing connections
3372 * alive after reconnecting, switching between networks, or even resuming
3373 * from deep sleep. Calls from applications should be done synchronously
3374 * to avoid race conditions. As these are all hidden APIs, refactoring can
3375 * be done whenever a better abstraction is developed.
3376 */
3377 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003378 private VpnCallback() {
3379 }
3380
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003381 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003382 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003383 }
3384
Chia-chi Yehcc844502011-07-14 18:01:57 -07003385 public void override(List<String> dnsServers, List<String> searchDomains) {
3386 if (dnsServers == null) {
3387 restore();
3388 return;
3389 }
3390
3391 // Convert DNS servers into addresses.
3392 List<InetAddress> addresses = new ArrayList<InetAddress>();
3393 for (String address : dnsServers) {
3394 // Double check the addresses and remove invalid ones.
3395 try {
3396 addresses.add(InetAddress.parseNumericAddress(address));
3397 } catch (Exception e) {
3398 // ignore
3399 }
3400 }
3401 if (addresses.isEmpty()) {
3402 restore();
3403 return;
3404 }
3405
3406 // Concatenate search domains into a string.
3407 StringBuilder buffer = new StringBuilder();
3408 if (searchDomains != null) {
3409 for (String domain : searchDomains) {
3410 buffer.append(domain).append(' ');
3411 }
3412 }
3413 String domains = buffer.toString().trim();
3414
3415 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003416 synchronized (mDnsLock) {
Mattias Falkd697aa22011-08-23 14:15:13 +02003417 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003418 mDnsOverridden = true;
3419 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003420
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003421 // Temporarily disable the default proxy (not global).
3422 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003423 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003424 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003425 sendProxyBroadcast(null);
3426 }
3427 }
3428
3429 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003430 }
3431
Chia-chi Yehcc844502011-07-14 18:01:57 -07003432 public void restore() {
3433 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003434 if (mDnsOverridden) {
3435 mDnsOverridden = false;
3436 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003437 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003438 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003439 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003440 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003441 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003442 sendProxyBroadcast(mDefaultProxy);
3443 }
3444 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003445 }
3446 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003447
3448 @Override
3449 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003450 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3451 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3452 return false;
3453 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003454
3455 // Tear down existing lockdown if profile was removed
3456 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3457 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003458 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003459 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3460 return false;
3461 }
3462
3463 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3464 final VpnProfile profile = VpnProfile.decode(
3465 profileName, mKeyStore.get(Credentials.VPN + profileName));
3466 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3467 } else {
3468 setLockdownTracker(null);
3469 }
3470
3471 return true;
3472 }
3473
3474 /**
3475 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3476 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3477 */
3478 private void setLockdownTracker(LockdownVpnTracker tracker) {
3479 // Shutdown any existing tracker
3480 final LockdownVpnTracker existing = mLockdownTracker;
3481 mLockdownTracker = null;
3482 if (existing != null) {
3483 existing.shutdown();
3484 }
3485
3486 try {
3487 if (tracker != null) {
3488 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003489 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003490 mLockdownTracker = tracker;
3491 mLockdownTracker.init();
3492 } else {
3493 mNetd.setFirewallEnabled(false);
3494 }
3495 } catch (RemoteException e) {
3496 // ignored; NMS lives inside system_server
3497 }
3498 }
3499
3500 private void throwIfLockdownEnabled() {
3501 if (mLockdownEnabled) {
3502 throw new IllegalStateException("Unavailable in lockdown mode");
3503 }
3504 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003505
3506 public void supplyMessenger(int networkType, Messenger messenger) {
3507 enforceConnectivityInternalPermission();
3508
3509 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3510 mNetTrackers[networkType].supplyMessenger(messenger);
3511 }
3512 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003513
3514 public int findConnectionTypeForIface(String iface) {
3515 enforceConnectivityInternalPermission();
3516
3517 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3518 for (NetworkStateTracker tracker : mNetTrackers) {
3519 if (tracker != null) {
3520 LinkProperties lp = tracker.getLinkProperties();
3521 if (lp != null && iface.equals(lp.getInterfaceName())) {
3522 return tracker.getNetworkInfo().getType();
3523 }
3524 }
3525 }
3526 return ConnectivityManager.TYPE_NONE;
3527 }
Wink Saville32506bc2013-06-29 21:10:57 -07003528
3529 /**
3530 * Have mobile data fail fast if enabled.
3531 *
3532 * @param enabled DctConstants.ENABLED/DISABLED
3533 */
3534 private void setEnableFailFastMobileData(int enabled) {
3535 int tag;
3536
3537 if (enabled == DctConstants.ENABLED) {
3538 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3539 } else {
3540 tag = mEnableFailFastMobileDataTag.get();
3541 }
3542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3543 enabled));
3544 }
3545
3546 @Override
3547 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3548 final ResultReceiver resultReceiver) {
3549 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3550 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3551 + " resultReceiver=" + resultReceiver);
3552 enforceChangePermission();
3553
3554 int timeOutMs = suggestedTimeOutMs;
3555 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3556 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3557 }
3558
Wink Savilled469c472013-07-02 10:55:14 -07003559 // Check that mobile networks are supported
3560 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3561 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3562 log("checkMobileProvisioning: X no mobile network");
3563 if (resultReceiver != null) {
3564 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3565 }
3566 return timeOutMs;
3567 }
3568
Wink Saville32506bc2013-06-29 21:10:57 -07003569 final long token = Binder.clearCallingIdentity();
3570 try {
3571 CheckMp checkMp = new CheckMp(mContext, this);
3572 CheckMp.CallBack cb = new CheckMp.CallBack() {
3573 @Override
3574 void onComplete(Integer result) {
3575 log("CheckMp.onComplete: result=" + result);
3576 if (resultReceiver != null) {
3577 log("CheckMp.onComplete: send result");
3578 resultReceiver.send(result, null);
3579 }
3580 NetworkInfo ni =
3581 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3582 switch(result) {
3583 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3584 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3585 log("CheckMp.onComplete: ignore, connected or no connection");
3586 break;
3587 }
3588 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3589 log("CheckMp.onComplete: warm sim");
3590 String url = getProvisioningUrl();
3591 if (TextUtils.isEmpty(url)) {
3592 url = mContext.getResources()
3593 .getString(R.string.mobile_redirected_provisioning_url);
3594 }
3595 if (TextUtils.isEmpty(url) == false) {
3596 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3597 setNotificationVisible(true, ni, url);
3598 } else {
3599 log("CheckMp.onComplete: warm sim (redirected), no url");
3600 }
3601 break;
3602 }
3603 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3604 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3605 String url = getProvisioningUrl();
3606 if (TextUtils.isEmpty(url) == false) {
3607 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3608 setNotificationVisible(true, ni, url);
3609 } else {
3610 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3611 }
3612 break;
3613 }
3614 default: {
3615 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3616 break;
3617 }
3618 }
3619 }
3620 };
3621 CheckMp.Params params =
3622 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3623 log("checkMobileProvisioning: params=" + params);
3624 setNotificationVisible(false, null, null);
3625 checkMp.execute(params);
3626 } finally {
3627 Binder.restoreCallingIdentity(token);
3628 log("checkMobileProvisioning: X");
3629 }
3630 return timeOutMs;
3631 }
3632
3633 static class CheckMp extends
3634 AsyncTask<CheckMp.Params, Void, Integer> {
3635 private static final String CHECKMP_TAG = "CheckMp";
3636 public static final int MAX_TIMEOUT_MS = 60000;
3637 private static final int SOCKET_TIMEOUT_MS = 5000;
3638 private Context mContext;
3639 private ConnectivityService mCs;
3640 private TelephonyManager mTm;
3641 private Params mParams;
3642
3643 /**
3644 * Parameters for AsyncTask.execute
3645 */
3646 static class Params {
3647 private String mUrl;
3648 private long mTimeOutMs;
3649 private CallBack mCb;
3650
3651 Params(String url, long timeOutMs, CallBack cb) {
3652 mUrl = url;
3653 mTimeOutMs = timeOutMs;
3654 mCb = cb;
3655 }
3656
3657 @Override
3658 public String toString() {
3659 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3660 }
3661 }
3662
3663 /**
3664 * The call back object passed in Params. onComplete will be called
3665 * on the main thread.
3666 */
3667 abstract static class CallBack {
3668 // Called on the main thread.
3669 abstract void onComplete(Integer result);
3670 }
3671
3672 public CheckMp(Context context, ConnectivityService cs) {
3673 mContext = context;
3674 mCs = cs;
3675
3676 // Setup access to TelephonyService we'll be using.
3677 mTm = (TelephonyManager) mContext.getSystemService(
3678 Context.TELEPHONY_SERVICE);
3679 }
3680
3681 /**
3682 * Get the default url to use for the test.
3683 */
3684 public String getDefaultUrl() {
3685 // See http://go/clientsdns for usage approval
3686 String server = Settings.Global.getString(mContext.getContentResolver(),
3687 Settings.Global.CAPTIVE_PORTAL_SERVER);
3688 if (server == null) {
3689 server = "clients3.google.com";
3690 }
3691 return "http://" + server + "/generate_204";
3692 }
3693
3694 /**
3695 * Detect if its possible to connect to the http url. DNS based detection techniques
3696 * do not work at all hotspots. The best way to check is to perform a request to
3697 * a known address that fetches the data we expect.
3698 */
3699 private synchronized Integer isMobileOk(Params params) {
3700 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3701 Uri orgUri = Uri.parse(params.mUrl);
3702 Random rand = new Random();
3703 mParams = params;
3704
3705 try {
3706 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3707 log("isMobileOk: not mobile capable");
3708 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3709 return result;
3710 }
3711
3712 // Enable fail fast as we'll do retries here and use a
3713 // hipri connection so the default connection stays active.
3714 log("isMobileOk: start hipri url=" + params.mUrl);
3715 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3716 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3717 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3718
3719 // Continue trying to connect until time has run out
3720 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3721 while(SystemClock.elapsedRealtime() < endTime) {
3722 try {
3723 // Wait for hipri to connect.
3724 // TODO: Don't poll and handle situation where hipri fails
3725 // because default is retrying. See b/9569540
3726 NetworkInfo.State state = mCs
3727 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3728 if (state != NetworkInfo.State.CONNECTED) {
3729 log("isMobileOk: not connected ni=" +
3730 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3731 sleep(1);
3732 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3733 continue;
3734 }
3735
3736 // Get of the addresses associated with the url host. We need to use the
3737 // address otherwise HttpURLConnection object will use the name to get
3738 // the addresses and is will try every address but that will bypass the
3739 // route to host we setup and the connection could succeed as the default
3740 // interface might be connected to the internet via wifi or other interface.
3741 InetAddress[] addresses;
3742 try {
3743 addresses = InetAddress.getAllByName(orgUri.getHost());
3744 } catch (UnknownHostException e) {
3745 log("isMobileOk: UnknownHostException");
3746 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3747 return result;
3748 }
3749 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3750
3751 // Get the type of addresses supported by this link
3752 LinkProperties lp = mCs.getLinkProperties(
3753 ConnectivityManager.TYPE_MOBILE_HIPRI);
3754 boolean linkHasIpv4 = hasIPv4Address(lp);
3755 boolean linkHasIpv6 = hasIPv6Address(lp);
3756 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3757 + " linkHasIpv6=" + linkHasIpv6);
3758
3759 // Loop through at most 3 valid addresses or all of the address or until
3760 // we run out of time
3761 int loops = Math.min(3, addresses.length);
3762 for(int validAddr=0, addrTried=0;
3763 (validAddr < loops) && (addrTried < addresses.length)
3764 && (SystemClock.elapsedRealtime() < endTime);
3765 addrTried ++) {
3766
3767 // Choose the address at random but make sure its type is supported
3768 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3769 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3770 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3771 // Valid address, so use it
3772 validAddr += 1;
3773 } else {
3774 // Invalid address so try next address
3775 continue;
3776 }
3777
3778 // Make a route to host so we check the specific interface.
3779 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3780 hostAddr.getAddress())) {
3781 // Wait a short time to be sure the route is established ??
3782 log("isMobileOk:"
3783 + " wait to establish route to hostAddr=" + hostAddr);
3784 sleep(3);
3785 } else {
3786 log("isMobileOk:"
3787 + " could not establish route to hostAddr=" + hostAddr);
3788 continue;
3789 }
3790
3791 // Rewrite the url to have numeric address to use the specific route.
3792 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3793 // is used which is useless in this case.
3794 URL newUrl = new URL(orgUri.getScheme() + "://"
3795 + hostAddr.getHostAddress() + orgUri.getPath());
3796 log("isMobileOk: newUrl=" + newUrl);
3797
3798 HttpURLConnection urlConn = null;
3799 try {
3800 // Open the connection set the request header and get the response
3801 urlConn = (HttpURLConnection) newUrl.openConnection(
3802 java.net.Proxy.NO_PROXY);
3803 urlConn.setInstanceFollowRedirects(false);
3804 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3805 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3806 urlConn.setUseCaches(false);
3807 urlConn.setAllowUserInteraction(false);
3808 urlConn.setRequestProperty("Connection", "close");
3809 int responseCode = urlConn.getResponseCode();
3810 if (responseCode == 204) {
3811 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3812 } else {
3813 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3814 }
3815 log("isMobileOk: connected responseCode=" + responseCode);
3816 urlConn.disconnect();
3817 urlConn = null;
3818 return result;
3819 } catch (Exception e) {
3820 log("isMobileOk: HttpURLConnection Exception e=" + e);
3821 if (urlConn != null) {
3822 urlConn.disconnect();
3823 urlConn = null;
3824 }
3825 }
3826 }
3827 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3828 log("isMobileOk: loops|timed out");
3829 return result;
3830 } catch (Exception e) {
3831 log("isMobileOk: Exception e=" + e);
3832 continue;
3833 }
3834 }
3835 log("isMobileOk: timed out");
3836 } finally {
3837 log("isMobileOk: F stop hipri");
3838 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3839 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3840 Phone.FEATURE_ENABLE_HIPRI);
3841 log("isMobileOk: X result=" + result);
3842 }
3843 return result;
3844 }
3845
3846 @Override
3847 protected Integer doInBackground(Params... params) {
3848 return isMobileOk(params[0]);
3849 }
3850
3851 @Override
3852 protected void onPostExecute(Integer result) {
3853 log("onPostExecute: result=" + result);
3854 if ((mParams != null) && (mParams.mCb != null)) {
3855 mParams.mCb.onComplete(result);
3856 }
3857 }
3858
3859 private String inetAddressesToString(InetAddress[] addresses) {
3860 StringBuffer sb = new StringBuffer();
3861 boolean firstTime = true;
3862 for(InetAddress addr : addresses) {
3863 if (firstTime) {
3864 firstTime = false;
3865 } else {
3866 sb.append(",");
3867 }
3868 sb.append(addr);
3869 }
3870 return sb.toString();
3871 }
3872
3873 private void printNetworkInfo() {
3874 boolean hasIccCard = mTm.hasIccCard();
3875 int simState = mTm.getSimState();
3876 log("hasIccCard=" + hasIccCard
3877 + " simState=" + simState);
3878 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3879 if (ni != null) {
3880 log("ni.length=" + ni.length);
3881 for (NetworkInfo netInfo: ni) {
3882 log("netInfo=" + netInfo.toString());
3883 }
3884 } else {
3885 log("no network info ni=null");
3886 }
3887 }
3888
3889 /**
3890 * Sleep for a few seconds then return.
3891 * @param seconds
3892 */
3893 private static void sleep(int seconds) {
3894 try {
3895 Thread.sleep(seconds * 1000);
3896 } catch (InterruptedException e) {
3897 e.printStackTrace();
3898 }
3899 }
3900
3901 public boolean hasIPv4Address(LinkProperties lp) {
3902 return lp.hasIPv4Address();
3903 }
3904
3905 // Not implemented in LinkProperties, do it here.
3906 public boolean hasIPv6Address(LinkProperties lp) {
3907 for (LinkAddress address : lp.getLinkAddresses()) {
3908 if (address.getAddress() instanceof Inet6Address) {
3909 return true;
3910 }
3911 }
3912 return false;
3913 }
3914
3915 private void log(String s) {
3916 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3917 }
3918 }
3919
3920 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3921
3922 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3923 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3924
3925 Resources r = Resources.getSystem();
3926 NotificationManager notificationManager = (NotificationManager) mContext
3927 .getSystemService(Context.NOTIFICATION_SERVICE);
3928
3929 if (visible) {
3930 CharSequence title;
3931 CharSequence details;
3932 int icon;
3933 switch (networkInfo.getType()) {
3934 case ConnectivityManager.TYPE_WIFI:
3935 log("setNotificationVisible: TYPE_WIFI");
3936 title = r.getString(R.string.wifi_available_sign_in, 0);
3937 details = r.getString(R.string.network_available_sign_in_detailed,
3938 networkInfo.getExtraInfo());
3939 icon = R.drawable.stat_notify_wifi_in_range;
3940 break;
3941 case ConnectivityManager.TYPE_MOBILE:
3942 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3943 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
3944 title = r.getString(R.string.network_available_sign_in, 0);
3945 // TODO: Change this to pull from NetworkInfo once a printable
3946 // name has been added to it
3947 details = mTelephonyManager.getNetworkOperatorName();
3948 icon = R.drawable.stat_notify_rssi_in_range;
3949 break;
3950 default:
3951 log("setNotificationVisible: other type=" + networkInfo.getType());
3952 title = r.getString(R.string.network_available_sign_in, 0);
3953 details = r.getString(R.string.network_available_sign_in_detailed,
3954 networkInfo.getExtraInfo());
3955 icon = R.drawable.stat_notify_rssi_in_range;
3956 break;
3957 }
3958
3959 Notification notification = new Notification();
3960 notification.when = 0;
3961 notification.icon = icon;
3962 notification.flags = Notification.FLAG_AUTO_CANCEL;
3963 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3964 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3965 Intent.FLAG_ACTIVITY_NEW_TASK);
3966 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3967 notification.tickerText = title;
3968 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3969
3970 log("setNotificaitionVisible: notify notificaiton=" + notification);
3971 notificationManager.notify(NOTIFICATION_ID, 1, notification);
3972 } else {
3973 log("setNotificaitionVisible: cancel");
3974 notificationManager.cancel(NOTIFICATION_ID, 1);
3975 }
3976 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
3977 }
3978
3979 private String getProvisioningUrl() {
3980 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillec118d7e2013-07-10 23:00:07 -07003981 log("getProvisioningUrl: mobile_provisioning_url=" + url);
Wink Saville32506bc2013-06-29 21:10:57 -07003982
Wink Savillec118d7e2013-07-10 23:00:07 -07003983 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07003984 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07003985 String phoneNumber = mTelephonyManager.getLine1Number();
3986 if (TextUtils.isEmpty(phoneNumber)) {
3987 phoneNumber = "0000000000";
3988 }
Wink Saville32506bc2013-06-29 21:10:57 -07003989 url = String.format(url,
3990 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3991 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07003992 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07003993 }
3994
Wink Saville32506bc2013-06-29 21:10:57 -07003995 return url;
3996 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003997}