blob: a6344cafabf0e4897fa0cd48eb3ec2f783120124 [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;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700100import android.util.SparseArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101
Wink Saville32506bc2013-06-29 21:10:57 -0700102import com.android.internal.R;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700103import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700104import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700105import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700106import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700107import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700108import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700109import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700110import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400111import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900112import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800113import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700114import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700115import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700116import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700117import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700118import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700119
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700120import com.android.internal.annotations.GuardedBy;
121
tk.mun093f55c2011-10-13 22:51:57 +0900122import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700123
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700125import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900127import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700128import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700129import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700130import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700131import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700132import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700133import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700134import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700135import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700136import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700137import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700138import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700139import java.util.List;
Wink Saville32506bc2013-06-29 21:10:57 -0700140import java.util.Random;
141import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800142
143/**
144 * @hide
145 */
146public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700147 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800148
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700149 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700150 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800151
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700152 private static final boolean LOGD_RULES = false;
153
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700154 // TODO: create better separation between radio types and network types
155
Robert Greenwalt2034b912009-08-12 16:08:25 -0700156 // how long to wait before switching back to a radio's default network
157 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
158 // system property that can override the above value
159 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
160 "android.telephony.apn-restore";
161
Wink Saville32506bc2013-06-29 21:10:57 -0700162 // Default value if FAIL_FAST_TIME_MS is not set
163 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
164 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
165 private static final String FAIL_FAST_TIME_MS =
166 "persist.radio.fail_fast_time_ms";
167
Robert Greenwaltbd492212011-05-06 17:10:53 -0700168 // used in recursive route setting to add gateways for the host for which
169 // a host route was requested.
170 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
171
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800172 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800173 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800174
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700175 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700176
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700177 @GuardedBy("mVpns")
178 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700179 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700180
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700181 private boolean mLockdownEnabled;
182 private LockdownVpnTracker mLockdownTracker;
183
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900184 private Nat464Xlat mClat;
185
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700186 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
187 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700188 /** Currently active network rules by UID. */
189 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700190 /** Set of ifaces that are costly. */
191 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700192
The Android Open Source Project28527d22009-03-03 19:31:44 -0800193 /**
194 * Sometimes we want to refer to the individual network state
195 * trackers separately, and sometimes we just want to treat them
196 * abstractly.
197 */
198 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700199
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700200 /* Handles captive portal check on a network */
201 private CaptivePortalTracker mCaptivePortalTracker;
202
Robert Greenwalt2034b912009-08-12 16:08:25 -0700203 /**
Wink Saville051a6642011-07-13 13:44:13 -0700204 * The link properties that define the current links
205 */
206 private LinkProperties mCurrentLinkProperties[];
207
208 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700209 * A per Net list of the PID's that requested access to the net
210 * used both as a refcount and for per-PID DNS selection
211 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200212 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700213
Robert Greenwalt2034b912009-08-12 16:08:25 -0700214 // priority order of the nettrackers
215 // (excluding dynamically set mNetworkPreference)
216 // TODO - move mNetworkTypePreference into this
217 private int[] mPriorityList;
218
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219 private Context mContext;
220 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700221 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700222 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000223 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700224 private int mDefaultInetConditionPublished = 0;
225 private boolean mInetConditionChangeInFlight = false;
226 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227
Chia-chi Yehcc844502011-07-14 18:01:57 -0700228 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800229 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700230 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231
232 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700233 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234
Robert Greenwalt355205c2011-05-10 15:05:02 -0700235 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700236 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700237
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700238 private static final int ENABLED = 1;
239 private static final int DISABLED = 0;
240
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700241 private static final boolean ADD = true;
242 private static final boolean REMOVE = false;
243
244 private static final boolean TO_DEFAULT_TABLE = true;
245 private static final boolean TO_SECONDARY_TABLE = false;
246
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700247 /**
248 * used internally as a delayed event to make us switch back to the
249 * default network
250 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700251 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700252
253 /**
254 * used internally to change our mobile data enabled flag
255 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700256 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700257
258 /**
259 * used internally to change our network preference setting
260 * arg1 = networkType to prefer
261 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700262 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700263
264 /**
265 * used internally to synchronize inet condition reports
266 * arg1 = networkType
267 * arg2 = condition (0 bad, 100 good)
268 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700269 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700270
271 /**
272 * used internally to mark the end of inet condition hold periods
273 * arg1 = networkType
274 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700275 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700276
277 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700278 * used internally to set enable/disable cellular data
279 * arg1 = ENBALED or DISABLED
280 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700281 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700282
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700283 /**
284 * used internally to clear a wakelock when transitioning
285 * from one net to another
286 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700287 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700288
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700289 /**
290 * used internally to reload global proxy settings
291 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700292 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700293
Robert Greenwalt34848c02011-03-25 13:09:25 -0700294 /**
295 * used internally to set external dependency met/unmet
296 * arg1 = ENABLED (met) or DISABLED (unmet)
297 * arg2 = NetworkType
298 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700299 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700300
Chia-chi Yehcc844502011-07-14 18:01:57 -0700301 /**
302 * used internally to restore DNS properties back to the
303 * default network
304 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700305 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700306
Wink Saville7e4333c2011-08-05 11:40:22 -0700307 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700308 * used internally to send a sticky broadcast delayed.
309 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700310 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700311
Jeff Sharkey805662d2011-08-19 02:24:24 -0700312 /**
313 * Used internally to
314 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
315 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700316 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700317
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700318 private static final int EVENT_VPN_STATE_CHANGED = 14;
319
Wink Saville32506bc2013-06-29 21:10:57 -0700320 /**
321 * Used internally to disable fail fast of mobile data
322 */
323 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
324
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700325 /** Handler used for internal events. */
326 private InternalHandler mHandler;
327 /** Handler used for incoming {@link NetworkStateTracker} events. */
328 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700329
330 // list of DeathRecipients used to make sure features are turned off when
331 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500332 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700333
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400334 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800335 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400336
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700337 private PowerManager.WakeLock mNetTransitionWakeLock;
338 private String mNetTransitionWakeLockCausedBy = "";
339 private int mNetTransitionWakeLockSerialNumber;
340 private int mNetTransitionWakeLockTimeout;
341
Robert Greenwalt94daa182010-09-01 11:34:05 -0700342 private InetAddress mDefaultDns;
343
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700344 // this collection is used to refcount the added routes - if there are none left
345 // it's time to remove the route from the route table
346 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
347
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700348 // used in DBG mode to track inet condition reports
349 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
350 private ArrayList mInetLog;
351
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700352 // track the current default http proxy - tell the world if we get a new one (real change)
353 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700354 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700355 private boolean mDefaultProxyDisabled = false;
356
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700357 // track the global proxy.
358 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700359
360 private SettingsObserver mSettingsObserver;
361
Robert Greenwalt34848c02011-03-25 13:09:25 -0700362 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700364
Robert Greenwalt12c44552009-12-07 11:33:18 -0800365 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366 public int mSimultaneity;
367 public int mType;
368 public RadioAttributes(String init) {
369 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700370 mType = Integer.parseInt(fragments[0]);
371 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700372 }
373 }
374 RadioAttributes[] mRadioAttributes;
375
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700376 // the set of network types that can only be enabled by system/sig apps
377 List mProtectedNetworks;
378
John Spurlock1f5cec72013-06-24 14:20:23 -0400379 private DataConnectionStats mDataConnectionStats;
Wink Saville32506bc2013-06-29 21:10:57 -0700380 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
381
382 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400383
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700384 public ConnectivityService(Context context, INetworkManagementService netd,
385 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700386 // Currently, omitting a NetworkFactory will create one internally
387 // TODO: create here when we have cleaner WiMAX support
388 this(context, netd, statsService, policyManager, null);
389 }
390
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700391 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700392 INetworkStatsService statsService, INetworkPolicyManager policyManager,
393 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800394 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800395
Wink Saville775aad62010-09-02 19:23:52 -0700396 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
397 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700398 mHandler = new InternalHandler(handlerThread.getLooper());
399 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700400
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700401 if (netFactory == null) {
402 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
403 }
404
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800405 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800406 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
407 String id = Settings.Secure.getString(context.getContentResolver(),
408 Settings.Secure.ANDROID_ID);
409 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700410 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800411 SystemProperties.set("net.hostname", name);
412 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800413 }
414
Robert Greenwalt94daa182010-09-01 11:34:05 -0700415 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700416 String dns = Settings.Global.getString(context.getContentResolver(),
417 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700418 if (dns == null || dns.length() == 0) {
419 dns = context.getResources().getString(
420 com.android.internal.R.string.config_default_dns_server);
421 }
422 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800423 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
424 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800425 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700426 }
427
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700428 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700429 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700430 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700431 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700432 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700433
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700434 try {
435 mPolicyManager.registerListener(mPolicyListener);
436 } catch (RemoteException e) {
437 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700438 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700439 }
440
441 final PowerManager powerManager = (PowerManager) context.getSystemService(
442 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700443 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
444 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
445 com.android.internal.R.integer.config_networkTransitionTimeout);
446
Robert Greenwalt2034b912009-08-12 16:08:25 -0700447 mNetTrackers = new NetworkStateTracker[
448 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700449 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700450
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700451 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700452 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700453
Robert Greenwalt2034b912009-08-12 16:08:25 -0700454 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700455 String[] raStrings = context.getResources().getStringArray(
456 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700457 for (String raString : raStrings) {
458 RadioAttributes r = new RadioAttributes(raString);
459 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800460 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700461 continue;
462 }
463 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800464 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700465 r.mType);
466 continue;
467 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700468 mRadioAttributes[r.mType] = r;
469 }
470
Wink Saville00fe5092013-04-23 14:26:51 -0700471 // TODO: What is the "correct" way to do determine if this is a wifi only device?
472 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
473 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700474 String[] naStrings = context.getResources().getStringArray(
475 com.android.internal.R.array.networkAttributes);
476 for (String naString : naStrings) {
477 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700478 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700479 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800480 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700481 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700482 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700483 }
Wink Saville00fe5092013-04-23 14:26:51 -0700484 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
485 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
486 n.type);
487 continue;
488 }
Wink Savillef2a62832011-04-07 14:23:45 -0700489 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800490 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700491 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700492 continue;
493 }
Wink Savillef2a62832011-04-07 14:23:45 -0700494 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800495 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700496 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700497 continue;
498 }
Wink Savillef2a62832011-04-07 14:23:45 -0700499 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700500 mNetworksDefined++;
501 } catch(Exception e) {
502 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700503 }
504 }
505
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700506 mProtectedNetworks = new ArrayList<Integer>();
507 int[] protectedNetworks = context.getResources().getIntArray(
508 com.android.internal.R.array.config_protectedNetworks);
509 for (int p : protectedNetworks) {
510 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
511 mProtectedNetworks.add(p);
512 } else {
513 if (DBG) loge("Ignoring protectedNetwork " + p);
514 }
515 }
516
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700517 // high priority first
518 mPriorityList = new int[mNetworksDefined];
519 {
520 int insertionPoint = mNetworksDefined-1;
521 int currentLowest = 0;
522 int nextLowest = 0;
523 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700524 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700525 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700526 if (na.priority < currentLowest) continue;
527 if (na.priority > currentLowest) {
528 if (na.priority < nextLowest || nextLowest == 0) {
529 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700530 }
531 continue;
532 }
Wink Savillef2a62832011-04-07 14:23:45 -0700533 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700534 }
535 currentLowest = nextLowest;
536 nextLowest = 0;
537 }
538 }
539
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800540 // Update mNetworkPreference according to user mannually first then overlay config.xml
541 mNetworkPreference = getPersistedNetworkPreference();
542 if (mNetworkPreference == -1) {
543 for (int n : mPriorityList) {
544 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
545 mNetworkPreference = n;
546 break;
547 }
548 }
549 if (mNetworkPreference == -1) {
550 throw new IllegalStateException(
551 "You should set at least one default Network in config.xml!");
552 }
553 }
554
Mattias Falkd697aa22011-08-23 14:15:13 +0200555 mNetRequestersPids =
556 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700557 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200558 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 }
560
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500561 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700563 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
564 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700565
566 // Create and start trackers for hard-coded networks
567 for (int targetNetworkType : mPriorityList) {
568 final NetworkConfig config = mNetConfigs[targetNetworkType];
569 final NetworkStateTracker tracker;
570 try {
571 tracker = netFactory.createTracker(targetNetworkType, config);
572 mNetTrackers[targetNetworkType] = tracker;
573 } catch (IllegalArgumentException e) {
574 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
575 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700576 continue;
577 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700578
579 tracker.startMonitoring(context, mTrackerHandler);
580 if (config.isDefault()) {
581 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800582 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700583 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800584
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700585 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700586 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700587 mTethering.getTetherableWifiRegexs().length != 0 ||
588 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700589 mTethering.getUpstreamIfaceTypes().length != 0);
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700590 //set up the listener for user state for creating user VPNs
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800591
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700592 IntentFilter intentFilter = new IntentFilter();
593 intentFilter.addAction(Intent.ACTION_USER_STARTING);
594 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
595 mContext.registerReceiverAsUser(
596 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900597 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
598
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700599 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700600 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700601 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900602 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700603 } catch (RemoteException e) {
604 loge("Error registering observer :" + e);
605 }
606
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700607 if (DBG) {
608 mInetLog = new ArrayList();
609 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700610
611 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
612 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800613
Irfan Sheriff32bed2c2012-09-20 09:32:41 -0700614 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800615 loadGlobalProxy();
John Spurlock1f5cec72013-06-24 14:20:23 -0400616
617 mDataConnectionStats = new DataConnectionStats(mContext);
618 mDataConnectionStats.startMonitoring();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800619 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700620
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700621 /**
622 * Factory that creates {@link NetworkStateTracker} instances using given
623 * {@link NetworkConfig}.
624 */
625 public interface NetworkFactory {
626 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
627 }
628
629 private static class DefaultNetworkFactory implements NetworkFactory {
630 private final Context mContext;
631 private final Handler mTrackerHandler;
632
633 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
634 mContext = context;
635 mTrackerHandler = trackerHandler;
636 }
637
638 @Override
639 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
640 switch (config.radio) {
641 case TYPE_WIFI:
642 return new WifiStateTracker(targetNetworkType, config.name);
643 case TYPE_MOBILE:
644 return new MobileDataStateTracker(targetNetworkType, config.name);
645 case TYPE_DUMMY:
646 return new DummyDataStateTracker(targetNetworkType, config.name);
647 case TYPE_BLUETOOTH:
648 return BluetoothTetheringDataTracker.getInstance();
649 case TYPE_WIMAX:
650 return makeWimaxStateTracker(mContext, mTrackerHandler);
651 case TYPE_ETHERNET:
652 return EthernetDataTracker.getInstance();
653 default:
654 throw new IllegalArgumentException(
655 "Trying to create a NetworkStateTracker for an unknown radio type: "
656 + config.radio);
657 }
658 }
659 }
660
661 /**
662 * Loads external WiMAX library and registers as system service, returning a
663 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
664 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
665 */
666 private static NetworkStateTracker makeWimaxStateTracker(
667 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700668 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900669 DexClassLoader wimaxClassLoader;
670 Class wimaxStateTrackerClass = null;
671 Class wimaxServiceClass = null;
672 Class wimaxManagerClass;
673 String wimaxJarLocation;
674 String wimaxLibLocation;
675 String wimaxManagerClassName;
676 String wimaxServiceClassName;
677 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800678
tk.mun093f55c2011-10-13 22:51:57 +0900679 NetworkStateTracker wimaxStateTracker = null;
680
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700681 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900682 com.android.internal.R.bool.config_wimaxEnabled);
683
684 if (isWimaxEnabled) {
685 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700686 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900687 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700688 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900689 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700690 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900691 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700692 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900693 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700694 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900695 com.android.internal.R.string.config_wimaxStateTrackerClassname);
696
Dianne Hackborndc456a62012-11-08 11:12:09 -0800697 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900698 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700699 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900700 wimaxLibLocation, ClassLoader.getSystemClassLoader());
701
702 try {
703 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
704 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
705 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
706 } catch (ClassNotFoundException ex) {
707 loge("Exception finding Wimax classes: " + ex.toString());
708 return null;
709 }
710 } catch(Resources.NotFoundException ex) {
711 loge("Wimax Resources does not exist!!! ");
712 return null;
713 }
714
715 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800716 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900717
718 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
719 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700720 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
721 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900722
723 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
724 (new Class[] {Context.class, wimaxStateTrackerClass});
725 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700726 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900727 wmxSrvConst.setAccessible(false);
728
729 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
730
731 } catch(Exception ex) {
732 loge("Exception creating Wimax classes: " + ex.toString());
733 return null;
734 }
735 } else {
736 loge("Wimax is not enabled or not added to the network attributes!!! ");
737 return null;
738 }
739
740 return wimaxStateTracker;
741 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700742
The Android Open Source Project28527d22009-03-03 19:31:44 -0800743 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700744 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800745 * @param preference the new preference
746 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700747 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800748 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700749
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700750 mHandler.sendMessage(
751 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800752 }
753
754 public int getNetworkPreference() {
755 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700756 int preference;
757 synchronized(this) {
758 preference = mNetworkPreference;
759 }
760 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800761 }
762
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700763 private void handleSetNetworkPreference(int preference) {
764 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700765 mNetConfigs[preference] != null &&
766 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700767 if (mNetworkPreference != preference) {
768 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700769 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700770 synchronized(this) {
771 mNetworkPreference = preference;
772 }
773 enforcePreference();
774 }
775 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700777
Wink Saville4f0de1e2011-08-04 15:01:58 -0700778 private int getConnectivityChangeDelay() {
779 final ContentResolver cr = mContext.getContentResolver();
780
781 /** Check system properties for the default value then use secure settings value, if any. */
782 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700783 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
784 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
785 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700786 defaultDelay);
787 }
788
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789 private int getPersistedNetworkPreference() {
790 final ContentResolver cr = mContext.getContentResolver();
791
Jeff Brownc67cf562012-09-25 15:03:20 -0700792 final int networkPrefSetting = Settings.Global
793 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800794
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800795 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800796 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700797
The Android Open Source Project28527d22009-03-03 19:31:44 -0800798 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700799 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 * In this method, we only tear down a non-preferred network. Establishing
801 * a connection to the preferred network is taken care of when we handle
802 * the disconnect event from the non-preferred network
803 * (see {@link #handleDisconnect(NetworkInfo)}).
804 */
805 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700806 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800807 return;
808
Robert Greenwalt2034b912009-08-12 16:08:25 -0700809 if (!mNetTrackers[mNetworkPreference].isAvailable())
810 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800811
Robert Greenwalt2034b912009-08-12 16:08:25 -0700812 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700813 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700815 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800816 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700817 " in enforcePreference");
818 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700819 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800820 }
821 }
822 }
823
824 private boolean teardown(NetworkStateTracker netTracker) {
825 if (netTracker.teardown()) {
826 netTracker.setTeardownRequested(true);
827 return true;
828 } else {
829 return false;
830 }
831 }
832
833 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700834 * Check if UID should be blocked from using the network represented by the
835 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700836 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700837 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
838 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700839
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700840 final boolean networkCostly;
841 final int uidRules;
842 synchronized (mRulesLock) {
843 networkCostly = mMeteredIfaces.contains(iface);
844 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700845 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700846
847 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
848 return true;
849 }
850
851 // no restrictive rules; network is visible
852 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700853 }
854
855 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700856 * Return a filtered {@link NetworkInfo}, potentially marked
857 * {@link DetailedState#BLOCKED} based on
858 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700859 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700860 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
861 NetworkInfo info = tracker.getNetworkInfo();
862 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700863 // network is blocked; clone and override state
864 info = new NetworkInfo(info);
865 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700866 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700867 if (mLockdownTracker != null) {
868 info = mLockdownTracker.augmentNetworkInfo(info);
869 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700870 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700871 }
872
873 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800874 * Return NetworkInfo for the active (i.e., connected) network interface.
875 * It is assumed that at most one network is active at a time. If more
876 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700877 * @return the info for the active network, or {@code null} if none is
878 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800879 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700880 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700882 enforceAccessPermission();
883 final int uid = Binder.getCallingUid();
884 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800885 }
886
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700887 public NetworkInfo getActiveNetworkInfoUnfiltered() {
888 enforceAccessPermission();
889 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
890 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
891 if (tracker != null) {
892 return tracker.getNetworkInfo();
893 }
894 }
895 return null;
896 }
897
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700898 @Override
899 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
900 enforceConnectivityInternalPermission();
901 return getNetworkInfo(mActiveDefaultNetwork, uid);
902 }
903
904 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800905 public NetworkInfo getNetworkInfo(int networkType) {
906 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700907 final int uid = Binder.getCallingUid();
908 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800909 }
910
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700911 private NetworkInfo getNetworkInfo(int networkType, int uid) {
912 NetworkInfo info = null;
913 if (isNetworkTypeValid(networkType)) {
914 final NetworkStateTracker tracker = mNetTrackers[networkType];
915 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700916 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700917 }
918 }
919 return info;
920 }
921
922 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 public NetworkInfo[] getAllNetworkInfo() {
924 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700925 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700926 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700927 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700928 for (NetworkStateTracker tracker : mNetTrackers) {
929 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700930 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700931 }
932 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800933 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700934 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800935 }
936
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700937 @Override
938 public boolean isNetworkSupported(int networkType) {
939 enforceAccessPermission();
940 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
941 }
942
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700943 /**
944 * Return LinkProperties for the active (i.e., connected) default
945 * network interface. It is assumed that at most one default network
946 * is active at a time. If more than one is active, it is indeterminate
947 * which will be returned.
948 * @return the ip properties for the active network, or {@code null} if
949 * none is active
950 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700951 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700952 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700953 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700954 }
955
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700956 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700957 public LinkProperties getLinkProperties(int networkType) {
958 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700959 if (isNetworkTypeValid(networkType)) {
960 final NetworkStateTracker tracker = mNetTrackers[networkType];
961 if (tracker != null) {
962 return tracker.getLinkProperties();
963 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700964 }
965 return null;
966 }
967
Jeff Sharkey21062e72011-05-28 20:56:34 -0700968 @Override
969 public NetworkState[] getAllNetworkState() {
970 enforceAccessPermission();
971 final int uid = Binder.getCallingUid();
972 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700973 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700974 for (NetworkStateTracker tracker : mNetTrackers) {
975 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700976 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700977 result.add(new NetworkState(
978 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
979 }
980 }
981 }
982 return result.toArray(new NetworkState[result.size()]);
983 }
984
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700985 private NetworkState getNetworkStateUnchecked(int networkType) {
986 if (isNetworkTypeValid(networkType)) {
987 final NetworkStateTracker tracker = mNetTrackers[networkType];
988 if (tracker != null) {
989 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
990 tracker.getLinkCapabilities());
991 }
992 }
993 return null;
994 }
995
996 @Override
997 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
998 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700999
1000 final long token = Binder.clearCallingIdentity();
1001 try {
1002 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1003 if (state != null) {
1004 try {
1005 return mPolicyManager.getNetworkQuotaInfo(state);
1006 } catch (RemoteException e) {
1007 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001008 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001009 return null;
1010 } finally {
1011 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001012 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001013 }
1014
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001015 @Override
1016 public boolean isActiveNetworkMetered() {
1017 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001018 final long token = Binder.clearCallingIdentity();
1019 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001020 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001021 } finally {
1022 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001023 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001024 }
1025
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001026 private boolean isNetworkMeteredUnchecked(int networkType) {
1027 final NetworkState state = getNetworkStateUnchecked(networkType);
1028 if (state != null) {
1029 try {
1030 return mPolicyManager.isNetworkMetered(state);
1031 } catch (RemoteException e) {
1032 }
1033 }
1034 return false;
1035 }
1036
The Android Open Source Project28527d22009-03-03 19:31:44 -08001037 public boolean setRadios(boolean turnOn) {
1038 boolean result = true;
1039 enforceChangePermission();
1040 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001041 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001042 }
1043 return result;
1044 }
1045
1046 public boolean setRadio(int netType, boolean turnOn) {
1047 enforceChangePermission();
1048 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1049 return false;
1050 }
1051 NetworkStateTracker tracker = mNetTrackers[netType];
1052 return tracker != null && tracker.setRadio(turnOn);
1053 }
1054
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001055 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1056 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001057 public void interfaceClassDataActivityChanged(String label, boolean active) {
1058 int deviceType = Integer.parseInt(label);
1059 sendDataActivityBroadcast(deviceType, active);
1060 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001061 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001062
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001063 /**
1064 * Used to notice when the calling process dies so we can self-expire
1065 *
1066 * Also used to know if the process has cleaned up after itself when
1067 * our auto-expire timer goes off. The timer has a link to an object.
1068 *
1069 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001070 private class FeatureUser implements IBinder.DeathRecipient {
1071 int mNetworkType;
1072 String mFeature;
1073 IBinder mBinder;
1074 int mPid;
1075 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001076 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001077
1078 FeatureUser(int type, String feature, IBinder binder) {
1079 super();
1080 mNetworkType = type;
1081 mFeature = feature;
1082 mBinder = binder;
1083 mPid = getCallingPid();
1084 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001085 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001086
Robert Greenwalt2034b912009-08-12 16:08:25 -07001087 try {
1088 mBinder.linkToDeath(this, 0);
1089 } catch (RemoteException e) {
1090 binderDied();
1091 }
1092 }
1093
1094 void unlinkDeathRecipient() {
1095 mBinder.unlinkToDeath(this, 0);
1096 }
1097
1098 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001099 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001100 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1101 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001102 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001103 }
1104
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001105 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001106 if (VDBG) {
1107 log("ConnectivityService FeatureUser expire(" +
1108 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1109 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1110 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001111 stopUsingNetworkFeature(this, false);
1112 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001113
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001114 public boolean isSameUser(FeatureUser u) {
1115 if (u == null) return false;
1116
1117 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1118 }
1119
1120 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1121 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1122 TextUtils.equals(mFeature, feature)) {
1123 return true;
1124 }
1125 return false;
1126 }
1127
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001128 public String toString() {
1129 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1130 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1131 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001132 }
1133
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001134 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001135 public int startUsingNetworkFeature(int networkType, String feature,
1136 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001137 long startTime = 0;
1138 if (DBG) {
1139 startTime = SystemClock.elapsedRealtime();
1140 }
Wink Savillea7d56572011-09-21 11:05:43 -07001141 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001142 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1143 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001144 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001145 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001146 try {
1147 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1148 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001149 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001150 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001151
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001152 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001153
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001154 // TODO - move this into individual networktrackers
1155 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001156
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001157 if (mLockdownEnabled) {
1158 // Since carrier APNs usually aren't available from VPN
1159 // endpoint, mark them as unavailable.
1160 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1161 }
1162
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001163 if (mProtectedNetworks.contains(usedNetworkType)) {
1164 enforceConnectivityInternalPermission();
1165 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001166
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001167 // if UID is restricted, don't allow them to bring up metered APNs
1168 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1169 final int uidRules;
1170 synchronized (mRulesLock) {
1171 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1172 }
1173 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001174 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001175 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001176
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001177 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1178 if (network != null) {
1179 Integer currentPid = new Integer(getCallingPid());
1180 if (usedNetworkType != networkType) {
1181 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001182
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001183 if (ni.isAvailable() == false) {
1184 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1185 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001186 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001187 } else {
1188 // else make the attempt anyway - probably giving REQUEST_STARTED below
1189 if (DBG) {
1190 log("special network not available, but try anyway ni=" +
1191 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001192 }
1193 }
1194 }
1195
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001196 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001197
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001198 synchronized(this) {
1199 boolean addToList = true;
1200 if (restoreTimer < 0) {
1201 // In case there is no timer is specified for the feature,
1202 // make sure we don't add duplicate entry with the same request.
1203 for (FeatureUser u : mFeatureUsers) {
1204 if (u.isSameUser(f)) {
1205 // Duplicate user is found. Do not add.
1206 addToList = false;
1207 break;
1208 }
1209 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001210 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001211
1212 if (addToList) mFeatureUsers.add(f);
1213 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1214 // this gets used for per-pid dns when connected
1215 mNetRequestersPids[usedNetworkType].add(currentPid);
1216 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001217 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001218
1219 if (restoreTimer >= 0) {
1220 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1221 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1222 }
1223
1224 if ((ni.isConnectedOrConnecting() == true) &&
1225 !network.isTeardownRequested()) {
1226 if (ni.isConnected() == true) {
1227 final long token = Binder.clearCallingIdentity();
1228 try {
1229 // add the pid-specific dns
1230 handleDnsConfigurationChange(usedNetworkType);
1231 if (VDBG) log("special network already active");
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
1234 }
Wink Saville64e3f782012-07-10 12:37:54 -07001235 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001236 }
1237 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001238 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001239 }
1240
1241 // check if the radio in play can make another contact
1242 // assume if cannot for now
1243
1244 if (DBG) {
1245 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1246 feature);
1247 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001248 if (network.reconnect()) {
1249 return PhoneConstants.APN_REQUEST_STARTED;
1250 } else {
1251 return PhoneConstants.APN_REQUEST_FAILED;
1252 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001253 } else {
1254 // need to remember this unsupported request so we respond appropriately on stop
1255 synchronized(this) {
1256 mFeatureUsers.add(f);
1257 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1258 // this gets used for per-pid dns when connected
1259 mNetRequestersPids[usedNetworkType].add(currentPid);
1260 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001261 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001262 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001263 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001264 }
Wink Saville64e3f782012-07-10 12:37:54 -07001265 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001266 } finally {
1267 if (DBG) {
1268 final long execTime = SystemClock.elapsedRealtime() - startTime;
1269 if (execTime > 250) {
1270 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1271 } else {
1272 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1273 }
1274 }
1275 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001276 }
1277
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001278 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001279 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001280 enforceChangePermission();
1281
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001282 int pid = getCallingPid();
1283 int uid = getCallingUid();
1284
1285 FeatureUser u = null;
1286 boolean found = false;
1287
1288 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001289 for (FeatureUser x : mFeatureUsers) {
1290 if (x.isSameUser(pid, uid, networkType, feature)) {
1291 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001292 found = true;
1293 break;
1294 }
1295 }
1296 }
1297 if (found && u != null) {
1298 // stop regardless of how many other time this proc had called start
1299 return stopUsingNetworkFeature(u, true);
1300 } else {
1301 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001302 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001303 return 1;
1304 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001305 }
1306
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001307 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1308 int networkType = u.mNetworkType;
1309 String feature = u.mFeature;
1310 int pid = u.mPid;
1311 int uid = u.mUid;
1312
1313 NetworkStateTracker tracker = null;
1314 boolean callTeardown = false; // used to carry our decision outside of sync block
1315
Wink Savillea7d56572011-09-21 11:05:43 -07001316 if (VDBG) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001318 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001319
The Android Open Source Project28527d22009-03-03 19:31:44 -08001320 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001321 if (DBG) {
1322 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1323 ", net is invalid");
1324 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001325 return -1;
1326 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001327
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001328 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1329 // sync block
1330 synchronized(this) {
1331 // check if this process still has an outstanding start request
1332 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001333 if (VDBG) {
1334 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1335 ", ignoring");
1336 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001337 return 1;
1338 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001339 u.unlinkDeathRecipient();
1340 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1341 // If we care about duplicate requests, check for that here.
1342 //
1343 // This is done to support the extension of a request - the app
1344 // can request we start the network feature again and renew the
1345 // auto-shutoff delay. Normal "stop" calls from the app though
1346 // do not pay attention to duplicate requests - in effect the
1347 // API does not refcount and a single stop will counter multiple starts.
1348 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001349 for (FeatureUser x : mFeatureUsers) {
1350 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001351 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001352 return 1;
1353 }
1354 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001355 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001356
repo syncf5de5572011-07-29 23:55:49 -07001357 // TODO - move to individual network trackers
1358 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1359
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001360 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001361 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001362 if (DBG) {
1363 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1364 " no known tracker for used net type " + usedNetworkType);
1365 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001366 return -1;
1367 }
1368 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001369 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001370 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001371
1372 final long token = Binder.clearCallingIdentity();
1373 try {
1374 reassessPidDns(pid, true);
1375 } finally {
1376 Binder.restoreCallingIdentity(token);
1377 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001378 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001379 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001380 if (VDBG) {
1381 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1382 " others still using it");
1383 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001384 return 1;
1385 }
1386 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001387 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001388 if (DBG) {
1389 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1390 " not a known feature - dropping");
1391 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001392 }
1393 }
Wink Savillea7d56572011-09-21 11:05:43 -07001394
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001396 if (DBG) {
1397 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1398 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001399 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001400 return 1;
1401 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001402 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001403 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 }
1405
1406 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001407 * @deprecated use requestRouteToHostAddress instead
1408 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001409 * Ensure that a network route exists to deliver traffic to the specified
1410 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001411 * @param networkType the type of the network over which traffic to the
1412 * specified host is to be routed
1413 * @param hostAddress the IP address of the host to which the route is
1414 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001415 * @return {@code true} on success, {@code false} on failure
1416 */
1417 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001418 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1419
1420 if (inetAddress == null) {
1421 return false;
1422 }
1423
1424 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1425 }
1426
1427 /**
1428 * Ensure that a network route exists to deliver traffic to the specified
1429 * host via the specified network interface.
1430 * @param networkType the type of the network over which traffic to the
1431 * specified host is to be routed
1432 * @param hostAddress the IP address of the host to which the route is
1433 * desired
1434 * @return {@code true} on success, {@code false} on failure
1435 */
1436 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001438 if (mProtectedNetworks.contains(networkType)) {
1439 enforceConnectivityInternalPermission();
1440 }
1441
The Android Open Source Project28527d22009-03-03 19:31:44 -08001442 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001443 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001444 return false;
1445 }
1446 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001447 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001448
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001449 if (tracker == null || (netState != DetailedState.CONNECTED &&
1450 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001451 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001452 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001453 log("requestRouteToHostAddress on down network "
1454 + "(" + networkType + ") - dropped"
1455 + " tracker=" + tracker
1456 + " netState=" + netState
1457 + " isTeardownRequested="
1458 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001459 }
1460 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001461 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001462 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001463 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001464 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001465 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001466 boolean ok = addRouteToAddress(lp, addr);
1467 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1468 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001469 } catch (UnknownHostException e) {
1470 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1471 } finally {
1472 Binder.restoreCallingIdentity(token);
1473 }
Wink Saville32506bc2013-06-29 21:10:57 -07001474 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001475 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001476 }
1477
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001478 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001479 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001480 }
1481
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001482 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001483 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001484 }
1485
Robert Greenwalt98107422011-07-22 11:55:33 -07001486 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001487 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001488 }
1489
1490 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001491 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001492 }
1493
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001494 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1495 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001496 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001497 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001498 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001499 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001500 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001501 if (bestRoute.getGateway().equals(addr)) {
1502 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001503 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001504 } else {
1505 // if we will connect to this through another route, add a direct route
1506 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001507 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001508 }
1509 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001510 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001511 }
1512
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001513 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1514 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001515 if ((lp == null) || (r == null)) {
1516 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001517 return false;
1518 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001519
1520 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001521 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001522 return false;
1523 }
1524
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001525 String ifaceName = r.getInterface();
1526 if(ifaceName == null) {
1527 loge("Error modifying route - no interface name");
1528 return false;
1529 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001530 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001531 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001532 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001533 if (bestRoute.getGateway().equals(r.getGateway())) {
1534 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001535 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001536 } else {
1537 // if we will connect to our gateway through another route, add a direct
1538 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001539 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1540 bestRoute.getGateway(),
1541 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001542 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001543 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001544 }
1545 }
1546 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001547 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001548 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001549 if (toDefaultTable) {
1550 mAddedRoutes.add(r); // only track default table - only one apps can effect
1551 mNetd.addRoute(ifaceName, r);
1552 } else {
1553 mNetd.addSecondaryRoute(ifaceName, r);
1554 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001555 } catch (Exception e) {
1556 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001557 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001558 return false;
1559 }
1560 } else {
1561 // if we remove this one and there are no more like it, then refcount==0 and
1562 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001563 if (toDefaultTable) {
1564 mAddedRoutes.remove(r);
1565 if (mAddedRoutes.contains(r) == false) {
1566 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1567 try {
1568 mNetd.removeRoute(ifaceName, r);
1569 } catch (Exception e) {
1570 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001571 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001572 return false;
1573 }
1574 } else {
1575 if (VDBG) log("not removing " + r + " as it's still in use");
1576 }
1577 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001578 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001579 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001580 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001581 } catch (Exception e) {
1582 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001583 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001584 return false;
1585 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001586 }
1587 }
1588 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001589 }
1590
1591 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001592 * @see ConnectivityManager#getMobileDataEnabled()
1593 */
1594 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001595 // TODO: This detail should probably be in DataConnectionTracker's
1596 // which is where we store the value and maybe make this
1597 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001598 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001599 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1600 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001601 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001602 return retVal;
1603 }
1604
Robert Greenwalt34848c02011-03-25 13:09:25 -07001605 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001606 enforceConnectivityInternalPermission();
1607
Robert Greenwalt34848c02011-03-25 13:09:25 -07001608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1609 (met ? ENABLED : DISABLED), networkType));
1610 }
1611
1612 private void handleSetDependencyMet(int networkType, boolean met) {
1613 if (mNetTrackers[networkType] != null) {
1614 if (DBG) {
1615 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1616 }
1617 mNetTrackers[networkType].setDependencyMet(met);
1618 }
1619 }
1620
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001621 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1622 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001623 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001624 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001625 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001626 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001627 }
1628
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001629 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001630 // skip update when we've already applied rules
1631 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1632 if (oldRules == uidRules) return;
1633
1634 mUidRules.put(uid, uidRules);
1635 }
1636
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001637 // TODO: notify UID when it has requested targeted updates
1638 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001639
1640 @Override
1641 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001642 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001643 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001644 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001645 }
1646
1647 synchronized (mRulesLock) {
1648 mMeteredIfaces.clear();
1649 for (String iface : meteredIfaces) {
1650 mMeteredIfaces.add(iface);
1651 }
1652 }
1653 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001654
1655 @Override
1656 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1657 // caller is NPMS, since we only register with them
1658 if (LOGD_RULES) {
1659 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1660 }
1661
1662 // kick off connectivity change broadcast for active network, since
1663 // global background policy change is radical.
1664 final int networkType = mActiveDefaultNetwork;
1665 if (isNetworkTypeValid(networkType)) {
1666 final NetworkStateTracker tracker = mNetTrackers[networkType];
1667 if (tracker != null) {
1668 final NetworkInfo info = tracker.getNetworkInfo();
1669 if (info != null && info.isConnected()) {
1670 sendConnectedBroadcast(info);
1671 }
1672 }
1673 }
1674 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001675 };
1676
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001677 /**
1678 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1679 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001680 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001681 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001682 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001683
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001685 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001686 }
1687
1688 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001689 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001690 if (VDBG) {
1691 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001692 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001693 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1694 }
tk.mun5eee1042012-01-06 10:43:52 +09001695 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1696 if (VDBG) {
1697 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1698 }
1699 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1700 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001701 }
1702
1703 @Override
1704 public void setPolicyDataEnable(int networkType, boolean enabled) {
1705 // only someone like NPMS should only be calling us
1706 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1707
1708 mHandler.sendMessage(mHandler.obtainMessage(
1709 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1710 }
1711
1712 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1713 if (isNetworkTypeValid(networkType)) {
1714 final NetworkStateTracker tracker = mNetTrackers[networkType];
1715 if (tracker != null) {
1716 tracker.setPolicyDataEnable(enabled);
1717 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001718 }
1719 }
1720
The Android Open Source Project28527d22009-03-03 19:31:44 -08001721 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001722 mContext.enforceCallingOrSelfPermission(
1723 android.Manifest.permission.ACCESS_NETWORK_STATE,
1724 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001725 }
1726
1727 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001728 mContext.enforceCallingOrSelfPermission(
1729 android.Manifest.permission.CHANGE_NETWORK_STATE,
1730 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001731 }
1732
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001733 // TODO Make this a special check when it goes public
1734 private void enforceTetherChangePermission() {
1735 mContext.enforceCallingOrSelfPermission(
1736 android.Manifest.permission.CHANGE_NETWORK_STATE,
1737 "ConnectivityService");
1738 }
1739
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001740 private void enforceTetherAccessPermission() {
1741 mContext.enforceCallingOrSelfPermission(
1742 android.Manifest.permission.ACCESS_NETWORK_STATE,
1743 "ConnectivityService");
1744 }
1745
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001746 private void enforceConnectivityInternalPermission() {
1747 mContext.enforceCallingOrSelfPermission(
1748 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1749 "ConnectivityService");
1750 }
1751
The Android Open Source Project28527d22009-03-03 19:31:44 -08001752 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001753 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1754 * network, we ignore it. If it is for the active network, we send out a
1755 * broadcast. But first, we check whether it might be possible to connect
1756 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001757 * @param info the {@code NetworkInfo} for the network
1758 */
1759 private void handleDisconnect(NetworkInfo info) {
1760
Robert Greenwalt2034b912009-08-12 16:08:25 -07001761 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001762
Robert Greenwalt2034b912009-08-12 16:08:25 -07001763 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001764
1765 // Remove idletimer previously setup in {@code handleConnect}
1766 removeDataActivityTracking(prevNetType);
1767
The Android Open Source Project28527d22009-03-03 19:31:44 -08001768 /*
1769 * If the disconnected network is not the active one, then don't report
1770 * this as a loss of connectivity. What probably happened is that we're
1771 * getting the disconnect for a network that we explicitly disabled
1772 * in accordance with network preference policies.
1773 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001774 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001775 List<Integer> pids = mNetRequestersPids[prevNetType];
1776 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001777 // will remove them because the net's no longer connected
1778 // need to do this now as only now do we know the pids and
1779 // can properly null things that are no longer referenced.
1780 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001781 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001782 }
1783
The Android Open Source Project28527d22009-03-03 19:31:44 -08001784 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001785 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001786 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001787 if (info.isFailover()) {
1788 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1789 info.setFailover(false);
1790 }
1791 if (info.getReason() != null) {
1792 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1793 }
1794 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001795 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1796 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001797 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001798
Robert Greenwalt34848c02011-03-25 13:09:25 -07001799 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001800 tryFailover(prevNetType);
1801 if (mActiveDefaultNetwork != -1) {
1802 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001803 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1804 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001805 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001806 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1807 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001808 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001809 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001810
1811 // Reset interface if no other connections are using the same interface
1812 boolean doReset = true;
1813 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1814 if (linkProperties != null) {
1815 String oldIface = linkProperties.getInterfaceName();
1816 if (TextUtils.isEmpty(oldIface) == false) {
1817 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1818 if (networkStateTracker == null) continue;
1819 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1820 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1821 LinkProperties l = networkStateTracker.getLinkProperties();
1822 if (l == null) continue;
1823 if (oldIface.equals(l.getInterfaceName())) {
1824 doReset = false;
1825 break;
1826 }
1827 }
1828 }
1829 }
1830 }
1831
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001832 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001833 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001834
Jeff Sharkey971cd162011-08-29 16:02:57 -07001835 final Intent immediateIntent = new Intent(intent);
1836 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1837 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001838 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001839 /*
1840 * If the failover network is already connected, then immediately send
1841 * out a followup broadcast indicating successful failover
1842 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001843 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001844 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1845 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001846 }
1847 }
1848
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001849 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001850 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001851 * If this is a default network, check if other defaults are available.
1852 * Try to reconnect on all available and let them hash it out when
1853 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001854 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001855 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001856 if (mActiveDefaultNetwork == prevNetType) {
1857 mActiveDefaultNetwork = -1;
1858 }
1859
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001860 // don't signal a reconnect for anything lower or equal priority than our
1861 // current connected default
1862 // TODO - don't filter by priority now - nice optimization but risky
1863// int currentPriority = -1;
1864// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001865// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001866// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001867 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001868 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001869 if (mNetConfigs[checkType] == null) continue;
1870 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001871 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001872
1873// Enabling the isAvailable() optimization caused mobile to not get
1874// selected if it was in the middle of error handling. Specifically
1875// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1876// would not be available and we wouldn't get connected to anything.
1877// So removing the isAvailable() optimization below for now. TODO: This
1878// optimization should work and we need to investigate why it doesn't work.
1879// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1880// complete before it is really complete.
1881// if (!mNetTrackers[checkType].isAvailable()) continue;
1882
Robert Greenwalt34848c02011-03-25 13:09:25 -07001883// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001884
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001885 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1886 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1887 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1888 checkInfo.setFailover(true);
1889 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001890 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001891 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001892 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001893 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001894 }
1895
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001896 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001897 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001898 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1899 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001900 }
1901
Wink Saville4f0de1e2011-08-04 15:01:58 -07001902 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001903 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1904 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001905 }
1906
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001907 private void sendInetConditionBroadcast(NetworkInfo info) {
1908 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1909 }
1910
Wink Saville4f0de1e2011-08-04 15:01:58 -07001911 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001912 if (mLockdownTracker != null) {
1913 info = mLockdownTracker.augmentNetworkInfo(info);
1914 }
1915
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001916 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001917 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001918 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001919 if (info.isFailover()) {
1920 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1921 info.setFailover(false);
1922 }
1923 if (info.getReason() != null) {
1924 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1925 }
1926 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001927 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1928 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001930 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001931 return intent;
1932 }
1933
1934 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1935 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1936 }
1937
1938 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1939 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001940 }
1941
Haoyu Baib5da5752012-06-20 14:29:57 -07001942 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1943 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1944 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1945 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001946 final long ident = Binder.clearCallingIdentity();
1947 try {
1948 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1949 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1950 } finally {
1951 Binder.restoreCallingIdentity(ident);
1952 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001953 }
1954
The Android Open Source Project28527d22009-03-03 19:31:44 -08001955 /**
1956 * Called when an attempt to fail over to another network has failed.
1957 * @param info the {@link NetworkInfo} for the failed network
1958 */
1959 private void handleConnectionFailure(NetworkInfo info) {
1960 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001961
Robert Greenwalt2034b912009-08-12 16:08:25 -07001962 String reason = info.getReason();
1963 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001964
Robert Greenwalte981bc52010-10-08 16:35:52 -07001965 String reasonText;
1966 if (reason == null) {
1967 reasonText = ".";
1968 } else {
1969 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001970 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001971 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001972
1973 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001974 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001975 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001976 if (getActiveNetworkInfo() == null) {
1977 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1978 }
1979 if (reason != null) {
1980 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1981 }
1982 if (extraInfo != null) {
1983 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1984 }
1985 if (info.isFailover()) {
1986 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1987 info.setFailover(false);
1988 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001989
Robert Greenwalt34848c02011-03-25 13:09:25 -07001990 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001991 tryFailover(info.getType());
1992 if (mActiveDefaultNetwork != -1) {
1993 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001994 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1995 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001996 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001997 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1998 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001999 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002000
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002001 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002002
2003 final Intent immediateIntent = new Intent(intent);
2004 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2005 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002006 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002007 /*
2008 * If the failover network is already connected, then immediately send
2009 * out a followup broadcast indicating successful failover
2010 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002011 if (mActiveDefaultNetwork != -1) {
2012 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002013 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002014 }
2015
2016 private void sendStickyBroadcast(Intent intent) {
2017 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002018 if (!mSystemReady) {
2019 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002020 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002021 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002022 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002023 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002024 }
2025
Dianne Hackborne588ca12012-09-04 18:48:37 -07002026 final long ident = Binder.clearCallingIdentity();
2027 try {
2028 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2029 } finally {
2030 Binder.restoreCallingIdentity(ident);
2031 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002032 }
2033 }
2034
Wink Saville4f0de1e2011-08-04 15:01:58 -07002035 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2036 if (delayMs <= 0) {
2037 sendStickyBroadcast(intent);
2038 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002039 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002040 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2041 + intent.getAction());
2042 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002043 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2044 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2045 }
2046 }
2047
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002048 void systemReady() {
2049 synchronized(this) {
2050 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002051 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002052 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002053 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002054 }
2055 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002056 // load the global proxy at startup
2057 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002058
2059 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2060 // for user to unlock device.
2061 if (!updateLockdownVpn()) {
2062 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2063 mContext.registerReceiver(mUserPresentReceiver, filter);
2064 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002065 }
2066
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002067 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2068 @Override
2069 public void onReceive(Context context, Intent intent) {
2070 // Try creating lockdown tracker, since user present usually means
2071 // unlocked keystore.
2072 if (updateLockdownVpn()) {
2073 mContext.unregisterReceiver(this);
2074 }
2075 }
2076 };
2077
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002078 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2079 if ((type != mNetworkPreference &&
2080 mNetConfigs[mActiveDefaultNetwork].priority >
2081 mNetConfigs[type].priority) ||
2082 mNetworkPreference == mActiveDefaultNetwork) return false;
2083 return true;
2084 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002086 private void handleConnect(NetworkInfo info) {
2087 final int newNetType = info.getType();
2088
2089 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002090
The Android Open Source Project28527d22009-03-03 19:31:44 -08002091 // snapshot isFailover, because sendConnectedBroadcast() resets it
2092 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002093 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002094 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095
Robert Greenwalt2034b912009-08-12 16:08:25 -07002096 // if this is a default net and other default is running
2097 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002098 if (mNetConfigs[newNetType].isDefault()) {
2099 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2100 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002101 // tear down the other
2102 NetworkStateTracker otherNet =
2103 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002104 if (DBG) {
2105 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002106 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002107 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002108 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002109 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002110 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002111 return;
2112 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002113 } else {
2114 // don't accept this one
2115 if (VDBG) {
2116 log("Not broadcasting CONNECT_ACTION " +
2117 "to torn down network " + info.getTypeName());
2118 }
2119 teardown(thisNet);
2120 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002121 }
2122 }
2123 synchronized (ConnectivityService.this) {
2124 // have a new default network, release the transition wakelock in a second
2125 // if it's held. The second pause is to allow apps to reconnect over the
2126 // new network
2127 if (mNetTransitionWakeLock.isHeld()) {
2128 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002129 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002130 mNetTransitionWakeLockSerialNumber, 0),
2131 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002132 }
2133 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002134 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002135 // this will cause us to come up initially as unconnected and switching
2136 // to connected after our normal pause unless somebody reports us as reall
2137 // disconnected
2138 mDefaultInetConditionPublished = 0;
2139 mDefaultConnectionSequence++;
2140 mInetConditionChangeInFlight = false;
2141 // Don't do this - if we never sign in stay, grey
2142 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002143 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002144 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002145 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002146 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002147 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002148
2149 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002150 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002151 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002152 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002153 } catch (RemoteException e) {
2154 // ignored; service lives in system_server
2155 }
2156 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002157 }
2158
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002159 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2160 if (DBG) log("Captive portal check " + info);
2161 int type = info.getType();
2162 final NetworkStateTracker thisNet = mNetTrackers[type];
2163 if (mNetConfigs[type].isDefault()) {
2164 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2165 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2166 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002167 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002168 return;
2169 } else {
2170 if (DBG) log("Tear down low priority net " + info.getTypeName());
2171 teardown(thisNet);
2172 return;
2173 }
2174 }
2175 }
2176
2177 thisNet.captivePortalCheckComplete();
2178 }
2179
2180 /** @hide */
2181 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002182 enforceConnectivityInternalPermission();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002183 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002184 }
2185
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002187 * Setup data activity tracking for the given network interface.
2188 *
2189 * Every {@code setupDataActivityTracking} should be paired with a
2190 * {@link removeDataActivityTracking} for cleanup.
2191 */
2192 private void setupDataActivityTracking(int type) {
2193 final NetworkStateTracker thisNet = mNetTrackers[type];
2194 final String iface = thisNet.getLinkProperties().getInterfaceName();
2195
2196 final int timeout;
2197
2198 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002199 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2200 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002201 0);
2202 // Canonicalize mobile network type
2203 type = ConnectivityManager.TYPE_MOBILE;
2204 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002205 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2206 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002207 0);
2208 } else {
2209 // do not track any other networks
2210 timeout = 0;
2211 }
2212
2213 if (timeout > 0 && iface != null) {
2214 try {
2215 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2216 } catch (RemoteException e) {
2217 }
2218 }
2219 }
2220
2221 /**
2222 * Remove data activity tracking when network disconnects.
2223 */
2224 private void removeDataActivityTracking(int type) {
2225 final NetworkStateTracker net = mNetTrackers[type];
2226 final String iface = net.getLinkProperties().getInterfaceName();
2227
2228 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2229 ConnectivityManager.TYPE_WIFI == type)) {
2230 try {
2231 // the call fails silently if no idletimer setup for this interface
2232 mNetd.removeIdleTimer(iface);
2233 } catch (RemoteException e) {
2234 }
2235 }
2236 }
2237
2238 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002239 * After a change in the connectivity state of a network. We're mainly
2240 * concerned with making sure that the list of DNS servers is set up
2241 * according to which networks are connected, and ensuring that the
2242 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002243 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002244 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002245 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2246
The Android Open Source Project28527d22009-03-03 19:31:44 -08002247 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002248 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002249 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002250 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002251 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002252
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002253 LinkProperties curLp = mCurrentLinkProperties[netType];
2254 LinkProperties newLp = null;
2255
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002256 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002257 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002258 if (VDBG) {
2259 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2260 " doReset=" + doReset + " resetMask=" + resetMask +
2261 "\n curLp=" + curLp +
2262 "\n newLp=" + newLp);
2263 }
2264
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002265 if (curLp != null) {
2266 if (curLp.isIdenticalInterfaceName(newLp)) {
2267 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2268 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2269 for (LinkAddress linkAddr : car.removed) {
2270 if (linkAddr.getAddress() instanceof Inet4Address) {
2271 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2272 }
2273 if (linkAddr.getAddress() instanceof Inet6Address) {
2274 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2275 }
Wink Saville051a6642011-07-13 13:44:13 -07002276 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002277 if (DBG) {
2278 log("handleConnectivityChange: addresses changed" +
2279 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2280 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002281 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002282 } else {
2283 if (DBG) {
2284 log("handleConnectivityChange: address are the same reset per doReset" +
2285 " linkProperty[" + netType + "]:" +
2286 " resetMask=" + resetMask);
2287 }
Wink Saville051a6642011-07-13 13:44:13 -07002288 }
2289 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002290 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002291 if (DBG) {
2292 log("handleConnectivityChange: interface not not equivalent reset both" +
2293 " linkProperty[" + netType + "]:" +
2294 " resetMask=" + resetMask);
2295 }
Wink Saville051a6642011-07-13 13:44:13 -07002296 }
Wink Saville051a6642011-07-13 13:44:13 -07002297 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002298 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002299 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002300 }
2301 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002302 if (VDBG) {
2303 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2304 " doReset=" + doReset + " resetMask=" + resetMask +
2305 "\n curLp=" + curLp +
2306 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002307 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002308 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002309 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002310 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002311
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002312 if (resetMask != 0 || resetDns) {
Robert Greenwalt4398f342013-05-23 18:33:06 -07002313 if (curLp != null) {
2314 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002315 if (TextUtils.isEmpty(iface) == false) {
2316 if (resetMask != 0) {
2317 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2318 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002319
Lorenzo Colitti63839822013-03-20 19:22:58 +09002320 // Tell VPN the interface is down. It is a temporary
2321 // but effective fix to make VPN aware of the change.
2322 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002323 synchronized(mVpns) {
2324 for (int i = 0; i < mVpns.size(); i++) {
2325 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2326 }
2327 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002328 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002329 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002330 if (resetDns) {
2331 flushVmDnsCache();
2332 if (VDBG) log("resetting DNS cache for " + iface);
2333 try {
2334 mNetd.flushInterfaceDnsCache(iface);
2335 } catch (Exception e) {
2336 // never crash - catch them all
2337 if (DBG) loge("Exception resetting dns cache: " + e);
2338 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002339 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002340 } else {
2341 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002342 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002343 }
2344 }
2345 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002346
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002347 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002348 NetworkStateTracker tracker = mNetTrackers[netType];
2349 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002350 // If the connection was previously using clat, but is not using it now, stop the clat
2351 // daemon. Normally, this happens automatically when the connection disconnects, but if
2352 // the disconnect is not reported, or if the connection's LinkProperties changed for
2353 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2354 // still be running. If it's not running, then stopping it is a no-op.
2355 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2356 mClat.stopClat();
2357 }
2358 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002359 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2360 mClat.startClat(tracker);
2361 } else {
2362 mClat.stopClat();
2363 }
2364 }
2365
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002366 // TODO: Temporary notifying upstread change to Tethering.
2367 // @see bug/4455071
2368 /** Notify TetheringService if interface name has been changed. */
2369 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002370 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002371 if (isTetheringSupported()) {
2372 mTethering.handleTetherIfaceChange();
2373 }
2374 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002375 }
2376
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002377 /**
2378 * Add and remove routes using the old properties (null if not previously connected),
2379 * new properties (null if becoming disconnected). May even be double null, which
2380 * is a noop.
2381 * Uses isLinkDefault to determine if default routes should be set or conversely if
2382 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002383 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002384 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002385 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2386 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002387 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002388 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2389 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002390 if (curLp != null) {
2391 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002392 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002393 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002394 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002395 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002396 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002397 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002398
Robert Greenwalt8d777252011-08-15 12:31:55 -07002399 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2400
Robert Greenwalt98107422011-07-22 11:55:33 -07002401 for (RouteInfo r : routeDiff.removed) {
2402 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002403 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2404 }
2405 if (isLinkDefault == false) {
2406 // remove from a secondary route table
2407 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002408 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002409 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002410
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002411 if (!isLinkDefault) {
2412 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002413 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002414 // routes changed - remove all old dns entries and add new
2415 if (curLp != null) {
2416 for (InetAddress oldDns : curLp.getDnses()) {
2417 removeRouteToAddress(curLp, oldDns);
2418 }
2419 }
2420 if (newLp != null) {
2421 for (InetAddress newDns : newLp.getDnses()) {
2422 addRouteToAddress(newLp, newDns);
2423 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002424 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002425 } else {
2426 // no change in routes, check for change in dns themselves
2427 for (InetAddress oldDns : dnsDiff.removed) {
2428 removeRouteToAddress(curLp, oldDns);
2429 }
2430 for (InetAddress newDns : dnsDiff.added) {
2431 addRouteToAddress(newLp, newDns);
2432 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002433 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002434 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002435
2436 for (RouteInfo r : routeDiff.added) {
2437 if (isLinkDefault || ! r.isDefaultRoute()) {
2438 addRoute(newLp, r, TO_DEFAULT_TABLE);
2439 } else {
2440 // add to a secondary route table
2441 addRoute(newLp, r, TO_SECONDARY_TABLE);
2442
2443 // many radios add a default route even when we don't want one.
2444 // remove the default route unless somebody else has asked for it
2445 String ifaceName = newLp.getInterfaceName();
2446 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2447 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2448 try {
2449 mNetd.removeRoute(ifaceName, r);
2450 } catch (Exception e) {
2451 // never crash - catch them all
2452 if (DBG) loge("Exception trying to remove a route: " + e);
2453 }
2454 }
2455 }
2456 }
2457
Robert Greenwalt8d777252011-08-15 12:31:55 -07002458 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002459 }
2460
2461
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002462 /**
2463 * Reads the network specific TCP buffer sizes from SystemProperties
2464 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2465 * wide use
2466 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002467 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002468 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002469 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002470
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002471 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002472 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002473
2474 // Setting to default values so we won't be stuck to previous values
2475 key = "net.tcp.buffersize.default";
2476 bufferSizes = SystemProperties.get(key);
2477 }
2478
2479 // Set values in kernel
2480 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002481 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002482 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002483 + "] which comes from [" + key + "]");
2484 }
2485 setBufferSize(bufferSizes);
2486 }
2487 }
2488
2489 /**
2490 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2491 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2492 *
2493 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2494 * writeMin, writeInitial, writeMax"
2495 */
2496 private void setBufferSize(String bufferSizes) {
2497 try {
2498 String[] values = bufferSizes.split(",");
2499
2500 if (values.length == 6) {
2501 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002502 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2503 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2504 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2505 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2506 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2507 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002508 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002509 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002510 }
2511 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002512 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002513 }
2514 }
2515
Robert Greenwalt2034b912009-08-12 16:08:25 -07002516 /**
2517 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2518 * on the highest priority active net which this process requested.
2519 * If there aren't any, clear it out
2520 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002521 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002522 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002523 if (VDBG) log("reassessPidDns for pid " + pid);
2524 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002525 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002526 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002527 continue;
2528 }
2529 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002530 if (nt.getNetworkInfo().isConnected() &&
2531 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002532 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002533 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002534 if (mNetRequestersPids[i].contains(myPid)) {
2535 try {
2536 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2537 } catch (Exception e) {
2538 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002539 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002540 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002541 }
2542 }
2543 }
2544 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002545 try {
2546 mNetd.clearDnsInterfaceForPid(pid);
2547 } catch (Exception e) {
2548 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002549 }
2550 }
2551
Mattias Falkd697aa22011-08-23 14:15:13 +02002552 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002553 /*
2554 * Tell the VMs to toss their DNS caches
2555 */
2556 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2557 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002558 /*
2559 * Connectivity events can happen before boot has completed ...
2560 */
2561 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002562 final long ident = Binder.clearCallingIdentity();
2563 try {
2564 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2565 } finally {
2566 Binder.restoreCallingIdentity(ident);
2567 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002568 }
2569
Chia-chi Yehcc844502011-07-14 18:01:57 -07002570 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002571 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002572 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002573 int last = 0;
2574 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002575 dnses = new ArrayList();
2576 dnses.add(mDefaultDns);
2577 if (DBG) {
2578 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002579 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002580 }
2581
Mattias Falkd697aa22011-08-23 14:15:13 +02002582 try {
2583 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002584 for (InetAddress dns : dnses) {
2585 ++last;
2586 String key = "net.dns" + last;
2587 String value = dns.getHostAddress();
2588 SystemProperties.set(key, value);
2589 }
2590 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2591 String key = "net.dns" + i;
2592 SystemProperties.set(key, "");
2593 }
2594 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002595 } catch (Exception e) {
2596 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002597 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002598 }
2599
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002600 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002601 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002602 NetworkStateTracker nt = mNetTrackers[netType];
2603 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002604 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002605 if (p == null) return;
2606 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002607 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002608 String network = nt.getNetworkInfo().getTypeName();
2609 synchronized (mDnsLock) {
2610 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002611 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002612 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002613 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002614 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002615 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002616 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002617 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002618 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002619 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002620 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002621 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002622 List<Integer> pids = mNetRequestersPids[netType];
2623 for (Integer pid : pids) {
2624 try {
2625 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2626 } catch (Exception e) {
2627 Slog.e(TAG, "exception setting interface for pid: " + e);
2628 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002629 }
2630 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002631 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002632 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002633 }
2634
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002635 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002636 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2637 NETWORK_RESTORE_DELAY_PROP_NAME);
2638 if(restoreDefaultNetworkDelayStr != null &&
2639 restoreDefaultNetworkDelayStr.length() != 0) {
2640 try {
2641 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2642 } catch (NumberFormatException e) {
2643 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002644 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002645 // if the system property isn't set, use the value for the apn type
2646 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2647
2648 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2649 (mNetConfigs[networkType] != null)) {
2650 ret = mNetConfigs[networkType].restoreTime;
2651 }
2652 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002653 }
2654
2655 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002656 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2657 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002658 if (mContext.checkCallingOrSelfPermission(
2659 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002660 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002661 pw.println("Permission Denial: can't dump ConnectivityService " +
2662 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2663 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002664 return;
2665 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002666
2667 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002668 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002669 for (int i = 0; i < mNetTrackers.length; i++) {
2670 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002671 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002672 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2673 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002674 if (nst.getNetworkInfo().isConnected()) {
2675 pw.println("Active network: " + nst.getNetworkInfo().
2676 getTypeName());
2677 }
2678 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002679 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002680 pw.println(nst);
2681 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002682 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002683 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002684 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002685
2686 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002687 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002688 for (int net : mPriorityList) {
2689 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002690 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002691 pidString = pidString + pid.toString() + ", ";
2692 }
2693 pw.println(pidString);
2694 }
2695 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002696 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002697
2698 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002699 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002700 for (Object requester : mFeatureUsers) {
2701 pw.println(requester.toString());
2702 }
2703 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002704 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002705
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002706 synchronized (this) {
2707 pw.println("NetworkTranstionWakeLock is currently " +
2708 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2709 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2710 }
2711 pw.println();
2712
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002713 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002714
2715 if (mInetLog != null) {
2716 pw.println();
2717 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002718 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002719 for(int i = 0; i < mInetLog.size(); i++) {
2720 pw.println(mInetLog.get(i));
2721 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002722 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002723 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002724 }
2725
Robert Greenwalt2034b912009-08-12 16:08:25 -07002726 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002727 private class NetworkStateTrackerHandler extends Handler {
2728 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002729 super(looper);
2730 }
2731
The Android Open Source Project28527d22009-03-03 19:31:44 -08002732 @Override
2733 public void handleMessage(Message msg) {
2734 NetworkInfo info;
2735 switch (msg.what) {
2736 case NetworkStateTracker.EVENT_STATE_CHANGED:
2737 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002738 int type = info.getType();
2739 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002740
Wink Savillea7d56572011-09-21 11:05:43 -07002741 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2742 (state == NetworkInfo.State.DISCONNECTED)) {
2743 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002744 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002745 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002746 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002747
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002748 EventLogTags.writeConnectivityStateChanged(
2749 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002750
2751 if (info.getDetailedState() ==
2752 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002753 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002754 } else if (info.getDetailedState() ==
2755 DetailedState.CAPTIVE_PORTAL_CHECK) {
2756 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002757 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002758 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002759 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002760 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002761 // the logic here is, handle SUSPENDED the same as
2762 // DISCONNECTED. The only difference being we are
2763 // broadcasting an intent with NetworkInfo that's
2764 // suspended. This allows the applications an
2765 // opportunity to handle DISCONNECTED and SUSPENDED
2766 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002767 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002768 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002769 handleConnect(info);
2770 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002771 if (mLockdownTracker != null) {
2772 mLockdownTracker.onNetworkInfoChanged(info);
2773 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002774 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002775 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002776 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002777 // TODO: Temporary allowing network configuration
2778 // change not resetting sockets.
2779 // @see bug/4455071
2780 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002781 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002782 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2783 info = (NetworkInfo) msg.obj;
2784 type = info.getType();
2785 updateNetworkSettings(mNetTrackers[type]);
2786 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002787 }
2788 }
2789 }
2790
2791 private class InternalHandler extends Handler {
2792 public InternalHandler(Looper looper) {
2793 super(looper);
2794 }
2795
2796 @Override
2797 public void handleMessage(Message msg) {
2798 NetworkInfo info;
2799 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002800 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002801 String causedBy = null;
2802 synchronized (ConnectivityService.this) {
2803 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2804 mNetTransitionWakeLock.isHeld()) {
2805 mNetTransitionWakeLock.release();
2806 causedBy = mNetTransitionWakeLockCausedBy;
2807 }
2808 }
2809 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002810 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002811 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002812 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002813 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002814 FeatureUser u = (FeatureUser)msg.obj;
2815 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002816 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002817 case EVENT_INET_CONDITION_CHANGE:
2818 {
2819 int netType = msg.arg1;
2820 int condition = msg.arg2;
2821 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002822 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002823 }
2824 case EVENT_INET_CONDITION_HOLD_END:
2825 {
2826 int netType = msg.arg1;
2827 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00002828 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002829 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002830 }
2831 case EVENT_SET_NETWORK_PREFERENCE:
2832 {
2833 int preference = msg.arg1;
2834 handleSetNetworkPreference(preference);
2835 break;
2836 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002837 case EVENT_SET_MOBILE_DATA:
2838 {
2839 boolean enabled = (msg.arg1 == ENABLED);
2840 handleSetMobileData(enabled);
2841 break;
2842 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002843 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2844 {
2845 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002846 break;
2847 }
2848 case EVENT_SET_DEPENDENCY_MET:
2849 {
2850 boolean met = (msg.arg1 == ENABLED);
2851 handleSetDependencyMet(msg.arg2, met);
2852 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002853 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002854 case EVENT_RESTORE_DNS:
2855 {
2856 if (mActiveDefaultNetwork != -1) {
2857 handleDnsConfigurationChange(mActiveDefaultNetwork);
2858 }
2859 break;
2860 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002861 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2862 {
2863 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002864 sendStickyBroadcast(intent);
2865 break;
2866 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002867 case EVENT_SET_POLICY_DATA_ENABLE: {
2868 final int networkType = msg.arg1;
2869 final boolean enabled = msg.arg2 == ENABLED;
2870 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002871 break;
2872 }
2873 case EVENT_VPN_STATE_CHANGED: {
2874 if (mLockdownTracker != null) {
2875 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2876 }
2877 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002878 }
Wink Saville32506bc2013-06-29 21:10:57 -07002879 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2880 int tag = mEnableFailFastMobileDataTag.get();
2881 if (msg.arg1 == tag) {
2882 MobileDataStateTracker mobileDst =
2883 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2884 if (mobileDst != null) {
2885 mobileDst.setEnableFailFastMobileData(msg.arg2);
2886 }
2887 } else {
2888 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2889 + " != tag:" + tag);
2890 }
2891 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002892 }
2893 }
2894 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002895
2896 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002897 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002898 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002899
2900 if (isTetheringSupported()) {
2901 return mTethering.tether(iface);
2902 } else {
2903 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2904 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002905 }
2906
2907 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002908 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002909 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002910
2911 if (isTetheringSupported()) {
2912 return mTethering.untether(iface);
2913 } else {
2914 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2915 }
2916 }
2917
2918 // javadoc from interface
2919 public int getLastTetherError(String iface) {
2920 enforceTetherAccessPermission();
2921
2922 if (isTetheringSupported()) {
2923 return mTethering.getLastTetherError(iface);
2924 } else {
2925 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2926 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002927 }
2928
2929 // TODO - proper iface API for selection by property, inspection, etc
2930 public String[] getTetherableUsbRegexs() {
2931 enforceTetherAccessPermission();
2932 if (isTetheringSupported()) {
2933 return mTethering.getTetherableUsbRegexs();
2934 } else {
2935 return new String[0];
2936 }
2937 }
2938
2939 public String[] getTetherableWifiRegexs() {
2940 enforceTetherAccessPermission();
2941 if (isTetheringSupported()) {
2942 return mTethering.getTetherableWifiRegexs();
2943 } else {
2944 return new String[0];
2945 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002946 }
2947
Danica Chang96567052010-08-11 14:54:43 -07002948 public String[] getTetherableBluetoothRegexs() {
2949 enforceTetherAccessPermission();
2950 if (isTetheringSupported()) {
2951 return mTethering.getTetherableBluetoothRegexs();
2952 } else {
2953 return new String[0];
2954 }
2955 }
2956
Mike Lockwooded4a1742011-07-19 13:04:47 -07002957 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002958 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002959 if (isTetheringSupported()) {
2960 return mTethering.setUsbTethering(enable);
2961 } else {
2962 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2963 }
2964 }
2965
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002966 // TODO - move iface listing, queries, etc to new module
2967 // javadoc from interface
2968 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002969 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002970 return mTethering.getTetherableIfaces();
2971 }
2972
2973 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002974 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002975 return mTethering.getTetheredIfaces();
2976 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002977
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002978 @Override
2979 public String[] getTetheredIfacePairs() {
2980 enforceTetherAccessPermission();
2981 return mTethering.getTetheredIfacePairs();
2982 }
2983
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002984 public String[] getTetheringErroredIfaces() {
2985 enforceTetherAccessPermission();
2986 return mTethering.getErroredIfaces();
2987 }
2988
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002989 // if ro.tether.denied = true we default to no tethering
2990 // gservices could set the secure setting to 1 though to enable it on a build where it
2991 // had previously been turned off.
2992 public boolean isTetheringSupported() {
2993 enforceTetherAccessPermission();
2994 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07002995 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2996 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002997 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002998 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002999
3000 // An API NetworkStateTrackers can call when they lose their network.
3001 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3002 // whichever happens first. The timer is started by the first caller and not
3003 // restarted by subsequent callers.
3004 public void requestNetworkTransitionWakelock(String forWhom) {
3005 enforceConnectivityInternalPermission();
3006 synchronized (this) {
3007 if (mNetTransitionWakeLock.isHeld()) return;
3008 mNetTransitionWakeLockSerialNumber++;
3009 mNetTransitionWakeLock.acquire();
3010 mNetTransitionWakeLockCausedBy = forWhom;
3011 }
3012 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003013 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003014 mNetTransitionWakeLockSerialNumber, 0),
3015 mNetTransitionWakeLockTimeout);
3016 return;
3017 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003018
Robert Greenwalt986c7412010-09-08 15:24:47 -07003019 // 100 percent is full good, 0 is full bad.
3020 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003021 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003022 mContext.enforceCallingOrSelfPermission(
3023 android.Manifest.permission.STATUS_BAR,
3024 "ConnectivityService");
3025
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003026 if (DBG) {
3027 int pid = getCallingPid();
3028 int uid = getCallingUid();
3029 String s = pid + "(" + uid + ") reports inet is " +
3030 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3031 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3032 mInetLog.add(s);
3033 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3034 mInetLog.remove(0);
3035 }
3036 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003037 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003038 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3039 }
3040
3041 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003042 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003043 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003044 return;
3045 }
3046 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003047 if (DBG) log("handleInetConditionChange: net=" + netType +
3048 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003049 return;
3050 }
Wink Savillea7d56572011-09-21 11:05:43 -07003051 if (VDBG) {
3052 log("handleInetConditionChange: net=" +
3053 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003054 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003055 }
Wink Saville151eaa62013-01-31 00:30:13 +00003056 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003057 int delay;
3058 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003059 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003060 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003061 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003062 delay = Settings.Global.getInt(mContext.getContentResolver(),
3063 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003064 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003065 delay = Settings.Global.getInt(mContext.getContentResolver(),
3066 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003067 }
3068 mInetConditionChangeInFlight = true;
3069 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003070 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003071 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003072 // we've set the new condition, when this hold ends that will get picked up
3073 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003074 }
3075 }
3076
Wink Saville151eaa62013-01-31 00:30:13 +00003077 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003078 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003079 log("handleInetConditionHoldEnd: net=" + netType +
3080 ", condition=" + mDefaultInetCondition +
3081 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003082 }
3083 mInetConditionChangeInFlight = false;
3084
3085 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003086 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003087 return;
3088 }
3089 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003090 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003091 return;
3092 }
Wink Saville151eaa62013-01-31 00:30:13 +00003093 // TODO: Figure out why this optimization sometimes causes a
3094 // change in mDefaultInetCondition to be missed and the
3095 // UI to not be updated.
3096 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3097 // if (DBG) log("no change in condition - aborting");
3098 // return;
3099 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003100 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3101 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003102 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003103 return;
3104 }
Wink Saville151eaa62013-01-31 00:30:13 +00003105 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003106 sendInetConditionBroadcast(networkInfo);
3107 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003108 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003109
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003110 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003111 // this information is already available as a world read/writable jvm property
3112 // so this API change wouldn't have a benifit. It also breaks the passing
3113 // of proxy info to all the JVMs.
3114 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003115 synchronized (mProxyLock) {
3116 if (mGlobalProxy != null) return mGlobalProxy;
3117 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003118 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003119 }
3120
3121 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003122 enforceConnectivityInternalPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003123 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003124 if (proxyProperties == mGlobalProxy) return;
3125 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3126 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3127
3128 String host = "";
3129 int port = 0;
3130 String exclList = "";
3131 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3132 mGlobalProxy = new ProxyProperties(proxyProperties);
3133 host = mGlobalProxy.getHost();
3134 port = mGlobalProxy.getPort();
3135 exclList = mGlobalProxy.getExclusionList();
3136 } else {
3137 mGlobalProxy = null;
3138 }
3139 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003140 final long token = Binder.clearCallingIdentity();
3141 try {
3142 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3143 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3144 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3145 exclList);
3146 } finally {
3147 Binder.restoreCallingIdentity(token);
3148 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003149 }
3150
3151 if (mGlobalProxy == null) {
3152 proxyProperties = mDefaultProxy;
3153 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003154 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003155 }
3156
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003157 private void loadGlobalProxy() {
3158 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003159 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3160 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3161 String exclList = Settings.Global.getString(res,
3162 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003163 if (!TextUtils.isEmpty(host)) {
3164 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003165 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003166 mGlobalProxy = proxyProperties;
3167 }
3168 }
3169 }
3170
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003171 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003172 // this information is already available as a world read/writable jvm property
3173 // so this API change wouldn't have a benifit. It also breaks the passing
3174 // of proxy info to all the JVMs.
3175 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003176 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003177 return mGlobalProxy;
3178 }
3179 }
3180
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003181 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3182 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3183 proxy = null;
3184 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003185 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003186 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003187 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003188 mDefaultProxy = proxy;
3189
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003190 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003191 if (!mDefaultProxyDisabled) {
3192 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003193 }
3194 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003195 }
3196
3197 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003198 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3199 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003200 if (!TextUtils.isEmpty(proxy)) {
3201 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003202 if (data.length == 0) {
3203 return;
3204 }
3205
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003206 String proxyHost = data[0];
3207 int proxyPort = 8080;
3208 if (data.length > 1) {
3209 try {
3210 proxyPort = Integer.parseInt(data[1]);
3211 } catch (NumberFormatException e) {
3212 return;
3213 }
3214 }
3215 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3216 setGlobalProxy(p);
Andreas Huber23bff232013-05-28 15:17:37 -07003217 } else {
3218 setGlobalProxy(null);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003219 }
3220 }
3221
3222 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003223 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003224 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003225 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003226 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3227 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003228 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003229 final long ident = Binder.clearCallingIdentity();
3230 try {
3231 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3232 } finally {
3233 Binder.restoreCallingIdentity(ident);
3234 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003235 }
3236
3237 private static class SettingsObserver extends ContentObserver {
3238 private int mWhat;
3239 private Handler mHandler;
3240 SettingsObserver(Handler handler, int what) {
3241 super(handler);
3242 mHandler = handler;
3243 mWhat = what;
3244 }
3245
3246 void observe(Context context) {
3247 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003248 resolver.registerContentObserver(Settings.Global.getUriFor(
3249 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003250 }
3251
3252 @Override
3253 public void onChange(boolean selfChange) {
3254 mHandler.obtainMessage(mWhat).sendToTarget();
3255 }
3256 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003257
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003258 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003259 Slog.d(TAG, s);
3260 }
3261
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003262 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003263 Slog.e(TAG, s);
3264 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003265
repo syncf5de5572011-07-29 23:55:49 -07003266 int convertFeatureToNetworkType(int networkType, String feature) {
3267 int usedNetworkType = networkType;
3268
3269 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3270 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3271 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3272 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3273 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3274 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3275 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3276 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3277 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3278 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3279 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3280 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3281 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3282 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3283 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3284 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3285 } else {
3286 Slog.e(TAG, "Can't match any mobile netTracker!");
3287 }
3288 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3289 if (TextUtils.equals(feature, "p2p")) {
3290 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3291 } else {
3292 Slog.e(TAG, "Can't match any wifi netTracker!");
3293 }
3294 } else {
3295 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003296 }
repo syncf5de5572011-07-29 23:55:49 -07003297 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003298 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003299
3300 private static <T> T checkNotNull(T value, String message) {
3301 if (value == null) {
3302 throw new NullPointerException(message);
3303 }
3304 return value;
3305 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003306
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003307 /**
3308 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003309 * VpnBuilder and not available in ConnectivityManager. Permissions
3310 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003311 * @hide
3312 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003313 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003314 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003315 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003316 try {
3317 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003318 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003319 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003320 synchronized(mVpns) {
3321 mVpns.get(user).protect(socket,
3322 mNetTrackers[type].getLinkProperties().getInterfaceName());
3323 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003324 return true;
3325 }
3326 } catch (Exception e) {
3327 // ignore
3328 } finally {
3329 try {
3330 socket.close();
3331 } catch (Exception e) {
3332 // ignore
3333 }
3334 }
3335 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003336 }
3337
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003338 /**
3339 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003340 * and not available in ConnectivityManager. Permissions are checked
3341 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003342 * @hide
3343 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003344 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003345 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003346 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003347 int user = UserHandle.getUserId(Binder.getCallingUid());
3348 synchronized(mVpns) {
3349 return mVpns.get(user).prepare(oldPackage, newPackage);
3350 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003351 }
3352
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003353 /**
3354 * Configure a TUN interface and return its file descriptor. Parameters
3355 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003356 * and not available in ConnectivityManager. Permissions are checked in
3357 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003358 * @hide
3359 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003360 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003361 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003362 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003363 int user = UserHandle.getUserId(Binder.getCallingUid());
3364 synchronized(mVpns) {
3365 return mVpns.get(user).establish(config);
3366 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003367 }
3368
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003369 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003370 * Start legacy VPN, controlling native daemons as needed. Creates a
3371 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003372 */
3373 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003374 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003375 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003376 final LinkProperties egress = getActiveLinkProperties();
3377 if (egress == null) {
3378 throw new IllegalStateException("Missing active network connection");
3379 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003380 int user = UserHandle.getUserId(Binder.getCallingUid());
3381 synchronized(mVpns) {
3382 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3383 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003384 }
3385
3386 /**
3387 * Return the information of the ongoing legacy VPN. This method is used
3388 * by VpnSettings and not available in ConnectivityManager. Permissions
3389 * are checked in Vpn class.
3390 * @hide
3391 */
3392 @Override
3393 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003394 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003395 int user = UserHandle.getUserId(Binder.getCallingUid());
3396 synchronized(mVpns) {
3397 return mVpns.get(user).getLegacyVpnInfo();
3398 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003399 }
3400
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003401 /**
3402 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3403 * through NetworkStateTracker since it works differently. For example, it
3404 * needs to override DNS servers but never takes the default routes. It
3405 * relies on another data network, and it could keep existing connections
3406 * alive after reconnecting, switching between networks, or even resuming
3407 * from deep sleep. Calls from applications should be done synchronously
3408 * to avoid race conditions. As these are all hidden APIs, refactoring can
3409 * be done whenever a better abstraction is developed.
3410 */
3411 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003412 private VpnCallback() {
3413 }
3414
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003415 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003416 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003417 }
3418
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003419 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003420 if (dnsServers == null) {
3421 restore();
3422 return;
3423 }
3424
3425 // Convert DNS servers into addresses.
3426 List<InetAddress> addresses = new ArrayList<InetAddress>();
3427 for (String address : dnsServers) {
3428 // Double check the addresses and remove invalid ones.
3429 try {
3430 addresses.add(InetAddress.parseNumericAddress(address));
3431 } catch (Exception e) {
3432 // ignore
3433 }
3434 }
3435 if (addresses.isEmpty()) {
3436 restore();
3437 return;
3438 }
3439
3440 // Concatenate search domains into a string.
3441 StringBuilder buffer = new StringBuilder();
3442 if (searchDomains != null) {
3443 for (String domain : searchDomains) {
3444 buffer.append(domain).append(' ');
3445 }
3446 }
3447 String domains = buffer.toString().trim();
3448
3449 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003450 synchronized (mDnsLock) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003451 updateDnsLocked("VPN", iface, addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003452 mDnsOverridden = true;
3453 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003454
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003455 // Temporarily disable the default proxy (not global).
3456 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003457 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003458 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003459 sendProxyBroadcast(null);
3460 }
3461 }
3462
3463 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003464 }
3465
Chia-chi Yehcc844502011-07-14 18:01:57 -07003466 public void restore() {
3467 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003468 if (mDnsOverridden) {
3469 mDnsOverridden = false;
3470 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003471 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003472 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003473 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003474 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003475 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003476 sendProxyBroadcast(mDefaultProxy);
3477 }
3478 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003479 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003480
3481 public void protect(ParcelFileDescriptor socket) {
3482 try {
3483 final int mark = mNetd.getMarkForProtect();
3484 NetworkUtils.markSocket(socket.getFd(), mark);
3485 } catch (RemoteException e) {
3486 }
3487 }
3488
3489 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3490 for (RouteInfo route : routes) {
3491 try {
3492 mNetd.setMarkedForwardingRoute(interfaze, route);
3493 } catch (RemoteException e) {
3494 }
3495 }
3496 }
3497
3498 public void setMarkedForwarding(String interfaze) {
3499 try {
3500 mNetd.setMarkedForwarding(interfaze);
3501 } catch (RemoteException e) {
3502 }
3503 }
3504
3505 public void clearMarkedForwarding(String interfaze) {
3506 try {
3507 mNetd.clearMarkedForwarding(interfaze);
3508 } catch (RemoteException e) {
3509 }
3510 }
3511
3512 public void addUserForwarding(String interfaze, int uid) {
3513 int uidStart = uid * UserHandle.PER_USER_RANGE;
3514 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3515 addUidForwarding(interfaze, uidStart, uidEnd);
3516 }
3517
3518 public void clearUserForwarding(String interfaze, int uid) {
3519 int uidStart = uid * UserHandle.PER_USER_RANGE;
3520 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3521 clearUidForwarding(interfaze, uidStart, uidEnd);
3522 }
3523
3524 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3525 try {
3526 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3527 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3528 } catch (RemoteException e) {
3529 }
3530
3531 }
3532
3533 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3534 try {
3535 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3536 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3537 } catch (RemoteException e) {
3538 }
3539
3540 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003541 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003542
3543 @Override
3544 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003545 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3546 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3547 return false;
3548 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003549
3550 // Tear down existing lockdown if profile was removed
3551 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3552 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003553 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003554 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3555 return false;
3556 }
3557
3558 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3559 final VpnProfile profile = VpnProfile.decode(
3560 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003561 int user = UserHandle.getUserId(Binder.getCallingUid());
3562 synchronized(mVpns) {
3563 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3564 profile));
3565 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003566 } else {
3567 setLockdownTracker(null);
3568 }
3569
3570 return true;
3571 }
3572
3573 /**
3574 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3575 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3576 */
3577 private void setLockdownTracker(LockdownVpnTracker tracker) {
3578 // Shutdown any existing tracker
3579 final LockdownVpnTracker existing = mLockdownTracker;
3580 mLockdownTracker = null;
3581 if (existing != null) {
3582 existing.shutdown();
3583 }
3584
3585 try {
3586 if (tracker != null) {
3587 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003588 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003589 mLockdownTracker = tracker;
3590 mLockdownTracker.init();
3591 } else {
3592 mNetd.setFirewallEnabled(false);
3593 }
3594 } catch (RemoteException e) {
3595 // ignored; NMS lives inside system_server
3596 }
3597 }
3598
3599 private void throwIfLockdownEnabled() {
3600 if (mLockdownEnabled) {
3601 throw new IllegalStateException("Unavailable in lockdown mode");
3602 }
3603 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003604
3605 public void supplyMessenger(int networkType, Messenger messenger) {
3606 enforceConnectivityInternalPermission();
3607
3608 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3609 mNetTrackers[networkType].supplyMessenger(messenger);
3610 }
3611 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003612
3613 public int findConnectionTypeForIface(String iface) {
3614 enforceConnectivityInternalPermission();
3615
3616 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3617 for (NetworkStateTracker tracker : mNetTrackers) {
3618 if (tracker != null) {
3619 LinkProperties lp = tracker.getLinkProperties();
3620 if (lp != null && iface.equals(lp.getInterfaceName())) {
3621 return tracker.getNetworkInfo().getType();
3622 }
3623 }
3624 }
3625 return ConnectivityManager.TYPE_NONE;
3626 }
Wink Saville32506bc2013-06-29 21:10:57 -07003627
3628 /**
3629 * Have mobile data fail fast if enabled.
3630 *
3631 * @param enabled DctConstants.ENABLED/DISABLED
3632 */
3633 private void setEnableFailFastMobileData(int enabled) {
3634 int tag;
3635
3636 if (enabled == DctConstants.ENABLED) {
3637 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3638 } else {
3639 tag = mEnableFailFastMobileDataTag.get();
3640 }
3641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3642 enabled));
3643 }
3644
3645 @Override
3646 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3647 final ResultReceiver resultReceiver) {
3648 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3649 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3650 + " resultReceiver=" + resultReceiver);
3651 enforceChangePermission();
3652
3653 int timeOutMs = suggestedTimeOutMs;
3654 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3655 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3656 }
3657
Wink Savilled469c472013-07-02 10:55:14 -07003658 // Check that mobile networks are supported
3659 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3660 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3661 log("checkMobileProvisioning: X no mobile network");
3662 if (resultReceiver != null) {
3663 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3664 }
3665 return timeOutMs;
3666 }
3667
Wink Saville32506bc2013-06-29 21:10:57 -07003668 final long token = Binder.clearCallingIdentity();
3669 try {
3670 CheckMp checkMp = new CheckMp(mContext, this);
3671 CheckMp.CallBack cb = new CheckMp.CallBack() {
3672 @Override
3673 void onComplete(Integer result) {
3674 log("CheckMp.onComplete: result=" + result);
3675 if (resultReceiver != null) {
3676 log("CheckMp.onComplete: send result");
3677 resultReceiver.send(result, null);
3678 }
3679 NetworkInfo ni =
3680 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3681 switch(result) {
3682 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3683 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3684 log("CheckMp.onComplete: ignore, connected or no connection");
3685 break;
3686 }
3687 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3688 log("CheckMp.onComplete: warm sim");
3689 String url = getProvisioningUrl();
3690 if (TextUtils.isEmpty(url)) {
3691 url = mContext.getResources()
3692 .getString(R.string.mobile_redirected_provisioning_url);
3693 }
3694 if (TextUtils.isEmpty(url) == false) {
3695 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3696 setNotificationVisible(true, ni, url);
3697 } else {
3698 log("CheckMp.onComplete: warm sim (redirected), no url");
3699 }
3700 break;
3701 }
3702 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3703 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3704 String url = getProvisioningUrl();
3705 if (TextUtils.isEmpty(url) == false) {
3706 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3707 setNotificationVisible(true, ni, url);
3708 } else {
3709 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3710 }
3711 break;
3712 }
3713 default: {
3714 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3715 break;
3716 }
3717 }
3718 }
3719 };
3720 CheckMp.Params params =
3721 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3722 log("checkMobileProvisioning: params=" + params);
3723 setNotificationVisible(false, null, null);
3724 checkMp.execute(params);
3725 } finally {
3726 Binder.restoreCallingIdentity(token);
3727 log("checkMobileProvisioning: X");
3728 }
3729 return timeOutMs;
3730 }
3731
3732 static class CheckMp extends
3733 AsyncTask<CheckMp.Params, Void, Integer> {
3734 private static final String CHECKMP_TAG = "CheckMp";
3735 public static final int MAX_TIMEOUT_MS = 60000;
3736 private static final int SOCKET_TIMEOUT_MS = 5000;
3737 private Context mContext;
3738 private ConnectivityService mCs;
3739 private TelephonyManager mTm;
3740 private Params mParams;
3741
3742 /**
3743 * Parameters for AsyncTask.execute
3744 */
3745 static class Params {
3746 private String mUrl;
3747 private long mTimeOutMs;
3748 private CallBack mCb;
3749
3750 Params(String url, long timeOutMs, CallBack cb) {
3751 mUrl = url;
3752 mTimeOutMs = timeOutMs;
3753 mCb = cb;
3754 }
3755
3756 @Override
3757 public String toString() {
3758 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3759 }
3760 }
3761
3762 /**
3763 * The call back object passed in Params. onComplete will be called
3764 * on the main thread.
3765 */
3766 abstract static class CallBack {
3767 // Called on the main thread.
3768 abstract void onComplete(Integer result);
3769 }
3770
3771 public CheckMp(Context context, ConnectivityService cs) {
3772 mContext = context;
3773 mCs = cs;
3774
3775 // Setup access to TelephonyService we'll be using.
3776 mTm = (TelephonyManager) mContext.getSystemService(
3777 Context.TELEPHONY_SERVICE);
3778 }
3779
3780 /**
3781 * Get the default url to use for the test.
3782 */
3783 public String getDefaultUrl() {
3784 // See http://go/clientsdns for usage approval
3785 String server = Settings.Global.getString(mContext.getContentResolver(),
3786 Settings.Global.CAPTIVE_PORTAL_SERVER);
3787 if (server == null) {
3788 server = "clients3.google.com";
3789 }
3790 return "http://" + server + "/generate_204";
3791 }
3792
3793 /**
3794 * Detect if its possible to connect to the http url. DNS based detection techniques
3795 * do not work at all hotspots. The best way to check is to perform a request to
3796 * a known address that fetches the data we expect.
3797 */
3798 private synchronized Integer isMobileOk(Params params) {
3799 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3800 Uri orgUri = Uri.parse(params.mUrl);
3801 Random rand = new Random();
3802 mParams = params;
3803
3804 try {
3805 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3806 log("isMobileOk: not mobile capable");
3807 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3808 return result;
3809 }
3810
3811 // Enable fail fast as we'll do retries here and use a
3812 // hipri connection so the default connection stays active.
3813 log("isMobileOk: start hipri url=" + params.mUrl);
3814 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3815 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3816 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3817
3818 // Continue trying to connect until time has run out
3819 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3820 while(SystemClock.elapsedRealtime() < endTime) {
3821 try {
3822 // Wait for hipri to connect.
3823 // TODO: Don't poll and handle situation where hipri fails
3824 // because default is retrying. See b/9569540
3825 NetworkInfo.State state = mCs
3826 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3827 if (state != NetworkInfo.State.CONNECTED) {
3828 log("isMobileOk: not connected ni=" +
3829 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3830 sleep(1);
3831 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3832 continue;
3833 }
3834
3835 // Get of the addresses associated with the url host. We need to use the
3836 // address otherwise HttpURLConnection object will use the name to get
3837 // the addresses and is will try every address but that will bypass the
3838 // route to host we setup and the connection could succeed as the default
3839 // interface might be connected to the internet via wifi or other interface.
3840 InetAddress[] addresses;
3841 try {
3842 addresses = InetAddress.getAllByName(orgUri.getHost());
3843 } catch (UnknownHostException e) {
3844 log("isMobileOk: UnknownHostException");
3845 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3846 return result;
3847 }
3848 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3849
3850 // Get the type of addresses supported by this link
3851 LinkProperties lp = mCs.getLinkProperties(
3852 ConnectivityManager.TYPE_MOBILE_HIPRI);
3853 boolean linkHasIpv4 = hasIPv4Address(lp);
3854 boolean linkHasIpv6 = hasIPv6Address(lp);
3855 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3856 + " linkHasIpv6=" + linkHasIpv6);
3857
3858 // Loop through at most 3 valid addresses or all of the address or until
3859 // we run out of time
3860 int loops = Math.min(3, addresses.length);
3861 for(int validAddr=0, addrTried=0;
3862 (validAddr < loops) && (addrTried < addresses.length)
3863 && (SystemClock.elapsedRealtime() < endTime);
3864 addrTried ++) {
3865
3866 // Choose the address at random but make sure its type is supported
3867 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3868 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3869 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3870 // Valid address, so use it
3871 validAddr += 1;
3872 } else {
3873 // Invalid address so try next address
3874 continue;
3875 }
3876
3877 // Make a route to host so we check the specific interface.
3878 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3879 hostAddr.getAddress())) {
3880 // Wait a short time to be sure the route is established ??
3881 log("isMobileOk:"
3882 + " wait to establish route to hostAddr=" + hostAddr);
3883 sleep(3);
3884 } else {
3885 log("isMobileOk:"
3886 + " could not establish route to hostAddr=" + hostAddr);
3887 continue;
3888 }
3889
3890 // Rewrite the url to have numeric address to use the specific route.
3891 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3892 // is used which is useless in this case.
3893 URL newUrl = new URL(orgUri.getScheme() + "://"
3894 + hostAddr.getHostAddress() + orgUri.getPath());
3895 log("isMobileOk: newUrl=" + newUrl);
3896
3897 HttpURLConnection urlConn = null;
3898 try {
3899 // Open the connection set the request header and get the response
3900 urlConn = (HttpURLConnection) newUrl.openConnection(
3901 java.net.Proxy.NO_PROXY);
3902 urlConn.setInstanceFollowRedirects(false);
3903 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3904 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3905 urlConn.setUseCaches(false);
3906 urlConn.setAllowUserInteraction(false);
3907 urlConn.setRequestProperty("Connection", "close");
3908 int responseCode = urlConn.getResponseCode();
3909 if (responseCode == 204) {
3910 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3911 } else {
3912 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3913 }
3914 log("isMobileOk: connected responseCode=" + responseCode);
3915 urlConn.disconnect();
3916 urlConn = null;
3917 return result;
3918 } catch (Exception e) {
3919 log("isMobileOk: HttpURLConnection Exception e=" + e);
3920 if (urlConn != null) {
3921 urlConn.disconnect();
3922 urlConn = null;
3923 }
3924 }
3925 }
3926 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3927 log("isMobileOk: loops|timed out");
3928 return result;
3929 } catch (Exception e) {
3930 log("isMobileOk: Exception e=" + e);
3931 continue;
3932 }
3933 }
3934 log("isMobileOk: timed out");
3935 } finally {
3936 log("isMobileOk: F stop hipri");
3937 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3938 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3939 Phone.FEATURE_ENABLE_HIPRI);
3940 log("isMobileOk: X result=" + result);
3941 }
3942 return result;
3943 }
3944
3945 @Override
3946 protected Integer doInBackground(Params... params) {
3947 return isMobileOk(params[0]);
3948 }
3949
3950 @Override
3951 protected void onPostExecute(Integer result) {
3952 log("onPostExecute: result=" + result);
3953 if ((mParams != null) && (mParams.mCb != null)) {
3954 mParams.mCb.onComplete(result);
3955 }
3956 }
3957
3958 private String inetAddressesToString(InetAddress[] addresses) {
3959 StringBuffer sb = new StringBuffer();
3960 boolean firstTime = true;
3961 for(InetAddress addr : addresses) {
3962 if (firstTime) {
3963 firstTime = false;
3964 } else {
3965 sb.append(",");
3966 }
3967 sb.append(addr);
3968 }
3969 return sb.toString();
3970 }
3971
3972 private void printNetworkInfo() {
3973 boolean hasIccCard = mTm.hasIccCard();
3974 int simState = mTm.getSimState();
3975 log("hasIccCard=" + hasIccCard
3976 + " simState=" + simState);
3977 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3978 if (ni != null) {
3979 log("ni.length=" + ni.length);
3980 for (NetworkInfo netInfo: ni) {
3981 log("netInfo=" + netInfo.toString());
3982 }
3983 } else {
3984 log("no network info ni=null");
3985 }
3986 }
3987
3988 /**
3989 * Sleep for a few seconds then return.
3990 * @param seconds
3991 */
3992 private static void sleep(int seconds) {
3993 try {
3994 Thread.sleep(seconds * 1000);
3995 } catch (InterruptedException e) {
3996 e.printStackTrace();
3997 }
3998 }
3999
4000 public boolean hasIPv4Address(LinkProperties lp) {
4001 return lp.hasIPv4Address();
4002 }
4003
4004 // Not implemented in LinkProperties, do it here.
4005 public boolean hasIPv6Address(LinkProperties lp) {
4006 for (LinkAddress address : lp.getLinkAddresses()) {
4007 if (address.getAddress() instanceof Inet6Address) {
4008 return true;
4009 }
4010 }
4011 return false;
4012 }
4013
4014 private void log(String s) {
4015 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4016 }
4017 }
4018
4019 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4020
4021 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4022 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4023
4024 Resources r = Resources.getSystem();
4025 NotificationManager notificationManager = (NotificationManager) mContext
4026 .getSystemService(Context.NOTIFICATION_SERVICE);
4027
4028 if (visible) {
4029 CharSequence title;
4030 CharSequence details;
4031 int icon;
4032 switch (networkInfo.getType()) {
4033 case ConnectivityManager.TYPE_WIFI:
4034 log("setNotificationVisible: TYPE_WIFI");
4035 title = r.getString(R.string.wifi_available_sign_in, 0);
4036 details = r.getString(R.string.network_available_sign_in_detailed,
4037 networkInfo.getExtraInfo());
4038 icon = R.drawable.stat_notify_wifi_in_range;
4039 break;
4040 case ConnectivityManager.TYPE_MOBILE:
4041 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4042 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4043 title = r.getString(R.string.network_available_sign_in, 0);
4044 // TODO: Change this to pull from NetworkInfo once a printable
4045 // name has been added to it
4046 details = mTelephonyManager.getNetworkOperatorName();
4047 icon = R.drawable.stat_notify_rssi_in_range;
4048 break;
4049 default:
4050 log("setNotificationVisible: other type=" + networkInfo.getType());
4051 title = r.getString(R.string.network_available_sign_in, 0);
4052 details = r.getString(R.string.network_available_sign_in_detailed,
4053 networkInfo.getExtraInfo());
4054 icon = R.drawable.stat_notify_rssi_in_range;
4055 break;
4056 }
4057
4058 Notification notification = new Notification();
4059 notification.when = 0;
4060 notification.icon = icon;
4061 notification.flags = Notification.FLAG_AUTO_CANCEL;
4062 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4063 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4064 Intent.FLAG_ACTIVITY_NEW_TASK);
4065 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4066 notification.tickerText = title;
4067 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4068
4069 log("setNotificaitionVisible: notify notificaiton=" + notification);
4070 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4071 } else {
4072 log("setNotificaitionVisible: cancel");
4073 notificationManager.cancel(NOTIFICATION_ID, 1);
4074 }
4075 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4076 }
4077
4078 private String getProvisioningUrl() {
4079 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillec118d7e2013-07-10 23:00:07 -07004080 log("getProvisioningUrl: mobile_provisioning_url=" + url);
Wink Saville32506bc2013-06-29 21:10:57 -07004081
Wink Savillec118d7e2013-07-10 23:00:07 -07004082 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004083 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004084 String phoneNumber = mTelephonyManager.getLine1Number();
4085 if (TextUtils.isEmpty(phoneNumber)) {
4086 phoneNumber = "0000000000";
4087 }
Wink Saville32506bc2013-06-29 21:10:57 -07004088 url = String.format(url,
4089 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4090 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004091 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004092 }
4093
Wink Saville32506bc2013-06-29 21:10:57 -07004094 return url;
4095 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004096
4097 private void onUserStart(int userId) {
4098 synchronized(mVpns) {
4099 Vpn userVpn = mVpns.get(userId);
4100 if (userVpn != null) {
4101 loge("Starting user already has a VPN");
4102 return;
4103 }
4104 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4105 mVpns.put(userId, userVpn);
4106 userVpn.startMonitoring(mContext, mTrackerHandler);
4107 }
4108 }
4109
4110 private void onUserStop(int userId) {
4111 synchronized(mVpns) {
4112 Vpn userVpn = mVpns.get(userId);
4113 if (userVpn == null) {
4114 loge("Stopping user has no VPN");
4115 return;
4116 }
4117 mVpns.delete(userId);
4118 }
4119 }
4120
4121 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4122 @Override
4123 public void onReceive(Context context, Intent intent) {
4124 final String action = intent.getAction();
4125 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4126 if (userId == UserHandle.USER_NULL) return;
4127
4128 if (Intent.ACTION_USER_STARTING.equals(action)) {
4129 onUserStart(userId);
4130 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4131 onUserStop(userId);
4132 }
4133 }
4134 };
The Android Open Source Project28527d22009-03-03 19:31:44 -08004135}