blob: d275b607355af5c455b51cec2e0438fd004225c0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-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
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080036import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
Pierre Imai55618be2016-02-19 15:25:54 +090074import android.net.metrics.ConnectivityServiceChangeEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080076import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070077import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080090import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040093import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070099import android.util.LocalLog;
100import android.util.LocalLog.ReadOnlyLocalLog;
101import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700103import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500104import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700106import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400109import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400110import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700112import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700114import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800115import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700116import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700117import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700118import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900119import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700121import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400122import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900123import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900124import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900125import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700126import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400128import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700129import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800130import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700132import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700133import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700134import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700136
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import org.xmlpull.v1.XmlPullParser;
138import org.xmlpull.v1.XmlPullParserException;
139
140import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700142import java.io.FileNotFoundException;
143import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700144import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700146import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700147import java.net.InetAddress;
148import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700149import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700150import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700151import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700152import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700154import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900155import java.util.SortedSet;
156import java.util.TreeSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700157import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700158import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700159import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161/**
162 * @hide
163 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800164public class ConnectivityService extends IConnectivityManager.Stub
165 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900168 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700169 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jake Hamby786e71a2014-02-06 14:43:50 -0800171 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900172 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700173
Jeff Sharkey899223b2012-08-04 15:24:58 -0700174 // TODO: create better separation between radio types and network types
175
Robert Greenwalt42acef32009-08-12 16:08:25 -0700176 // how long to wait before switching back to a radio's default network
177 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
178 // system property that can override the above value
179 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
180 "android.telephony.apn-restore";
181
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900182 // How long to wait before putting up a "This network doesn't have an Internet connection,
183 // connect anyway?" dialog after the user selects a network that doesn't validate.
184 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
185
Jeremy Joslin79294842014-12-03 17:15:28 -0800186 // How long to delay to removal of a pending intent based request.
187 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
188 private final int mReleasePendingIntentDelayMs;
189
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800190 private Tethering mTethering;
191
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700192 private final PermissionMonitor mPermissionMonitor;
193
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700194 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700195
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700196 @GuardedBy("mVpns")
197 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700198
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700199 private boolean mLockdownEnabled;
200 private LockdownVpnTracker mLockdownTracker;
201
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700202 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
203 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700204 /** Currently active network rules by UID. */
205 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700206 /** Set of ifaces that are costly. */
207 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700208
Erik Klineda4bfa82015-04-30 12:58:40 +0900209 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800214 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
216 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700217 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700219 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800220 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700222
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700223 private String mCurrentTcpBufferSizes;
224
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700225 private static final int ENABLED = 1;
226 private static final int DISABLED = 0;
227
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900228 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
229 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
230
Paul Jensenb10e37f2014-11-25 12:33:08 -0500231 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Tear down networks that have no chance (e.g. even if validated) of becoming
233 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 // all networks have been rematched against all NetworkRequests.
235 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400236 // Don't reap networks. This should be passed when some networks have not yet been
237 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500238 DONT_REAP
239 };
240
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 * used internally to change our mobile data enabled flag
243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245
246 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700248 * from one net to another. Clear happens when we get a new
249 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
250 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700252 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700253
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254 /**
255 * used internally to reload global proxy settings
256 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700257 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700258
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700259 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400260 * PAC manager has received new port.
261 */
262 private static final int EVENT_PROXY_HAS_CHANGED = 16;
263
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 /**
265 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700266 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700267 */
268 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
269
Robert Greenwalt7b816022014-04-18 15:25:25 -0700270 /**
271 * used internally when registering NetworkAgents
272 * obj = Messenger
273 */
274 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
275
Robert Greenwalt9258c642014-03-26 16:47:06 -0700276 /**
277 * used to add a network request
278 * includes a NetworkRequestInfo
279 */
280 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
281
282 /**
283 * indicates a timeout period is over - check if we had a network yet or not
284 * and if not, call the timeout calback (but leave the request live until they
285 * cancel it.
286 * includes a NetworkRequestInfo
287 */
288 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
289
290 /**
291 * used to add a network listener - no request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
295
296 /**
297 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400298 * arg1 = UID of caller
299 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 */
301 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
302
Robert Greenwalta67be032014-05-16 15:49:14 -0700303 /**
304 * used internally when registering NetworkFactories
305 * obj = Messenger
306 */
307 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
308
Robert Greenwalt27711812014-06-25 16:45:57 -0700309 /**
310 * used internally to expire a wakelock when transitioning
311 * from one net to another. Expire happens when we fail to find
312 * a new network (typically after 1 minute) -
313 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
314 * a replacement network.
315 */
316 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
317
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700318 /**
319 * Used internally to indicate the system is ready.
320 */
321 private static final int EVENT_SYSTEM_READY = 25;
322
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 /**
324 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400325 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800326 */
327 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
328
329 /**
330 * used to remove a pending intent and its associated network request.
331 * arg1 = UID of caller
332 * obj = PendingIntent
333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
335
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900336 /**
337 * used to specify whether a network should be used even if unvalidated.
338 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
339 * arg2 = whether to remember this choice in the future (1 or 0)
340 * obj = network
341 */
342 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
343
344 /**
345 * used to ask the user to confirm a connection to an unvalidated network.
346 * obj = network
347 */
348 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700349
Erik Klineda4bfa82015-04-30 12:58:40 +0900350 /**
351 * used internally to (re)configure mobile data always-on settings.
352 */
353 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
354
Paul Jensen694f2b82015-06-17 14:15:39 -0400355 /**
356 * used to add a network listener with a pending intent
357 * obj = NetworkRequestInfo
358 */
359 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
360
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900361 /** Handler thread used for both of the handlers below. */
362 @VisibleForTesting
363 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700366 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700367 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700368
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800370 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400371
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700372 private PowerManager.WakeLock mNetTransitionWakeLock;
373 private String mNetTransitionWakeLockCausedBy = "";
374 private int mNetTransitionWakeLockSerialNumber;
375 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800376 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700377
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700378 // used in DBG mode to track inet condition reports
379 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
380 private ArrayList mInetLog;
381
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400383 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700384 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700385 private boolean mDefaultProxyDisabled = false;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400388 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Jason Monk602b2322013-07-03 17:04:33 -0400390 private PacManager mPacManager = null;
391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400394 private UserManager mUserManager;
395
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700396 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398
Robert Greenwalt50393202011-06-21 17:26:14 -0700399 // the set of network types that can only be enabled by system/sig apps
400 List mProtectedNetworks;
401
John Spurlockbf991a82013-06-24 14:20:23 -0400402 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700403
Wink Savilleab9321d2013-06-29 21:10:57 -0700404 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400405
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900406 private KeepaliveTracker mKeepaliveTracker;
407
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700408 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
409 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700410 private final static int MAX_NET_ID = 65535;
411 private int mNextNetId = MIN_NET_ID;
412
Robert Greenwalt34524f02014-05-18 16:22:10 -0700413 // sequence number of NetworkRequests
414 private int mNextNetworkRequestId = 1;
415
Erik Kline7523eb32015-07-09 18:24:03 +0900416 // NetworkRequest activity String log entries.
417 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
418 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900453 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900454 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900455
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700456 /**
457 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
458 * Each list holds references to all NetworkAgentInfos that are used to
459 * satisfy requests for that network type.
460 *
461 * This array is built out at startup such that an unsupported network
462 * doesn't get an ArrayList instance, making this a tristate:
463 * unsupported, supported but not active and active.
464 *
465 * The actual lists are populated when we scan the network types that
466 * are supported on this device.
467 */
468 private ArrayList<NetworkAgentInfo> mTypeLists[];
469
470 public LegacyTypeTracker() {
471 mTypeLists = (ArrayList<NetworkAgentInfo>[])
472 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
473 }
474
475 public void addSupportedType(int type) {
476 if (mTypeLists[type] != null) {
477 throw new IllegalStateException(
478 "legacy list for type " + type + "already initialized");
479 }
480 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
481 }
482
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700483 public boolean isTypeSupported(int type) {
484 return isNetworkTypeValid(type) && mTypeLists[type] != null;
485 }
486
487 public NetworkAgentInfo getNetworkForType(int type) {
488 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
489 return mTypeLists[type].get(0);
490 } else {
491 return null;
492 }
493 }
494
Robert Greenwalt8d482522015-06-24 13:23:42 -0700495 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900496 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900497 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700498 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900499 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900500 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 }
502 }
503
504 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700505 public void add(int type, NetworkAgentInfo nai) {
506 if (!isTypeSupported(type)) {
507 return; // Invalid network type.
508 }
509 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
510
511 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
512 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700513 return;
514 }
515
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900516 list.add(nai);
517
518 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900519 final boolean isDefaultNetwork = isDefaultNetwork(nai);
520 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700521 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
522 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700523 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
525
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900527 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
529 if (list == null || list.isEmpty()) {
530 return;
531 }
532
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534
535 if (!list.remove(nai)) {
536 return;
537 }
538
Robert Greenwalt8d482522015-06-24 13:23:42 -0700539 final DetailedState state = DetailedState.DISCONNECTED;
540
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700542 maybeLogBroadcast(nai, state, type, wasDefault);
543 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544 }
545
546 if (!list.isEmpty() && wasFirstNetwork) {
547 if (DBG) log("Other network available for type " + type +
548 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700550 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
551 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 }
553 }
554
555 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900556 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
557 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900559 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
561 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700562
Robert Greenwalt8d482522015-06-24 13:23:42 -0700563 // send out another legacy broadcast - currently only used for suspend/unsuspend
564 // toggle
565 public void update(NetworkAgentInfo nai) {
566 final boolean isDefault = isDefaultNetwork(nai);
567 final DetailedState state = nai.networkInfo.getDetailedState();
568 for (int type = 0; type < mTypeLists.length; type++) {
569 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700570 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700571 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700572 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 maybeLogBroadcast(nai, state, type, isDefault);
574 sendLegacyNetworkBroadcast(nai, state, type);
575 }
576 }
577 }
578
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 private String naiToString(NetworkAgentInfo nai) {
580 String name = (nai != null) ? nai.name() : "null";
581 String state = (nai.networkInfo != null) ?
582 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
583 "???/???";
584 return name + " " + state;
585 }
586
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700587 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900588 pw.println("mLegacyTypeTracker:");
589 pw.increaseIndent();
590 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700591 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900592 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700593 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900594 pw.println();
595 pw.println("Current state:");
596 pw.increaseIndent();
597 for (int type = 0; type < mTypeLists.length; type++) {
598 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
599 for (NetworkAgentInfo nai : mTypeLists[type]) {
600 pw.println(type + " " + naiToString(nai));
601 }
602 }
603 pw.decreaseIndent();
604 pw.decreaseIndent();
605 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700606 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700607 }
608 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
609
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900610 @VisibleForTesting
611 protected HandlerThread createHandlerThread() {
612 return new HandlerThread("ConnectivityServiceThread");
613 }
614
Jeff Sharkey899223b2012-08-04 15:24:58 -0700615 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700616 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800617 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800618
Erik Klineda4bfa82015-04-30 12:58:40 +0900619 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900620 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900621 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900622 mNetworkRequests.put(mDefaultRequest, defaultNRI);
623 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900624
625 mDefaultMobileDataRequest = createInternetRequestForTransport(
626 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700627
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900628 mHandlerThread = createHandlerThread();
629 mHandlerThread.start();
630 mHandler = new InternalHandler(mHandlerThread.getLooper());
631 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700632
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800633 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800634 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
635 String id = Settings.Secure.getString(context.getContentResolver(),
636 Settings.Secure.ANDROID_ID);
637 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700638 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800639 SystemProperties.set("net.hostname", name);
640 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800641 }
642
Jeremy Joslin79294842014-12-03 17:15:28 -0800643 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
644 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
645
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700646 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700647 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800648 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700650 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700651 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700652
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700653 try {
654 mPolicyManager.registerListener(mPolicyListener);
655 } catch (RemoteException e) {
656 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700657 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700658 }
659
660 final PowerManager powerManager = (PowerManager) context.getSystemService(
661 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700662 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
663 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
664 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800665 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700666
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700667 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700668
Wink Saville51f456f2013-04-23 14:26:51 -0700669 // TODO: What is the "correct" way to do determine if this is a wifi only device?
670 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
671 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700672 String[] naStrings = context.getResources().getStringArray(
673 com.android.internal.R.array.networkAttributes);
674 for (String naString : naStrings) {
675 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700676 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700677 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700678 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800679 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700680 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700681 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700682 }
Wink Saville51f456f2013-04-23 14:26:51 -0700683 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
684 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
685 n.type);
686 continue;
687 }
Wink Saville975c8482011-04-07 14:23:45 -0700688 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800689 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700690 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700691 continue;
692 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700693 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700694
Wink Saville975c8482011-04-07 14:23:45 -0700695 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 mNetworksDefined++;
697 } catch(Exception e) {
698 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700699 }
700 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700701
702 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
703 if (mNetConfigs[TYPE_VPN] == null) {
704 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
705 // don't need to add TYPE_VPN to mNetConfigs.
706 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
707 mNetworksDefined++; // used only in the log() statement below.
708 }
709
Wink Saville5e56bc52013-07-29 15:00:57 -0700710 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700711
Robert Greenwalt50393202011-06-21 17:26:14 -0700712 mProtectedNetworks = new ArrayList<Integer>();
713 int[] protectedNetworks = context.getResources().getIntArray(
714 com.android.internal.R.array.config_protectedNetworks);
715 for (int p : protectedNetworks) {
716 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
717 mProtectedNetworks.add(p);
718 } else {
719 if (DBG) loge("Ignoring protectedNetwork " + p);
720 }
721 }
722
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700723 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
724 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700725
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800726 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800727
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700728 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
729
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700730 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700731 IntentFilter intentFilter = new IntentFilter();
732 intentFilter.addAction(Intent.ACTION_USER_STARTING);
733 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700734 intentFilter.addAction(Intent.ACTION_USER_ADDED);
735 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000736 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700737 mContext.registerReceiverAsUser(
738 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900739
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700740 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700741 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700742 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700743 } catch (RemoteException e) {
744 loge("Error registering observer :" + e);
745 }
746
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700747 if (DBG) {
748 mInetLog = new ArrayList();
749 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700750
Erik Klineda4bfa82015-04-30 12:58:40 +0900751 mSettingsObserver = new SettingsObserver(mContext, mHandler);
752 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800753
John Spurlockbf991a82013-06-24 14:20:23 -0400754 mDataConnectionStats = new DataConnectionStats(mContext);
755 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400756
Jason Monkdecd2952013-10-10 14:02:51 -0400757 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700758
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400759 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900760
761 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700763
Erik Klineda4bfa82015-04-30 12:58:40 +0900764 private NetworkRequest createInternetRequestForTransport(int transportType) {
765 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900766 netCap.addCapability(NET_CAPABILITY_INTERNET);
767 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900768 if (transportType > -1) {
769 netCap.addTransportType(transportType);
770 }
771 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
772 }
773
774 private void handleMobileDataAlwaysOn() {
775 final boolean enable = (Settings.Global.getInt(
776 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
777 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
778 if (enable == isEnabled) {
779 return; // Nothing to do.
780 }
781
782 if (enable) {
783 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900784 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900785 } else {
786 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
787 }
788 }
789
790 private void registerSettingsCallbacks() {
791 // Watch for global HTTP proxy changes.
792 mSettingsObserver.observe(
793 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
794 EVENT_APPLY_GLOBAL_HTTP_PROXY);
795
796 // Watch for whether or not to keep mobile data always on.
797 mSettingsObserver.observe(
798 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
799 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
800 }
801
Robert Greenwalt34524f02014-05-18 16:22:10 -0700802 private synchronized int nextNetworkRequestId() {
803 return mNextNetworkRequestId++;
804 }
805
Paul Jensen67b0b072015-06-10 11:22:17 -0400806 @VisibleForTesting
807 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400808 synchronized (mNetworkForNetId) {
809 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
810 int netId = mNextNetId;
811 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
812 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500813 if (!mNetIdInUse.get(netId)) {
814 mNetIdInUse.put(netId, true);
815 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400816 }
817 }
818 }
819 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700820 }
821
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800822 private NetworkState getFilteredNetworkState(int networkType, int uid) {
823 NetworkInfo info = null;
824 LinkProperties lp = null;
825 NetworkCapabilities nc = null;
826 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800827 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800828
829 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
830 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
831 if (nai != null) {
832 synchronized (nai) {
833 info = new NetworkInfo(nai.networkInfo);
834 lp = new LinkProperties(nai.linkProperties);
835 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400836 // Network objects are outwardly immutable so there is no point to duplicating.
837 // Duplicating also precludes sharing socket factories and connection pools.
838 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800839 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800840 }
841 info.setType(networkType);
842 } else {
843 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
844 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
845 info.setIsAvailable(true);
846 lp = new LinkProperties();
847 nc = new NetworkCapabilities();
848 network = null;
849 }
850 info = getFilteredNetworkInfo(info, lp, uid);
851 }
852
Jeff Sharkey32566012014-12-02 18:30:14 -0800853 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400854 }
855
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800856 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
857 if (network == null) {
858 return null;
859 }
860 synchronized (mNetworkForNetId) {
861 return mNetworkForNetId.get(network.netId);
862 }
863 };
864
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900865 private Network[] getVpnUnderlyingNetworks(int uid) {
866 if (!mLockdownEnabled) {
867 int user = UserHandle.getUserId(uid);
868 synchronized (mVpns) {
869 Vpn vpn = mVpns.get(user);
870 if (vpn != null && vpn.appliesToUid(uid)) {
871 return vpn.getUnderlyingNetworks();
872 }
873 }
874 }
875 return null;
876 }
877
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878 private NetworkState getUnfilteredActiveNetworkState(int uid) {
879 NetworkInfo info = null;
880 LinkProperties lp = null;
881 NetworkCapabilities nc = null;
882 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800883 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800884
Paul Jensen85cf78e2015-06-25 13:25:07 -0400885 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800886
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900887 final Network[] networks = getVpnUnderlyingNetworks(uid);
888 if (networks != null) {
889 // getUnderlyingNetworks() returns:
890 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
891 // empty array => the VPN explicitly said "no default network".
892 // non-empty array => the VPN specified one or more default networks; we use the
893 // first one.
894 if (networks.length > 0) {
895 nai = getNetworkAgentInfoForNetwork(networks[0]);
896 } else {
897 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800898 }
899 }
900
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800901 if (nai != null) {
902 synchronized (nai) {
903 info = new NetworkInfo(nai.networkInfo);
904 lp = new LinkProperties(nai.linkProperties);
905 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400906 // Network objects are outwardly immutable so there is no point to duplicating.
907 // Duplicating also precludes sharing socket factories and connection pools.
908 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800909 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800910 }
911 }
912
Jeff Sharkey32566012014-12-02 18:30:14 -0800913 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400914 }
915
916 /**
917 * Check if UID should be blocked from using the network with the given LinkProperties.
918 */
919 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700920 final boolean networkCostly;
921 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700922
Robert Greenwalt12e67352014-05-13 21:41:06 -0700923 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700924 synchronized (mRulesLock) {
925 networkCostly = mMeteredIfaces.contains(iface);
926 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700927 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700928
Jeff Sharkeydc988062015-09-14 10:09:47 -0700929 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700931 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
932 return true;
933 } else {
934 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700935 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700936 }
937
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900938 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
939 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
940 boolean removed = false;
941 boolean added = false;
942 synchronized (mBlockedAppUids) {
943 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
944 added = true;
945 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
946 removed = true;
947 }
948 }
949 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
950 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
951 }
952
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700953 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700954 * Return a filtered {@link NetworkInfo}, potentially marked
955 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700957 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
959 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400960 // network is blocked; clone and override state
961 info = new NetworkInfo(info);
962 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700965 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900966 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700967 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700968 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700969 }
970
971 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * Return NetworkInfo for the active (i.e., connected) network interface.
973 * It is assumed that at most one network is active at a time. If more
974 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700975 * @return the info for the active network, or {@code null} if none is
976 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700980 enforceAccessPermission();
981 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900983 NetworkInfo ni = getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
984 maybeLogBlockedNetworkInfo(ni, uid);
985 return ni;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987
Paul Jensen31a94f42015-02-13 14:18:39 -0500988 @Override
989 public Network getActiveNetwork() {
990 enforceAccessPermission();
991 final int uid = Binder.getCallingUid();
992 final int user = UserHandle.getUserId(uid);
993 int vpnNetId = NETID_UNSET;
994 synchronized (mVpns) {
995 final Vpn vpn = mVpns.get(user);
996 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
997 }
998 NetworkAgentInfo nai;
999 if (vpnNetId != NETID_UNSET) {
1000 synchronized (mNetworkForNetId) {
1001 nai = mNetworkForNetId.get(vpnNetId);
1002 }
1003 if (nai != null) return nai.network;
1004 }
1005 nai = getDefaultNetwork();
1006 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1007 return nai != null ? nai.network : null;
1008 }
1009
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001010 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1011 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 final int uid = Binder.getCallingUid();
1013 NetworkState state = getUnfilteredActiveNetworkState(uid);
1014 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001015 }
1016
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001017 @Override
1018 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1019 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001022 }
1023
1024 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 public NetworkInfo getNetworkInfo(int networkType) {
1026 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001027 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001028 if (getVpnUnderlyingNetworks(uid) != null) {
1029 // A VPN is active, so we may need to return one of its underlying networks. This
1030 // information is not available in LegacyTypeTracker, so we have to get it from
1031 // getUnfilteredActiveNetworkState.
1032 NetworkState state = getUnfilteredActiveNetworkState(uid);
1033 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1034 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1035 }
1036 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 NetworkState state = getFilteredNetworkState(networkType, uid);
1038 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001041 @Override
1042 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1043 enforceAccessPermission();
1044 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001045 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1047 if (nai != null) {
1048 synchronized (nai) {
1049 info = new NetworkInfo(nai.networkInfo);
1050 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 }
1052 }
1053 return info;
1054 }
1055
1056 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 public NetworkInfo[] getAllNetworkInfo() {
1058 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001059 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001060 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1061 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062 NetworkInfo info = getNetworkInfo(networkType);
1063 if (info != null) {
1064 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001067 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001070 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001071 public Network getNetworkForType(int networkType) {
1072 enforceAccessPermission();
1073 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001074 NetworkState state = getFilteredNetworkState(networkType, uid);
1075 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1076 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001077 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001078 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001079 }
1080
1081 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 public Network[] getAllNetworks() {
1083 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001084 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001085 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001086 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001087 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001088 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001089 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001090 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 }
1092
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001093 @Override
1094 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1095 // The basic principle is: if an app's traffic could possibly go over a
1096 // network, without the app doing anything multinetwork-specific,
1097 // (hence, by "default"), then include that network's capabilities in
1098 // the array.
1099 //
1100 // In the normal case, app traffic only goes over the system's default
1101 // network connection, so that's the only network returned.
1102 //
1103 // With a VPN in force, some app traffic may go into the VPN, and thus
1104 // over whatever underlying networks the VPN specifies, while other app
1105 // traffic may go over the system default network (e.g.: a split-tunnel
1106 // VPN, or an app disallowed by the VPN), so the set of networks
1107 // returned includes the VPN's underlying networks and the system
1108 // default.
1109 enforceAccessPermission();
1110
1111 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1112
1113 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001114 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001115 if (nc != null) {
1116 result.put(nai.network, nc);
1117 }
1118
1119 if (!mLockdownEnabled) {
1120 synchronized (mVpns) {
1121 Vpn vpn = mVpns.get(userId);
1122 if (vpn != null) {
1123 Network[] networks = vpn.getUnderlyingNetworks();
1124 if (networks != null) {
1125 for (Network network : networks) {
1126 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001127 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001128 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001129 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001130 }
1131 }
1132 }
1133 }
1134 }
1135 }
1136
1137 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1138 out = result.values().toArray(out);
1139 return out;
1140 }
1141
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001142 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001143 public boolean isNetworkSupported(int networkType) {
1144 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001146 }
1147
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001148 /**
1149 * Return LinkProperties for the active (i.e., connected) default
1150 * network interface. It is assumed that at most one default network
1151 * is active at a time. If more than one is active, it is indeterminate
1152 * which will be returned.
1153 * @return the ip properties for the active network, or {@code null} if
1154 * none is active
1155 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 enforceAccessPermission();
1159 final int uid = Binder.getCallingUid();
1160 NetworkState state = getUnfilteredActiveNetworkState(uid);
1161 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001162 }
1163
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001164 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001165 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001166 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1168 if (nai != null) {
1169 synchronized (nai) {
1170 return new LinkProperties(nai.linkProperties);
1171 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001172 }
1173 return null;
1174 }
1175
Robert Greenwalt12e67352014-05-13 21:41:06 -07001176 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001177 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001178 public LinkProperties getLinkProperties(Network network) {
1179 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001181 if (nai != null) {
1182 synchronized (nai) {
1183 return new LinkProperties(nai.linkProperties);
1184 }
1185 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001186 return null;
1187 }
1188
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001189 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 if (nai != null) {
1191 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001192 if (nai.networkCapabilities != null) {
1193 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001194 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001195 }
1196 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001197 return null;
1198 }
1199
1200 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001201 public NetworkCapabilities getNetworkCapabilities(Network network) {
1202 enforceAccessPermission();
1203 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1204 }
1205
1206 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001207 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001208 // Require internal since we're handing out IMSI details
1209 enforceConnectivityInternalPermission();
1210
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001211 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001212 for (Network network : getAllNetworks()) {
1213 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1214 if (nai != null) {
1215 synchronized (nai) {
1216 final String subscriberId = (nai.networkMisc != null)
1217 ? nai.networkMisc.subscriberId : null;
1218 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1219 nai.networkCapabilities, network, subscriberId, null));
1220 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001221 }
1222 }
1223 return result.toArray(new NetworkState[result.size()]);
1224 }
1225
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001226 @Override
1227 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1228 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001229 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001230 final long token = Binder.clearCallingIdentity();
1231 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001232 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1233 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001234 try {
1235 return mPolicyManager.getNetworkQuotaInfo(state);
1236 } catch (RemoteException e) {
1237 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001238 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001239 return null;
1240 } finally {
1241 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001242 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001243 }
1244
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001245 @Override
1246 public boolean isActiveNetworkMetered() {
1247 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001248 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001249 final long token = Binder.clearCallingIdentity();
1250 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001251 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001252 } finally {
1253 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001254 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001255 }
1256
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1258 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1259 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001260 try {
1261 return mPolicyManager.isNetworkMetered(state);
1262 } catch (RemoteException e) {
1263 }
1264 }
1265 return false;
1266 }
1267
Jeff Sharkey216c1812012-08-05 14:29:23 -07001268 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1269 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001270 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001271 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001272 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001273 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001274 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001275
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 * Ensure that a network route exists to deliver traffic to the specified
1278 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001279 * @param networkType the type of the network over which traffic to the
1280 * specified host is to be routed
1281 * @param hostAddress the IP address of the host to which the route is
1282 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * @return {@code true} on success, {@code false} on failure
1284 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001285 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001287 if (mProtectedNetworks.contains(networkType)) {
1288 enforceConnectivityInternalPermission();
1289 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001290
Chad Brubakerc0234532014-02-14 13:24:29 -08001291 InetAddress addr;
1292 try {
1293 addr = InetAddress.getByAddress(hostAddress);
1294 } catch (UnknownHostException e) {
1295 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1296 return false;
1297 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001300 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 return false;
1302 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001303
1304 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1305 if (nai == null) {
1306 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1307 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1308 } else {
1309 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1310 }
1311 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001312 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001313
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001314 DetailedState netState;
1315 synchronized (nai) {
1316 netState = nai.networkInfo.getDetailedState();
1317 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001318
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001320 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001321 log("requestRouteToHostAddress on down network "
1322 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001323 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001324 }
1325 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001327
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001328 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001329 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001330 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001331 LinkProperties lp;
1332 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 synchronized (nai) {
1334 lp = nai.linkProperties;
1335 netId = nai.network.netId;
1336 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001338 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1339 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001340 } finally {
1341 Binder.restoreCallingIdentity(token);
1342 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001343 }
1344
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001345 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001346 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001347 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001348 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001349 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001350 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001351 if (bestRoute.getGateway().equals(addr)) {
1352 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001353 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001354 } else {
1355 // if we will connect to this through another route, add a direct route
1356 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001357 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 }
1359 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001360 if (DBG) log("Adding legacy route " + bestRoute +
1361 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001362 try {
1363 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1364 } catch (Exception e) {
1365 // never crash - catch them all
1366 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001367 return false;
1368 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001369 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
1371
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1373 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001374 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001375 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001377 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 }
1379
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001380 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001381 // skip update when we've already applied rules
1382 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1383 if (oldRules == uidRules) return;
1384
1385 mUidRules.put(uid, uidRules);
1386 }
1387
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001388 // TODO: notify UID when it has requested targeted updates
1389 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001390
1391 @Override
1392 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001393 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001394 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001395 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001396 }
1397
1398 synchronized (mRulesLock) {
1399 mMeteredIfaces.clear();
1400 for (String iface : meteredIfaces) {
1401 mMeteredIfaces.add(iface);
1402 }
1403 }
1404 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001405
1406 @Override
1407 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1408 // caller is NPMS, since we only register with them
1409 if (LOGD_RULES) {
1410 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1411 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001412 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001413 };
1414
Robin Lee3b3dd942015-05-12 18:14:58 +01001415 /**
1416 * Require that the caller is either in the same user or has appropriate permission to interact
1417 * across users.
1418 *
1419 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1420 */
1421 private void enforceCrossUserPermission(int userId) {
1422 if (userId == UserHandle.getCallingUserId()) {
1423 // Not a cross-user call.
1424 return;
1425 }
1426 mContext.enforceCallingOrSelfPermission(
1427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1428 "ConnectivityService");
1429 }
1430
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001431 private void enforceInternetPermission() {
1432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.INTERNET,
1434 "ConnectivityService");
1435 }
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.ACCESS_NETWORK_STATE,
1440 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442
1443 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001444 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001447 private void enforceTetherAccessPermission() {
1448 mContext.enforceCallingOrSelfPermission(
1449 android.Manifest.permission.ACCESS_NETWORK_STATE,
1450 "ConnectivityService");
1451 }
1452
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001453 private void enforceConnectivityInternalPermission() {
1454 mContext.enforceCallingOrSelfPermission(
1455 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1456 "ConnectivityService");
1457 }
1458
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001459 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001460 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001461 }
1462
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001463 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001464 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001465 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001466 }
1467
1468 private void sendInetConditionBroadcast(NetworkInfo info) {
1469 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1470 }
1471
Wink Saville628b0852011-08-04 15:01:58 -07001472 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001473 if (mLockdownTracker != null) {
1474 info = mLockdownTracker.augmentNetworkInfo(info);
1475 }
1476
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001477 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001478 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001479 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 if (info.isFailover()) {
1481 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1482 info.setFailover(false);
1483 }
1484 if (info.getReason() != null) {
1485 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1486 }
1487 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001488 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1489 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001491 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001492 return intent;
1493 }
1494
1495 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1496 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1497 }
1498
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001499 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001500 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1501 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1502 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001503 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001504 final long ident = Binder.clearCallingIdentity();
1505 try {
1506 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1507 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1508 } finally {
1509 Binder.restoreCallingIdentity(ident);
1510 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001511 }
1512
Mike Lockwood0f79b542009-08-14 14:18:49 -04001513 private void sendStickyBroadcast(Intent intent) {
1514 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001515 if (!mSystemReady) {
1516 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001517 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001518 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001519 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001520 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001521 }
1522
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001523 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001524 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001525 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001526 final NetworkInfo ni = intent.getParcelableExtra(
1527 ConnectivityManager.EXTRA_NETWORK_INFO);
1528 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1529 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001531 } else {
1532 BroadcastOptions opts = BroadcastOptions.makeBasic();
1533 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1534 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001535 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001536 final IBatteryStats bs = BatteryStatsService.getService();
1537 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001538 bs.noteConnectivityChanged(intent.getIntExtra(
1539 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1540 ni != null ? ni.getState().toString() : "?");
1541 } catch (RemoteException e) {
1542 }
1543 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001544 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001545 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001546 } finally {
1547 Binder.restoreCallingIdentity(ident);
1548 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001549 }
1550 }
1551
1552 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001553 loadGlobalProxy();
1554
Mike Lockwood0f79b542009-08-14 14:18:49 -04001555 synchronized(this) {
1556 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001557 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001558 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001559 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001560 }
1561 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001562 // load the global proxy at startup
1563 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001564
Robin Lee244ce8e2016-01-05 18:03:46 +00001565 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1566 // for user to unlock device too.
1567 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001568
Erik Klineda4bfa82015-04-30 12:58:40 +09001569 // Configure whether mobile data is always on.
1570 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1571
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001572 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001573
1574 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001578 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001579 *
1580 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001581 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001582 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001583 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1584 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001585
1586 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001588
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 if (networkAgent.networkCapabilities.hasTransport(
1590 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001591 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1592 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001593 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001594 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001595 } else if (networkAgent.networkCapabilities.hasTransport(
1596 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001597 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1598 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001599 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001600 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001601 } else {
1602 // do not track any other networks
1603 timeout = 0;
1604 }
1605
Robert Greenwalt7b816022014-04-18 15:25:25 -07001606 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001607 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001608 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001609 } catch (Exception e) {
1610 // You shall not crash!
1611 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001612 }
1613 }
1614 }
1615
1616 /**
1617 * Remove data activity tracking when network disconnects.
1618 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001619 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1620 final String iface = networkAgent.linkProperties.getInterfaceName();
1621 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001622
Robert Greenwalt7b816022014-04-18 15:25:25 -07001623 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1624 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001625 try {
1626 // the call fails silently if no idletimer setup for this interface
1627 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001628 } catch (Exception e) {
1629 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001630 }
1631 }
1632 }
1633
1634 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001635 * Reads the network specific MTU size from reources.
1636 * and set it on it's iface.
1637 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001638 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1639 final String iface = newLp.getInterfaceName();
1640 final int mtu = newLp.getMtu();
1641 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1642 if (VDBG) log("identical MTU - not setting");
1643 return;
1644 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001645
Robert Greenwalt43074032014-08-15 17:53:05 -07001646 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001647 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 return;
1649 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001650
w1997615afd812014-08-05 15:18:11 -07001651 // Cannot set MTU without interface name
1652 if (TextUtils.isEmpty(iface)) {
1653 loge("Setting MTU size with null iface.");
1654 return;
1655 }
1656
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001658 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001659 mNetd.setMtu(iface, mtu);
1660 } catch (Exception e) {
1661 Slog.e(TAG, "exception in setMtu()" + e);
1662 }
1663 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001664
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001665 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001666 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1667
1668 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001669 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001670 protected int getDefaultTcpRwnd() {
1671 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1672 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001673
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001674 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1675 if (isDefaultNetwork(nai) == false) {
1676 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001677 }
1678
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001679 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1680 String[] values = null;
1681 if (tcpBufferSizes != null) {
1682 values = tcpBufferSizes.split(",");
1683 }
1684
1685 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001686 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001687 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1688 values = tcpBufferSizes.split(",");
1689 }
1690
1691 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1692
1693 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001694 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001695
1696 final String prefix = "/sys/kernel/ipv4/tcp_";
1697 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1698 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1699 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1700 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1701 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1702 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1703 mCurrentTcpBufferSizes = tcpBufferSizes;
1704 } catch (IOException e) {
1705 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001706 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001707
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001708 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001709 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001710 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1711 if (rwndValue != 0) {
1712 SystemProperties.set(sysctlKey, rwndValue.toString());
1713 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001714 }
1715
Mattias Falk8b47b362011-08-23 14:15:13 +02001716 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001717 /*
1718 * Tell the VMs to toss their DNS caches
1719 */
1720 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1721 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001722 /*
1723 * Connectivity events can happen before boot has completed ...
1724 */
1725 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001726 final long ident = Binder.clearCallingIdentity();
1727 try {
1728 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1729 } finally {
1730 Binder.restoreCallingIdentity(ident);
1731 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001732 }
1733
Robert Greenwalt562cc542014-05-15 18:07:26 -07001734 @Override
1735 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001736 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1737 NETWORK_RESTORE_DELAY_PROP_NAME);
1738 if(restoreDefaultNetworkDelayStr != null &&
1739 restoreDefaultNetworkDelayStr.length() != 0) {
1740 try {
1741 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1742 } catch (NumberFormatException e) {
1743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001745 // if the system property isn't set, use the value for the apn type
1746 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1747
1748 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1749 (mNetConfigs[networkType] != null)) {
1750 ret = mNetConfigs[networkType].restoreTime;
1751 }
1752 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001755 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001756 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001757 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001758 }
1759 return false;
1760 }
1761
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001762 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1763 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1764 final long DIAG_TIME_MS = 5000;
1765 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1766 // Start gathering diagnostic information.
1767 netDiags.add(new NetworkDiagnostics(
1768 nai.network,
1769 new LinkProperties(nai.linkProperties), // Must be a copy.
1770 DIAG_TIME_MS));
1771 }
1772
1773 for (NetworkDiagnostics netDiag : netDiags) {
1774 pw.println();
1775 netDiag.waitForMeasurements();
1776 netDiag.dump(pw);
1777 }
1778 }
1779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001781 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1782 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001783 if (mContext.checkCallingOrSelfPermission(
1784 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001786 pw.println("Permission Denial: can't dump ConnectivityService " +
1787 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1788 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 return;
1790 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001791
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001792 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001793 dumpNetworkDiagnostics(pw);
1794 return;
1795 }
Erik Kline379747a2015-06-05 17:47:34 +09001796
Lorenzo Colittie3805462015-06-03 11:18:24 +09001797 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001798 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001799 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001800 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001801 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001802 pw.println();
1803
Paul Jensen85cf78e2015-06-25 13:25:07 -04001804 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001805 pw.print("Active default network: ");
1806 if (defaultNai == null) {
1807 pw.println("none");
1808 } else {
1809 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001811 pw.println();
1812
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001813 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001814 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001815 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1816 pw.println(nai.toString());
1817 pw.increaseIndent();
1818 pw.println("Requests:");
1819 pw.increaseIndent();
1820 for (int i = 0; i < nai.networkRequests.size(); i++) {
1821 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001822 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001823 pw.decreaseIndent();
1824 pw.println("Lingered:");
1825 pw.increaseIndent();
1826 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1827 pw.decreaseIndent();
1828 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001829 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001831 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001832
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001833 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001834 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001835 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1836 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001837 }
1838 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001839 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001840
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001841 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001842
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001843 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001844 pw.print("mNetTransitionWakeLock: currently " +
1845 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1846 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1847 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1848 } else {
1849 pw.println(", last requested never");
1850 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001851 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001852
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001853 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001854 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001855
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001856 pw.println();
1857 mKeepaliveTracker.dump(pw);
1858
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001859 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001860
Lorenzo Colittie3805462015-06-03 11:18:24 +09001861 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001862 pw.println();
1863 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001864 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001865 for(int i = 0; i < mInetLog.size(); i++) {
1866 pw.println(mInetLog.get(i));
1867 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001868 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001869 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001870
1871 if (argsContain(args, "--short") == false) {
1872 pw.println();
1873 synchronized (mValidationLogs) {
1874 pw.println("mValidationLogs (most recent first):");
1875 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1876 pw.println(p.first);
1877 pw.increaseIndent();
1878 p.second.dump(fd, pw, args);
1879 pw.decreaseIndent();
1880 }
1881 }
Erik Kline7523eb32015-07-09 18:24:03 +09001882
1883 pw.println();
1884 pw.println("mNetworkRequestInfoLogs (most recent first):");
1885 pw.increaseIndent();
1886 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1887 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 }
1890
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001891 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001892 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001893 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001894 if (officialNai != null && officialNai.equals(nai)) return true;
1895 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001896 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001897 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001898 " - " + nai);
1899 }
1900 return false;
1901 }
1902
Paul Jensenc8b9a742014-09-30 15:37:41 -04001903 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001904 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001905 }
1906
Robert Greenwalt42acef32009-08-12 16:08:25 -07001907 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001908 private class NetworkStateTrackerHandler extends Handler {
1909 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001910 super(looper);
1911 }
1912
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001913 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001915 default:
1916 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001917 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001918 handleAsyncChannelHalfConnect(msg);
1919 break;
1920 }
1921 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1922 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1923 if (nai != null) nai.asyncChannel.disconnect();
1924 break;
1925 }
1926 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1927 handleAsyncChannelDisconnected(msg);
1928 break;
1929 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001930 }
1931 return true;
1932 }
1933
1934 private void maybeHandleNetworkAgentMessage(Message msg) {
1935 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1936 if (nai == null) {
1937 if (VDBG) {
1938 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
1939 log(String.format("%s from unknown NetworkAgent", what));
1940 }
1941 return;
1942 }
1943
1944 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001945 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001946 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1947 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1948 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1949 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001950 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001951 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1952 networkCapabilities)) {
1953 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1954 + nai.networkCapabilities + " -> " + networkCapabilities);
1955 }
1956 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001957 break;
1958 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001959 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001960 if (VDBG) {
1961 log("Update of LinkProperties for " + nai.name() +
1962 "; created=" + nai.created);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001963 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001964 LinkProperties oldLp = nai.linkProperties;
1965 synchronized (nai) {
1966 nai.linkProperties = (LinkProperties)msg.obj;
1967 }
1968 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001969 break;
1970 }
1971 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001972 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001973 updateNetworkInfo(nai, info);
1974 break;
1975 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001976 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07001977 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001978 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001979 break;
1980 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001981 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001982 try {
1983 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001984 } catch (Exception e) {
1985 // Never crash!
1986 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001987 }
1988 break;
1989 }
1990 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001991 try {
1992 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001993 } catch (Exception e) {
1994 // Never crash!
1995 loge("Exception in removeVpnUidRanges: " + e);
1996 }
1997 break;
1998 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001999 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002000 if (nai.created && !nai.networkMisc.explicitlySelected) {
2001 loge("ERROR: created network explicitly selected.");
2002 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002003 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002004 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002005 break;
2006 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002007 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002008 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2009 break;
2010 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002011 }
2012 }
2013
2014 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2015 switch (msg.what) {
2016 default:
2017 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002018 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002019 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002020 if (isLiveNetworkAgent(nai, msg.what)) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002021 final boolean valid =
2022 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002023 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2024 if (valid != nai.lastValidated) {
2025 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002026 nai.lastValidated = valid;
2027 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002028 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002029 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2030 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002031 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002032 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002033 // Let the NetworkAgent know the state of its network
2034 nai.asyncChannel.sendMessage(
2035 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2036 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2037 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002038 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 break;
2040 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002041 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002043 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002044 handleLingerComplete(nai);
2045 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 break;
2047 }
Paul Jensen869868be2014-05-15 10:33:05 -04002048 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002049 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002050 final boolean visible = (msg.arg1 != 0);
2051 final NetworkAgentInfo nai;
2052 synchronized (mNetworkForNetId) {
2053 nai = mNetworkForNetId.get(netId);
2054 }
2055 // If captive portal status has changed, update capabilities.
2056 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2057 nai.lastCaptivePortalDetected = visible;
2058 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002059 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002060 }
2061 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002062 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002063 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002064 if (nai == null) {
2065 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2066 break;
2067 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002068 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002069 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2070 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002071 }
Paul Jensen869868be2014-05-15 10:33:05 -04002072 break;
2073 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002074 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 return true;
2076 }
2077
2078 @Override
2079 public void handleMessage(Message msg) {
2080 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2081 maybeHandleNetworkAgentMessage(msg);
2082 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002083 }
2084 }
2085
Paul Jensen85cf78e2015-06-25 13:25:07 -04002086 private void linger(NetworkAgentInfo nai) {
2087 nai.lingering = true;
2088 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2089 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2090 }
2091
Paul Jensen0cc17322014-11-25 15:26:53 -05002092 // Cancel any lingering so the linger timeout doesn't teardown a network.
2093 // This should be called when a network begins satisfying a NetworkRequest.
2094 // Note: depending on what state the NetworkMonitor is in (e.g.,
2095 // if it's awaiting captive portal login, or if validation failed), this
2096 // may trigger a re-evaluation of the network.
2097 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002098 nai.networkLingered.clear();
2099 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002100 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002101 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002102 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2103 }
2104
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 private void handleAsyncChannelHalfConnect(Message msg) {
2106 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002107 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002108 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2109 if (VDBG) log("NetworkFactory connected");
2110 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002111 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002112 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002113 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002114 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002115 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 }
2117 } else {
2118 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002119 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 }
2121 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2122 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2123 if (VDBG) log("NetworkAgent connected");
2124 // A network agent has requested a connection. Establish the connection.
2125 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2126 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2127 } else {
2128 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002129 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002130 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002131 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002132 synchronized (mNetworkForNetId) {
2133 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002134 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002135 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002136 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002137 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002138 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 }
2140 }
2141 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002142
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 private void handleAsyncChannelDisconnected(Message msg) {
2144 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2145 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002146 if (DBG) {
2147 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2148 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002150 // TODO - if we move the logic to the network agent (have them disconnect
2151 // because they lost all their requests or because their score isn't good)
2152 // then they would disconnect organically, report their new state and then
2153 // disconnect the channel.
2154 if (nai.networkInfo.isConnected()) {
2155 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2156 null, null);
2157 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002158 final boolean wasDefault = isDefaultNetwork(nai);
2159 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002160 mDefaultInetConditionPublished = 0;
2161 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002162 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002163 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2164 // by other networks that are already connected. Perhaps that can be done by
2165 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2166 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002167 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002168 mKeepaliveTracker.handleStopAllKeepalives(nai,
2169 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002170 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002171 mNetworkAgentInfos.remove(msg.replyTo);
2172 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002173 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002174 // Remove the NetworkAgent, but don't mark the netId as
2175 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002176 mNetworkForNetId.remove(nai.network.netId);
2177 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002178 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 for (int i = 0; i < nai.networkRequests.size(); i++) {
2180 NetworkRequest request = nai.networkRequests.valueAt(i);
2181 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2182 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2183 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002184 sendUpdatedScoreToFactories(request, 0);
2185 }
2186 }
2187 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2188 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002189 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002190 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002192 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002193 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002194 if (nai.created) {
2195 // Tell netd to clean up the configuration for this network
2196 // (routing rules, DNS, etc).
2197 // This may be slow as it requires a lot of netd shelling out to ip and
2198 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2199 // after we've rematched networks with requests which should make a potential
2200 // fallback network the default or requested a new network from the
2201 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2202 // long time.
2203 try {
2204 mNetd.removeNetwork(nai.network.netId);
2205 } catch (Exception e) {
2206 loge("Exception removing network: " + e);
2207 }
2208 }
2209 synchronized (mNetworkForNetId) {
2210 mNetIdInUse.delete(nai.network.netId);
2211 }
2212 } else {
2213 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2214 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 }
2216 }
2217
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002218 // If this method proves to be too slow then we can maintain a separate
2219 // pendingIntent => NetworkRequestInfo map.
2220 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2221 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2222 Intent intent = pendingIntent.getIntent();
2223 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2224 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2225 if (existingPendingIntent != null &&
2226 existingPendingIntent.getIntent().filterEquals(intent)) {
2227 return entry.getValue();
2228 }
2229 }
2230 return null;
2231 }
2232
2233 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2234 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2235
2236 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2237 if (existingRequest != null) { // remove the existing request.
2238 if (DBG) log("Replacing " + existingRequest.request + " with "
2239 + nri.request + " because their intents matched.");
2240 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2241 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002242 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002243 }
2244
Erik Klineda4bfa82015-04-30 12:58:40 +09002245 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002246 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002247 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002248 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002249 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002250 if (nri.request.networkCapabilities.hasSignalStrength() &&
2251 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2252 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002253 }
2254 }
2255 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002256 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002257 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002258 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002259 }
2260 }
2261
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002262 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2263 int callingUid) {
2264 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2265 if (nri != null) {
2266 handleReleaseNetworkRequest(nri.request, callingUid);
2267 }
2268 }
2269
Paul Jensen99364842014-12-09 11:43:45 -05002270 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002271 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2272 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002273 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002274 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002275 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2276 // If this Network is already the highest scoring Network for a request, or if
2277 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002278 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002279 (nai.networkRequests.get(nri.request.requestId) != null ||
2280 // Note that this catches two important cases:
2281 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2282 // is currently satisfying the request. This is desirable when
2283 // cellular ends up validating but WiFi does not.
2284 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002285 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002286 // WiFi ends up validating and out scoring cellular.
2287 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2288 nai.getCurrentScoreAsValidated())) {
2289 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002290 }
2291 }
Paul Jensene0988542015-06-25 15:30:08 -04002292 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002293 }
2294
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002295 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2296 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002297 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002298 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002299 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2300 return;
2301 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002302 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002303 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002304 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002305 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002306 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002307 // Find all networks that are satisfying this request and remove the request
2308 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002309 // TODO - it's my understanding that for a request there is only a single
2310 // network satisfying it, so this loop is wasteful
2311 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002312 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2313 if (nai.networkRequests.get(nri.request.requestId) != null) {
2314 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002315 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002316 log(" Removing from current network " + nai.name() +
2317 ", leaving " + nai.networkRequests.size() +
2318 " requests.");
2319 }
Paul Jensen99364842014-12-09 11:43:45 -05002320 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002321 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002322 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002323 } else {
2324 // suspect there should only be one pass through here
2325 // but if any were kept do the check below
2326 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002327 }
2328 }
2329 }
2330
Robert Greenwalt51481852015-01-08 14:43:31 -08002331 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2332 if (nai != null) {
2333 mNetworkForRequestId.remove(nri.request.requestId);
2334 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002335 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002336 // that a network connected to serve it, even though the network was already
2337 // connected. Now that this request has gone away, we might have to pretend
2338 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002339 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002340 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2341 boolean doRemove = true;
2342 if (wasKept) {
2343 // check if any of the remaining requests for this network are for the
2344 // same legacy type - if so, don't remove the nai
2345 for (int i = 0; i < nai.networkRequests.size(); i++) {
2346 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2347 if (otherRequest.legacyType == nri.request.legacyType &&
2348 isRequest(otherRequest)) {
2349 if (DBG) log(" still have other legacy request - leaving");
2350 doRemove = false;
2351 }
2352 }
2353 }
2354
2355 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002356 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002357 }
2358 }
2359
Robert Greenwalta67be032014-05-16 15:49:14 -07002360 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002361 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2362 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002363 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002364 } else {
2365 // listens don't have a singular affectedNetwork. Check all networks to see
2366 // if this listen request applies and remove it.
2367 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2368 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002369 if (nri.request.networkCapabilities.hasSignalStrength() &&
2370 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2371 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002372 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 }
2374 }
2375 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2376 }
2377 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002378
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002379 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2380 enforceConnectivityInternalPermission();
2381 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2382 accept ? 1 : 0, always ? 1: 0, network));
2383 }
2384
2385 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2386 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2387 " accept=" + accept + " always=" + always);
2388
2389 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2390 if (nai == null) {
2391 // Nothing to do.
2392 return;
2393 }
2394
2395 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002396 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002397 return;
2398 }
2399
2400 if (!nai.networkMisc.explicitlySelected) {
2401 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2402 }
2403
2404 if (accept != nai.networkMisc.acceptUnvalidated) {
2405 int oldScore = nai.getCurrentScore();
2406 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002407 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002408 sendUpdatedScoreToFactories(nai);
2409 }
2410
2411 if (always) {
2412 nai.asyncChannel.sendMessage(
2413 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2414 }
2415
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002416 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002417 // Tell the NetworkAgent to not automatically reconnect to the network.
2418 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2419 // Teardown the nework.
2420 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002421 }
2422
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002423 }
2424
2425 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002426 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002427 mHandler.sendMessageDelayed(
2428 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2429 PROMPT_UNVALIDATED_DELAY_MS);
2430 }
2431
2432 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002433 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002434 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2435
2436 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2437 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002438 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002439 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002440 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2441 return;
2442 }
2443
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002444 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002445 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002446 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2447 intent.setClassName("com.android.settings",
2448 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002449
2450 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2451 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2452 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002453 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002454 }
2455
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002456 private class InternalHandler extends Handler {
2457 public InternalHandler(Looper looper) {
2458 super(looper);
2459 }
2460
2461 @Override
2462 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002463 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002464 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002465 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002466 String causedBy = null;
2467 synchronized (ConnectivityService.this) {
2468 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2469 mNetTransitionWakeLock.isHeld()) {
2470 mNetTransitionWakeLock.release();
2471 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002472 } else {
2473 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002474 }
2475 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002476 if (VDBG) {
2477 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2478 log("Failed to find a new network - expiring NetTransition Wakelock");
2479 } else {
2480 log("NetTransition Wakelock (" +
2481 (causedBy == null ? "unknown" : causedBy) +
2482 " cleared because we found a replacement network");
2483 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002484 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002485 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002486 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002487 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002488 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002489 break;
2490 }
Jason Monkdecd2952013-10-10 14:02:51 -04002491 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002492 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002493 break;
2494 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002495 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002496 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2497 break;
2498 }
2499 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2500 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002501 break;
2502 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002503 case EVENT_REGISTER_NETWORK_AGENT: {
2504 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2505 break;
2506 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002507 case EVENT_REGISTER_NETWORK_REQUEST:
2508 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002509 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002510 break;
2511 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002512 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2513 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002514 handleRegisterNetworkRequestWithIntent(msg);
2515 break;
2516 }
2517 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2518 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2519 break;
2520 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002521 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002522 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002523 break;
2524 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002525 case EVENT_SET_ACCEPT_UNVALIDATED: {
2526 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2527 break;
2528 }
2529 case EVENT_PROMPT_UNVALIDATED: {
2530 handlePromptUnvalidated((Network) msg.obj);
2531 break;
2532 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002533 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2534 handleMobileDataAlwaysOn();
2535 break;
2536 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002537 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2538 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2539 mKeepaliveTracker.handleStartKeepalive(msg);
2540 break;
2541 }
2542 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2543 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2544 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2545 int slot = msg.arg1;
2546 int reason = msg.arg2;
2547 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2548 break;
2549 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002550 case EVENT_SYSTEM_READY: {
2551 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2552 nai.networkMonitor.systemReady = true;
2553 }
2554 break;
2555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
2557 }
2558 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002559
2560 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002561 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002562 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002563 if (isTetheringSupported()) {
2564 return mTethering.tether(iface);
2565 } else {
2566 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2567 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002568 }
2569
2570 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002571 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002572 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002573
2574 if (isTetheringSupported()) {
2575 return mTethering.untether(iface);
2576 } else {
2577 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2578 }
2579 }
2580
2581 // javadoc from interface
2582 public int getLastTetherError(String iface) {
2583 enforceTetherAccessPermission();
2584
2585 if (isTetheringSupported()) {
2586 return mTethering.getLastTetherError(iface);
2587 } else {
2588 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2589 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002590 }
2591
2592 // TODO - proper iface API for selection by property, inspection, etc
2593 public String[] getTetherableUsbRegexs() {
2594 enforceTetherAccessPermission();
2595 if (isTetheringSupported()) {
2596 return mTethering.getTetherableUsbRegexs();
2597 } else {
2598 return new String[0];
2599 }
2600 }
2601
2602 public String[] getTetherableWifiRegexs() {
2603 enforceTetherAccessPermission();
2604 if (isTetheringSupported()) {
2605 return mTethering.getTetherableWifiRegexs();
2606 } else {
2607 return new String[0];
2608 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002609 }
2610
Danica Chang6fdd0c62010-08-11 14:54:43 -07002611 public String[] getTetherableBluetoothRegexs() {
2612 enforceTetherAccessPermission();
2613 if (isTetheringSupported()) {
2614 return mTethering.getTetherableBluetoothRegexs();
2615 } else {
2616 return new String[0];
2617 }
2618 }
2619
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002620 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002621 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002622 if (isTetheringSupported()) {
2623 return mTethering.setUsbTethering(enable);
2624 } else {
2625 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2626 }
2627 }
2628
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002629 // TODO - move iface listing, queries, etc to new module
2630 // javadoc from interface
2631 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002632 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002633 return mTethering.getTetherableIfaces();
2634 }
2635
2636 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002637 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002638 return mTethering.getTetheredIfaces();
2639 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002640
Robert Greenwalt5a735062010-03-02 17:25:02 -08002641 public String[] getTetheringErroredIfaces() {
2642 enforceTetherAccessPermission();
2643 return mTethering.getErroredIfaces();
2644 }
2645
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002646 public String[] getTetheredDhcpRanges() {
2647 enforceConnectivityInternalPermission();
2648 return mTethering.getTetheredDhcpRanges();
2649 }
2650
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002651 // if ro.tether.denied = true we default to no tethering
2652 // gservices could set the secure setting to 1 though to enable it on a build where it
2653 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002654 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002655 public boolean isTetheringSupported() {
2656 enforceTetherAccessPermission();
2657 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002658 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002659 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2660 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002661 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2662 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002663 mTethering.getTetherableWifiRegexs().length != 0 ||
2664 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2665 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002666 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002667
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002668 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002669 public void startTethering(int type, ResultReceiver receiver,
2670 boolean showProvisioningUi) {
2671 ConnectivityManager.enforceTetherChangePermission(mContext);
2672 if (!isTetheringSupported()) {
2673 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2674 return;
2675 }
2676 mTethering.startTethering(type, receiver, showProvisioningUi);
2677 }
2678
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002679 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002680 public void stopTethering(int type) {
2681 ConnectivityManager.enforceTetherChangePermission(mContext);
2682 mTethering.stopTethering(type);
2683 }
2684
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002685 // Called when we lose the default network and have no replacement yet.
2686 // This will automatically be cleared after X seconds or a new default network
2687 // becomes CONNECTED, whichever happens first. The timer is started by the
2688 // first caller and not restarted by subsequent callers.
2689 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002690 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002691 synchronized (this) {
2692 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002693 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002694 mNetTransitionWakeLock.acquire();
2695 mNetTransitionWakeLockCausedBy = forWhom;
2696 }
2697 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002698 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002699 mNetTransitionWakeLockTimeout);
2700 return;
2701 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002702
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002703 // 100 percent is full good, 0 is full bad.
2704 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002705 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002706 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002707 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002708 }
2709
Paul Jensenbfd17b72015-04-07 12:43:13 -04002710 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002711 enforceAccessPermission();
2712 enforceInternetPermission();
2713
Paul Jensenbfd17b72015-04-07 12:43:13 -04002714 NetworkAgentInfo nai;
2715 if (network == null) {
2716 nai = getDefaultNetwork();
2717 } else {
2718 nai = getNetworkAgentInfoForNetwork(network);
2719 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002720 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2721 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2722 return;
2723 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002724 // Revalidate if the app report does not match our current validated state.
2725 if (hasConnectivity == nai.lastValidated) return;
2726 final int uid = Binder.getCallingUid();
2727 if (DBG) {
2728 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2729 ") by " + uid);
2730 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002731 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002732 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2733 // which isn't meant to work on uncreated networks.
2734 if (!nai.created) return;
2735
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002736 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002737
2738 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2739 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002740 }
2741
Paul Jensencee9b512015-05-06 07:32:40 -04002742 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002743 // this information is already available as a world read/writable jvm property
2744 // so this API change wouldn't have a benifit. It also breaks the passing
2745 // of proxy info to all the JVMs.
2746 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002747 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002748 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002749 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2750 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002751 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002752 }
2753
Paul Jensencee9b512015-05-06 07:32:40 -04002754 public ProxyInfo getProxyForNetwork(Network network) {
2755 if (network == null) return getDefaultProxy();
2756 final ProxyInfo globalProxy = getGlobalProxy();
2757 if (globalProxy != null) return globalProxy;
2758 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2759 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2760 // caller may not have.
2761 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2762 if (nai == null) return null;
2763 synchronized (nai) {
2764 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2765 if (proxyInfo == null) return null;
2766 return new ProxyInfo(proxyInfo);
2767 }
2768 }
2769
Paul Jensene0bef712014-12-10 15:12:18 -05002770 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2771 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2772 // proxy is null then there is no proxy in place).
2773 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2774 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2775 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2776 proxy = null;
2777 }
2778 return proxy;
2779 }
2780
2781 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2782 // better for determining if a new proxy broadcast is necessary:
2783 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2784 // avoid unnecessary broadcasts.
2785 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2786 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2787 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2788 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2789 // all set.
2790 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2791 a = canonicalizeProxyInfo(a);
2792 b = canonicalizeProxyInfo(b);
2793 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2794 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2795 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2796 }
2797
Jason Monk207900c2014-04-25 15:00:09 -04002798 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002799 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002800
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002801 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002802 if (proxyProperties == mGlobalProxy) return;
2803 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2804 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2805
2806 String host = "";
2807 int port = 0;
2808 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002809 String pacFileUrl = "";
2810 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002811 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002812 if (!proxyProperties.isValid()) {
2813 if (DBG)
2814 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2815 return;
2816 }
Jason Monk207900c2014-04-25 15:00:09 -04002817 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002818 host = mGlobalProxy.getHost();
2819 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002820 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002821 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002822 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002823 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002824 } else {
2825 mGlobalProxy = null;
2826 }
2827 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002828 final long token = Binder.clearCallingIdentity();
2829 try {
2830 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2831 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2832 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2833 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002834 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002835 } finally {
2836 Binder.restoreCallingIdentity(token);
2837 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002838
Jason Monkcf0f97a2014-10-02 15:39:38 -04002839 if (mGlobalProxy == null) {
2840 proxyProperties = mDefaultProxy;
2841 }
2842 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002843 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002844 }
2845
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002846 private void loadGlobalProxy() {
2847 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002848 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2849 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2850 String exclList = Settings.Global.getString(res,
2851 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002852 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2853 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002854 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002855 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002856 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002857 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002858 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002859 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002860 if (!proxyProperties.isValid()) {
2861 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2862 return;
2863 }
2864
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002865 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002866 mGlobalProxy = proxyProperties;
2867 }
2868 }
2869 }
2870
Jason Monk207900c2014-04-25 15:00:09 -04002871 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002872 // this information is already available as a world read/writable jvm property
2873 // so this API change wouldn't have a benifit. It also breaks the passing
2874 // of proxy info to all the JVMs.
2875 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002876 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002877 return mGlobalProxy;
2878 }
2879 }
2880
Jason Monk207900c2014-04-25 15:00:09 -04002881 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002882 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002883 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002884 proxy = null;
2885 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002886 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002888 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002889 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002890 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2891 return;
2892 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002893
2894 // This call could be coming from the PacManager, containing the port of the local
2895 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2896 // global (to get the correct local port), and send a broadcast.
2897 // TODO: Switch PacManager to have its own message to send back rather than
2898 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002899 if ((mGlobalProxy != null) && (proxy != null)
2900 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002901 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2902 mGlobalProxy = proxy;
2903 sendProxyBroadcast(mGlobalProxy);
2904 return;
2905 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002906 mDefaultProxy = proxy;
2907
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002908 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002909 if (!mDefaultProxyDisabled) {
2910 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002911 }
2912 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002913 }
2914
Paul Jensene0bef712014-12-10 15:12:18 -05002915 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2916 // This method gets called when any network changes proxy, but the broadcast only ever contains
2917 // the default proxy (even if it hasn't changed).
2918 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2919 // world where an app might be bound to a non-default network.
2920 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2921 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2922 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2923
2924 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2925 sendProxyBroadcast(getDefaultProxy());
2926 }
2927 }
2928
Robert Greenwalt434203a2010-10-11 16:00:27 -07002929 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002930 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2931 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 if (!TextUtils.isEmpty(proxy)) {
2933 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002934 if (data.length == 0) {
2935 return;
2936 }
2937
Robert Greenwalt434203a2010-10-11 16:00:27 -07002938 String proxyHost = data[0];
2939 int proxyPort = 8080;
2940 if (data.length > 1) {
2941 try {
2942 proxyPort = Integer.parseInt(data[1]);
2943 } catch (NumberFormatException e) {
2944 return;
2945 }
2946 }
Jason Monk207900c2014-04-25 15:00:09 -04002947 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002948 setGlobalProxy(p);
2949 }
2950 }
2951
Jason Monk207900c2014-04-25 15:00:09 -04002952 private void sendProxyBroadcast(ProxyInfo proxy) {
2953 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002954 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002955 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002956 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002957 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2958 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002959 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002960 final long ident = Binder.clearCallingIdentity();
2961 try {
2962 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2963 } finally {
2964 Binder.restoreCallingIdentity(ident);
2965 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002966 }
2967
2968 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002969 final private HashMap<Uri, Integer> mUriEventMap;
2970 final private Context mContext;
2971 final private Handler mHandler;
2972
2973 SettingsObserver(Context context, Handler handler) {
2974 super(null);
2975 mUriEventMap = new HashMap<Uri, Integer>();
2976 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002977 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002978 }
2979
Erik Klineda4bfa82015-04-30 12:58:40 +09002980 void observe(Uri uri, int what) {
2981 mUriEventMap.put(uri, what);
2982 final ContentResolver resolver = mContext.getContentResolver();
2983 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 }
2985
2986 @Override
2987 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002988 Slog.wtf(TAG, "Should never be reached.");
2989 }
2990
2991 @Override
2992 public void onChange(boolean selfChange, Uri uri) {
2993 final Integer what = mUriEventMap.get(uri);
2994 if (what != null) {
2995 mHandler.obtainMessage(what.intValue()).sendToTarget();
2996 } else {
2997 loge("No matching event to send for URI=" + uri);
2998 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 }
3000 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003001
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003002 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003003 Slog.d(TAG, s);
3004 }
3005
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003006 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003007 Slog.e(TAG, s);
3008 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003009
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003010 private static <T> T checkNotNull(T value, String message) {
3011 if (value == null) {
3012 throw new NullPointerException(message);
3013 }
3014 return value;
3015 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003016
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003017 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003018 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003019 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3020 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3021 *
3022 * @param oldPackage Package name of the application which currently controls VPN, which will
3023 * be replaced. If there is no such application, this should should either be
3024 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3025 * @param newPackage Package name of the application which should gain control of VPN, or
3026 * {@code null} to disable.
3027 * @param userId User for whom to prepare the new VPN.
3028 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003029 * @hide
3030 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003031 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003032 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3033 int userId) {
3034 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003035 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003036
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003037 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003038 Vpn vpn = mVpns.get(userId);
3039 if (vpn != null) {
3040 return vpn.prepare(oldPackage, newPackage);
3041 } else {
3042 return false;
3043 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003044 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003045 }
3046
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003047 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003048 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3049 * This method is used by system-privileged apps.
3050 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3051 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3052 *
3053 * @param packageName The package for which authorization state should change.
3054 * @param userId User for whom {@code packageName} is installed.
3055 * @param authorized {@code true} if this app should be able to start a VPN connection without
3056 * explicit user approval, {@code false} if not.
3057 *
Jeff Davidson05542602014-08-11 14:07:27 -07003058 * @hide
3059 */
3060 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003061 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3062 enforceCrossUserPermission(userId);
3063
Jeff Davidson05542602014-08-11 14:07:27 -07003064 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003065 Vpn vpn = mVpns.get(userId);
3066 if (vpn != null) {
3067 vpn.setPackageAuthorization(packageName, authorized);
3068 }
Jeff Davidson05542602014-08-11 14:07:27 -07003069 }
3070 }
3071
3072 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003073 * Configure a TUN interface and return its file descriptor. Parameters
3074 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003075 * and not available in ConnectivityManager. Permissions are checked in
3076 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003077 * @hide
3078 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003079 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003080 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003081 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003082 int user = UserHandle.getUserId(Binder.getCallingUid());
3083 synchronized(mVpns) {
3084 return mVpns.get(user).establish(config);
3085 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003086 }
3087
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003088 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003089 * Start legacy VPN, controlling native daemons as needed. Creates a
3090 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003091 */
3092 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003093 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003094 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003095 final LinkProperties egress = getActiveLinkProperties();
3096 if (egress == null) {
3097 throw new IllegalStateException("Missing active network connection");
3098 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003099 int user = UserHandle.getUserId(Binder.getCallingUid());
3100 synchronized(mVpns) {
3101 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3102 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003103 }
3104
3105 /**
3106 * Return the information of the ongoing legacy VPN. This method is used
3107 * by VpnSettings and not available in ConnectivityManager. Permissions
3108 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003109 */
3110 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003111 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3112 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003113 if (mLockdownEnabled) {
3114 return null;
3115 }
3116
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003117 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003118 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003119 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003120 }
3121
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003122 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003123 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3124 * and not available in ConnectivityManager.
3125 */
3126 @Override
3127 public VpnInfo[] getAllVpnInfo() {
3128 enforceConnectivityInternalPermission();
3129 if (mLockdownEnabled) {
3130 return new VpnInfo[0];
3131 }
3132
3133 synchronized(mVpns) {
3134 List<VpnInfo> infoList = new ArrayList<>();
3135 for (int i = 0; i < mVpns.size(); i++) {
3136 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3137 if (info != null) {
3138 infoList.add(info);
3139 }
3140 }
3141 return infoList.toArray(new VpnInfo[infoList.size()]);
3142 }
3143 }
3144
3145 /**
3146 * @return VPN information for accounting, or null if we can't retrieve all required
3147 * information, e.g primary underlying iface.
3148 */
3149 @Nullable
3150 private VpnInfo createVpnInfo(Vpn vpn) {
3151 VpnInfo info = vpn.getVpnInfo();
3152 if (info == null) {
3153 return null;
3154 }
3155 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3156 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3157 // the underlyingNetworks list.
3158 if (underlyingNetworks == null) {
3159 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3160 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3161 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3162 }
3163 } else if (underlyingNetworks.length > 0) {
3164 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3165 if (linkProperties != null) {
3166 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3167 }
3168 }
3169 return info.primaryUnderlyingIface == null ? null : info;
3170 }
3171
3172 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003173 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3174 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003175 * Permissions are checked in Vpn class.
3176 * @hide
3177 */
3178 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003179 public VpnConfig getVpnConfig(int userId) {
3180 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003181 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003182 Vpn vpn = mVpns.get(userId);
3183 if (vpn != null) {
3184 return vpn.getVpnConfig();
3185 } else {
3186 return null;
3187 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003188 }
3189 }
3190
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003191 @Override
3192 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003193 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3194 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3195 return false;
3196 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003197
3198 // Tear down existing lockdown if profile was removed
3199 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3200 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003201 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3202 final VpnProfile profile = VpnProfile.decode(
3203 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003204 if (profile == null) {
3205 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3206 setLockdownTracker(null);
3207 return true;
3208 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003209 int user = UserHandle.getUserId(Binder.getCallingUid());
3210 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003211 Vpn vpn = mVpns.get(user);
3212 if (vpn == null) {
3213 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3214 return false;
3215 }
3216 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003217 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003218 } else {
3219 setLockdownTracker(null);
3220 }
3221
3222 return true;
3223 }
3224
3225 /**
3226 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3227 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3228 */
3229 private void setLockdownTracker(LockdownVpnTracker tracker) {
3230 // Shutdown any existing tracker
3231 final LockdownVpnTracker existing = mLockdownTracker;
3232 mLockdownTracker = null;
3233 if (existing != null) {
3234 existing.shutdown();
3235 }
3236
3237 try {
3238 if (tracker != null) {
3239 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003240 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003241 mLockdownTracker = tracker;
3242 mLockdownTracker.init();
3243 } else {
3244 mNetd.setFirewallEnabled(false);
3245 }
3246 } catch (RemoteException e) {
3247 // ignored; NMS lives inside system_server
3248 }
3249 }
3250
3251 private void throwIfLockdownEnabled() {
3252 if (mLockdownEnabled) {
3253 throw new IllegalStateException("Unavailable in lockdown mode");
3254 }
3255 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003256
Robin Lee244ce8e2016-01-05 18:03:46 +00003257 /**
3258 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3259 *
3260 * @return {@code false} in case of errors; {@code true} otherwise.
3261 */
3262 private boolean updateAlwaysOnVpn(int user) {
3263 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3264 if (lockdownPackage == null) {
3265 return true;
3266 }
3267
3268 // Create an intent to start the VPN service declared in the app's manifest.
3269 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3270 serviceIntent.setPackage(lockdownPackage);
3271
3272 try {
3273 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3274 } catch (RuntimeException e) {
3275 return false;
3276 }
3277 }
3278
3279 @Override
3280 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3281 enforceConnectivityInternalPermission();
3282 enforceCrossUserPermission(userId);
3283
3284 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3285 if (LockdownVpnTracker.isEnabled()) {
3286 return false;
3287 }
3288
3289 // If the current VPN package is the same as the new one, this is a no-op
3290 final String oldPackage = getAlwaysOnVpnPackage(userId);
3291 if (TextUtils.equals(oldPackage, packageName)) {
3292 return true;
3293 }
3294
3295 synchronized (mVpns) {
3296 Vpn vpn = mVpns.get(userId);
3297 if (vpn == null) {
3298 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3299 return false;
3300 }
3301 if (!vpn.setAlwaysOnPackage(packageName)) {
3302 return false;
3303 }
3304 if (!updateAlwaysOnVpn(userId)) {
3305 vpn.setAlwaysOnPackage(null);
3306 return false;
3307 }
3308 }
3309 return true;
3310 }
3311
3312 @Override
3313 public String getAlwaysOnVpnPackage(int userId) {
3314 enforceConnectivityInternalPermission();
3315 enforceCrossUserPermission(userId);
3316
3317 synchronized (mVpns) {
3318 Vpn vpn = mVpns.get(userId);
3319 if (vpn == null) {
3320 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3321 return null;
3322 }
3323 return vpn.getAlwaysOnPackage();
3324 }
3325 }
3326
Wink Savilleab9321d2013-06-29 21:10:57 -07003327 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003328 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003329 // TODO: Remove? Any reason to trigger a provisioning check?
3330 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003331 }
3332
3333 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003334 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003335
Paul Jensen89e0f092014-09-15 15:59:36 -04003336 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003337 Intent intent = new Intent(action);
3338 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003339 // Concatenate the range of types onto the range of NetIDs.
3340 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003341 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003342 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003343 }
3344
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003345 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003346 * Show or hide network provisioning notifications.
3347 *
3348 * We use notifications for two purposes: to notify that a network requires sign in
3349 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3350 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3351 * particular network we can display the notification type that was most recently requested.
3352 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3353 * might first display NO_INTERNET, and then when the captive portal check completes, display
3354 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003355 *
3356 * @param id an identifier that uniquely identifies this notification. This must match
3357 * between show and hide calls. We use the NetID value but for legacy callers
3358 * we concatenate the range of types with the range of NetIDs.
3359 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003360 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003361 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3362 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003363 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003364 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3365 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003366 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003367 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003368
3369 Resources r = Resources.getSystem();
3370 NotificationManager notificationManager = (NotificationManager) mContext
3371 .getSystemService(Context.NOTIFICATION_SERVICE);
3372
3373 if (visible) {
3374 CharSequence title;
3375 CharSequence details;
3376 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003377 if (notifyType == NotificationType.NO_INTERNET &&
3378 networkType == ConnectivityManager.TYPE_WIFI) {
3379 title = r.getString(R.string.wifi_no_internet, 0);
3380 details = r.getString(R.string.wifi_no_internet_detailed);
3381 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3382 } else if (notifyType == NotificationType.SIGN_IN) {
3383 switch (networkType) {
3384 case ConnectivityManager.TYPE_WIFI:
3385 title = r.getString(R.string.wifi_available_sign_in, 0);
3386 details = r.getString(R.string.network_available_sign_in_detailed,
3387 extraInfo);
3388 icon = R.drawable.stat_notify_wifi_in_range;
3389 break;
3390 case ConnectivityManager.TYPE_MOBILE:
3391 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3392 title = r.getString(R.string.network_available_sign_in, 0);
3393 // TODO: Change this to pull from NetworkInfo once a printable
3394 // name has been added to it
3395 details = mTelephonyManager.getNetworkOperatorName();
3396 icon = R.drawable.stat_notify_rssi_in_range;
3397 break;
3398 default:
3399 title = r.getString(R.string.network_available_sign_in, 0);
3400 details = r.getString(R.string.network_available_sign_in_detailed,
3401 extraInfo);
3402 icon = R.drawable.stat_notify_rssi_in_range;
3403 break;
3404 }
3405 } else {
3406 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3407 + getNetworkTypeName(networkType));
3408 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003409 }
3410
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003411 Notification notification = new Notification.Builder(mContext)
3412 .setWhen(0)
3413 .setSmallIcon(icon)
3414 .setAutoCancel(true)
3415 .setTicker(title)
3416 .setColor(mContext.getColor(
3417 com.android.internal.R.color.system_notification_accent_color))
3418 .setContentTitle(title)
3419 .setContentText(details)
3420 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003421 .setLocalOnly(true)
3422 .setPriority(highPriority ?
3423 Notification.PRIORITY_HIGH :
3424 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003425 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003426 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003427 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003428
Wink Saville948282b2013-08-29 08:55:16 -07003429 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003430 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003431 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003432 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003433 npe.printStackTrace();
3434 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003435 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003436 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003437 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003438 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003439 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003440 npe.printStackTrace();
3441 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003442 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003443 }
3444
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003445 /** Location to an updatable file listing carrier provisioning urls.
3446 * An example:
3447 *
3448 * <?xml version="1.0" encoding="utf-8"?>
3449 * <provisioningUrls>
3450 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003451 * </provisioningUrls>
3452 */
3453 private static final String PROVISIONING_URL_PATH =
3454 "/data/misc/radio/provisioning_urls.xml";
3455 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003456
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003457 /** XML tag for root element. */
3458 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3459 /** XML tag for individual url */
3460 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003461 /** XML attribute for mcc */
3462 private static final String ATTR_MCC = "mcc";
3463 /** XML attribute for mnc */
3464 private static final String ATTR_MNC = "mnc";
3465
Paul Jensen434dde82015-06-11 09:43:30 -04003466 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003467 FileReader fileReader = null;
3468 XmlPullParser parser = null;
3469 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003470
3471 try {
3472 fileReader = new FileReader(mProvisioningUrlFile);
3473 parser = Xml.newPullParser();
3474 parser.setInput(fileReader);
3475 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3476
3477 while (true) {
3478 XmlUtils.nextElement(parser);
3479
3480 String element = parser.getName();
3481 if (element == null) break;
3482
Paul Jensen434dde82015-06-11 09:43:30 -04003483 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003484 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3485 try {
3486 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3487 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3488 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3489 parser.next();
3490 if (parser.getEventType() == XmlPullParser.TEXT) {
3491 return parser.getText();
3492 }
3493 }
3494 }
3495 } catch (NumberFormatException e) {
3496 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3497 }
3498 }
3499 }
3500 return null;
3501 } catch (FileNotFoundException e) {
3502 loge("Carrier Provisioning Urls file not found");
3503 } catch (XmlPullParserException e) {
3504 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3505 } catch (IOException e) {
3506 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3507 } finally {
3508 if (fileReader != null) {
3509 try {
3510 fileReader.close();
3511 } catch (IOException e) {}
3512 }
3513 }
3514 return null;
3515 }
3516
Wink Saville42d4f082013-07-20 20:31:59 -07003517 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003518 public String getMobileProvisioningUrl() {
3519 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003520 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003521 if (TextUtils.isEmpty(url)) {
3522 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003523 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003524 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003525 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003526 }
Wink Saville8cf35602013-07-10 23:00:07 -07003527 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003528 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003529 String phoneNumber = mTelephonyManager.getLine1Number();
3530 if (TextUtils.isEmpty(phoneNumber)) {
3531 phoneNumber = "0000000000";
3532 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003533 url = String.format(url,
3534 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3535 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003536 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003537 }
3538
Wink Savilleab9321d2013-06-29 21:10:57 -07003539 return url;
3540 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003541
Wink Saville948282b2013-08-29 08:55:16 -07003542 @Override
3543 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003544 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003545 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003546 final long ident = Binder.clearCallingIdentity();
3547 try {
3548 setProvNotificationVisible(visible, networkType, action);
3549 } finally {
3550 Binder.restoreCallingIdentity(ident);
3551 }
Wink Saville948282b2013-08-29 08:55:16 -07003552 }
Wink Saville7788c612013-08-29 14:57:08 -07003553
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003554 @Override
3555 public void setAirplaneMode(boolean enable) {
3556 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003557 final long ident = Binder.clearCallingIdentity();
3558 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003559 final ContentResolver cr = mContext.getContentResolver();
3560 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3561 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3562 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003563 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003564 } finally {
3565 Binder.restoreCallingIdentity(ident);
3566 }
3567 }
3568
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003569 private void onUserStart(int userId) {
3570 synchronized(mVpns) {
3571 Vpn userVpn = mVpns.get(userId);
3572 if (userVpn != null) {
3573 loge("Starting user already has a VPN");
3574 return;
3575 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003576 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003577 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003578 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003579 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3580 updateLockdownVpn();
3581 } else {
3582 updateAlwaysOnVpn(userId);
3583 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584 }
3585
3586 private void onUserStop(int userId) {
3587 synchronized(mVpns) {
3588 Vpn userVpn = mVpns.get(userId);
3589 if (userVpn == null) {
3590 loge("Stopping user has no VPN");
3591 return;
3592 }
3593 mVpns.delete(userId);
3594 }
3595 }
3596
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003597 private void onUserAdded(int userId) {
3598 synchronized(mVpns) {
3599 final int vpnsSize = mVpns.size();
3600 for (int i = 0; i < vpnsSize; i++) {
3601 Vpn vpn = mVpns.valueAt(i);
3602 vpn.onUserAdded(userId);
3603 }
3604 }
3605 }
3606
3607 private void onUserRemoved(int userId) {
3608 synchronized(mVpns) {
3609 final int vpnsSize = mVpns.size();
3610 for (int i = 0; i < vpnsSize; i++) {
3611 Vpn vpn = mVpns.valueAt(i);
3612 vpn.onUserRemoved(userId);
3613 }
3614 }
3615 }
3616
Robin Lee89e7a692016-02-29 14:38:17 +00003617 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003618 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3619 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3620 updateLockdownVpn();
3621 } else {
3622 updateAlwaysOnVpn(userId);
3623 }
3624 }
3625
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003626 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3627 @Override
3628 public void onReceive(Context context, Intent intent) {
3629 final String action = intent.getAction();
3630 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3631 if (userId == UserHandle.USER_NULL) return;
3632
3633 if (Intent.ACTION_USER_STARTING.equals(action)) {
3634 onUserStart(userId);
3635 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3636 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003637 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3638 onUserAdded(userId);
3639 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3640 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003641 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3642 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003643 }
3644 }
3645 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003646
Robert Greenwalta67be032014-05-16 15:49:14 -07003647 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3648 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003649 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3650 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003651
Robert Greenwalta67be032014-05-16 15:49:14 -07003652 private static class NetworkFactoryInfo {
3653 public final String name;
3654 public final Messenger messenger;
3655 public final AsyncChannel asyncChannel;
3656
3657 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3658 this.name = name;
3659 this.messenger = messenger;
3660 this.asyncChannel = asyncChannel;
3661 }
3662 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003663
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003664 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003665 * A NetworkRequest as registered by an application can be one of three
3666 * types:
3667 *
3668 * - "listen", for which the framework will issue callbacks about any
3669 * and all networks that match the specified NetworkCapabilities,
3670 *
3671 * - "request", capable of causing a specific network to be created
3672 * first (e.g. a telephony DUN request), the framework will issue
3673 * callbacks about the single, highest scoring current network
3674 * (if any) that matches the specified NetworkCapabilities, or
3675 *
3676 * - "track the default network", a hybrid of the two designed such
3677 * that the framework will issue callbacks for the single, highest
3678 * scoring current network (if any) that matches the capabilities of
3679 * the default Internet request (mDefaultRequest), but which cannot
3680 * cause the framework to either create or retain the existence of
3681 * any specific network.
3682 *
3683 */
3684 private static enum NetworkRequestType {
3685 LISTEN,
3686 TRACK_DEFAULT,
3687 REQUEST
3688 };
3689
3690 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003691 * Tracks info about the requester.
3692 * Also used to notice when the calling process dies so we can self-expire
3693 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003694 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003695 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003696 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003697 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003698 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003699 final int mPid;
3700 final int mUid;
3701 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003702 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003703
Erik Kline371c7b72016-03-22 17:04:20 +09003704 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003705 request = r;
3706 mPendingIntent = pi;
3707 messenger = null;
3708 mBinder = null;
3709 mPid = getCallingPid();
3710 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003711 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003712 }
3713
Erik Kline371c7b72016-03-22 17:04:20 +09003714 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003715 super();
3716 messenger = m;
3717 request = r;
3718 mBinder = binder;
3719 mPid = getCallingPid();
3720 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003721 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003722 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723
3724 try {
3725 mBinder.linkToDeath(this, 0);
3726 } catch (RemoteException e) {
3727 binderDied();
3728 }
3729 }
3730
Erik Kline371c7b72016-03-22 17:04:20 +09003731 private String typeString() {
3732 switch (mType) {
3733 case LISTEN: return "Listen";
3734 case REQUEST: return "Request";
3735 case TRACK_DEFAULT: return "Track default";
3736 default:
3737 return "unknown type";
3738 }
3739 }
3740
Robert Greenwalt9258c642014-03-26 16:47:06 -07003741 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003742 if (mBinder != null) {
3743 mBinder.unlinkToDeath(this, 0);
3744 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003745 }
3746
3747 public void binderDied() {
3748 log("ConnectivityService NetworkRequestInfo binderDied(" +
3749 request + ", " + mBinder + ")");
3750 releaseNetworkRequest(request);
3751 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003752
Erik Kline371c7b72016-03-22 17:04:20 +09003753 /**
3754 * Returns true iff. the contained NetworkRequest is one that:
3755 *
3756 * - should be associated with at most one satisfying network
3757 * at a time;
3758 *
3759 * - should cause a network to be kept up if it is the only network
3760 * which can satisfy the NetworkReqeust.
3761 *
3762 * For full detail of how isRequest() is used for pairing Networks with
3763 * NetworkRequests read rematchNetworkAndRequests().
3764 *
3765 * TODO: Rename to something more properly descriptive.
3766 */
3767 public boolean isRequest() {
3768 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3769 (mType == NetworkRequestType.REQUEST);
3770 }
3771
Robert Greenwalta67be032014-05-16 15:49:14 -07003772 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003773 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003774 " from uid/pid:" + mUid + "/" + mPid +
3775 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003776 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003777 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003778 }
3779
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003780 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3781 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3782 if (badCapability != null) {
3783 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003784 }
3785 }
3786
Erik Kline9d598e12015-07-13 16:37:51 +09003787 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003788 final SortedSet<Integer> thresholds = new TreeSet();
3789 synchronized (nai) {
3790 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3791 if (nri.request.networkCapabilities.hasSignalStrength() &&
3792 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3793 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3794 }
3795 }
3796 }
Erik Kline9d598e12015-07-13 16:37:51 +09003797 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003798 }
3799
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003800 private void updateSignalStrengthThresholds(
3801 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3802 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003803 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003804 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3805
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003806 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003807 String detail;
3808 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3809 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3810 } else {
3811 detail = reason;
3812 }
3813 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3814 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3815 }
3816
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003817 nai.asyncChannel.sendMessage(
3818 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003819 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003820 }
3821
Robert Greenwalt9258c642014-03-26 16:47:06 -07003822 @Override
3823 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003824 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003825 final NetworkRequestType type = (networkCapabilities == null)
3826 ? NetworkRequestType.TRACK_DEFAULT
3827 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003828 // If the requested networkCapabilities is null, take them instead from
3829 // the default network request. This allows callers to keep track of
3830 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003831 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003832 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3833 enforceAccessPermission();
3834 } else {
3835 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3836 enforceNetworkRequestPermissions(networkCapabilities);
3837 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003838 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003839 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003840
Robert Greenwalt6078b502014-06-11 16:05:07 -07003841 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003842 throw new IllegalArgumentException("Bad timeout specified");
3843 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003844
Etan Cohenddb9ef02015-11-18 10:56:15 -08003845 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3846 .equals(networkCapabilities.getNetworkSpecifier())) {
3847 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3848 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3849 }
3850
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003851 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3852 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003853 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003854 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003855
3856 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003857 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003858 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003859 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003860 }
3861 return networkRequest;
3862 }
3863
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003864 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003865 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003866 enforceConnectivityInternalPermission();
3867 } else {
3868 enforceChangePermission();
3869 }
3870 }
3871
fenglub15e72b2015-03-20 11:29:56 -07003872 @Override
fengludb571472015-04-21 17:12:05 -07003873 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003874 enforceAccessPermission();
3875 NetworkAgentInfo nai = null;
3876 if (network == null) {
3877 return false;
3878 }
3879 synchronized (mNetworkForNetId) {
3880 nai = mNetworkForNetId.get(network.netId);
3881 }
3882 if (nai != null) {
3883 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3884 return true;
3885 }
3886 return false;
3887 }
3888
3889
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003890 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3891 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003892 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003893 final int uidRules;
3894 final int uid = Binder.getCallingUid();
3895 synchronized(mRulesLock) {
3896 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3897 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003898 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003899 // we could silently fail or we can filter the available nets to only give
3900 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003901 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003902 }
3903 }
3904 }
3905
Robert Greenwalt9258c642014-03-26 16:47:06 -07003906 @Override
3907 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3908 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003909 checkNotNull(operation, "PendingIntent cannot be null.");
3910 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3911 enforceNetworkRequestPermissions(networkCapabilities);
3912 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003913 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914
3915 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3916 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003918 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003919 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003920 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3921 nri));
3922 return networkRequest;
3923 }
3924
Jeremy Joslin79294842014-12-03 17:15:28 -08003925 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3926 mHandler.sendMessageDelayed(
3927 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3928 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3929 }
3930
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003931 @Override
3932 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003933 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003934 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3935 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003936 }
3937
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003938 // In order to implement the compatibility measure for pre-M apps that call
3939 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3940 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3941 // This ensures it has permission to do so.
3942 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3943 if (nc == null) {
3944 return false;
3945 }
3946 int[] transportTypes = nc.getTransportTypes();
3947 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3948 return false;
3949 }
3950 try {
3951 mContext.enforceCallingOrSelfPermission(
3952 android.Manifest.permission.ACCESS_WIFI_STATE,
3953 "ConnectivityService");
3954 } catch (SecurityException e) {
3955 return false;
3956 }
3957 return true;
3958 }
3959
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960 @Override
3961 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3962 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003963 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3964 enforceAccessPermission();
3965 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003966
Erik Kline7523eb32015-07-09 18:24:03 +09003967 NetworkRequest networkRequest = new NetworkRequest(
3968 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003969 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09003970 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003971 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003972
3973 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3974 return networkRequest;
3975 }
3976
3977 @Override
3978 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3979 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003980 checkNotNull(operation, "PendingIntent cannot be null.");
3981 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3982 enforceAccessPermission();
3983 }
3984
Erik Kline7523eb32015-07-09 18:24:03 +09003985 NetworkRequest networkRequest = new NetworkRequest(
3986 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003987 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003988 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003989 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003990
3991 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003992 }
3993
3994 @Override
3995 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003996 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3997 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003998 }
3999
4000 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004001 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004002 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004003 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4004 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004005 }
4006
Robert Greenwalta67be032014-05-16 15:49:14 -07004007 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004008 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004009 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4010 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4011 }
4012
4013 @Override
4014 public void unregisterNetworkFactory(Messenger messenger) {
4015 enforceConnectivityInternalPermission();
4016 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4017 }
4018
4019 private void handleUnregisterNetworkFactory(Messenger messenger) {
4020 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4021 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004022 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004023 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004025 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004026 }
4027
Robert Greenwalt7b816022014-04-18 15:25:25 -07004028 /**
4029 * NetworkAgentInfo supporting a request by requestId.
4030 * These have already been vetted (their Capabilities satisfy the request)
4031 * and the are the highest scored network available.
4032 * the are keyed off the Requests requestId.
4033 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004034 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004035 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4036 new SparseArray<NetworkAgentInfo>();
4037
Paul Jensen31a94f42015-02-13 14:18:39 -05004038 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4039 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004040 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4041 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004042 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4043 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4044 // there may not be a strict 1:1 correlation between the two.
4045 @GuardedBy("mNetworkForNetId")
4046 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047
Robert Greenwalt7b816022014-04-18 15:25:25 -07004048 // NetworkAgentInfo keyed off its connecting messenger
4049 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004050 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004051 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4052 new HashMap<Messenger, NetworkAgentInfo>();
4053
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004054 @GuardedBy("mBlockedAppUids")
4055 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4056
Paul Jensen2c311d62014-11-17 12:34:51 -05004057 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004058 private final NetworkRequest mDefaultRequest;
4059
Erik Klineda4bfa82015-04-30 12:58:40 +09004060 // Request used to optionally keep mobile data active even when higher
4061 // priority networks like Wi-Fi are active.
4062 private final NetworkRequest mDefaultMobileDataRequest;
4063
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004064 private NetworkAgentInfo getDefaultNetwork() {
4065 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4066 }
4067
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004068 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004069 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004070 }
4071
Paul Jensen31a94f42015-02-13 14:18:39 -05004072 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004073 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004074 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004075 enforceConnectivityInternalPermission();
4076
Paul Jensen2c311d62014-11-17 12:34:51 -05004077 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4078 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004079 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004080 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4081 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004082 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004083 synchronized (this) {
4084 nai.networkMonitor.systemReady = mSystemReady;
4085 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004086 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004087 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004089 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004090 }
4091
4092 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4093 if (VDBG) log("Got NetworkAgent Messenger");
4094 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004095 synchronized (mNetworkForNetId) {
4096 mNetworkForNetId.put(na.network.netId, na);
4097 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004098 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4099 NetworkInfo networkInfo = na.networkInfo;
4100 na.networkInfo = null;
4101 updateNetworkInfo(na, networkInfo);
4102 }
4103
4104 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4105 LinkProperties newLp = networkAgent.linkProperties;
4106 int netId = networkAgent.network.netId;
4107
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004108 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4109 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004110 if (networkAgent.clatd != null) {
4111 networkAgent.clatd.fixupLinkProperties(oldLp);
4112 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004113
Paul Jensen992f2522014-04-28 10:33:11 -04004114 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004115 updateMtu(newLp, oldLp);
4116 // TODO - figure out what to do for clat
4117// for (LinkProperties lp : newLp.getStackedLinks()) {
4118// updateMtu(lp, null);
4119// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004120 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004121
Erik Kline94887872016-04-05 13:30:49 +09004122 updateRoutes(newLp, oldLp, netId);
4123 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004124
Paul Jensen3b759822014-05-13 11:44:01 -04004125 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004126 if (isDefaultNetwork(networkAgent)) {
4127 handleApplyDefaultProxy(newLp.getHttpProxy());
4128 } else {
4129 updateProxy(newLp, oldLp, networkAgent);
4130 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004131 // TODO - move this check to cover the whole function
4132 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004133 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004134 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4135 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004136
4137 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004138 }
4139
Lorenzo Colitti95439462014-10-09 13:44:48 +09004140 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4141 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4142 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004143
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004144 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004145 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4146 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004147 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004148 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004150 }
Paul Jensen992f2522014-04-28 10:33:11 -04004151
4152 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4153 CompareResult<String> interfaceDiff = new CompareResult<String>();
4154 if (oldLp != null) {
4155 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4156 } else if (newLp != null) {
4157 interfaceDiff.added = newLp.getAllInterfaceNames();
4158 }
4159 for (String iface : interfaceDiff.added) {
4160 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004161 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004162 mNetd.addInterfaceToNetwork(iface, netId);
4163 } catch (Exception e) {
4164 loge("Exception adding interface: " + e);
4165 }
4166 }
4167 for (String iface : interfaceDiff.removed) {
4168 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004169 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004170 mNetd.removeInterfaceFromNetwork(iface, netId);
4171 } catch (Exception e) {
4172 loge("Exception removing interface: " + e);
4173 }
4174 }
4175 }
4176
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004177 /**
4178 * Have netd update routes from oldLp to newLp.
4179 * @return true if routes changed between oldLp and newLp
4180 */
4181 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004182 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4183 if (oldLp != null) {
4184 routeDiff = oldLp.compareAllRoutes(newLp);
4185 } else if (newLp != null) {
4186 routeDiff.added = newLp.getAllRoutes();
4187 }
4188
4189 // add routes before removing old in case it helps with continuous connectivity
4190
4191 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4192 for (RouteInfo route : routeDiff.added) {
4193 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004194 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004195 try {
4196 mNetd.addRoute(netId, route);
4197 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004198 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4199 loge("Exception in addRoute for non-gateway: " + e);
4200 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004201 }
4202 }
4203 for (RouteInfo route : routeDiff.added) {
4204 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004205 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004206 try {
4207 mNetd.addRoute(netId, route);
4208 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004209 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4210 loge("Exception in addRoute for gateway: " + e);
4211 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 }
4213 }
4214
4215 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004216 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004217 try {
4218 mNetd.removeRoute(netId, route);
4219 } catch (Exception e) {
4220 loge("Exception in removeRoute: " + e);
4221 }
4222 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004223 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 }
Erik Kline41368502015-06-17 13:19:54 +09004225
Erik Kline94887872016-04-05 13:30:49 +09004226 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4227 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4228 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 }
Erik Kline94887872016-04-05 13:30:49 +09004230
4231 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004232 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004233 try {
4234 mNetd.setDnsServersForNetwork(
4235 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4236 } catch (Exception e) {
4237 loge("Exception in setDnsServersForNetwork: " + e);
4238 }
4239 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4240 if (defaultNai != null && defaultNai.network.netId == netId) {
4241 setDefaultDnsSystemProperties(dnses);
4242 }
4243 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004244 }
4245
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004246 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4247 int last = 0;
4248 for (InetAddress dns : dnses) {
4249 ++last;
4250 String key = "net.dns" + last;
4251 String value = dns.getHostAddress();
4252 SystemProperties.set(key, value);
4253 }
4254 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4255 String key = "net.dns" + i;
4256 SystemProperties.set(key, "");
4257 }
4258 mNumDnsEntries = last;
4259 }
4260
Paul Jensen3d194ea2015-06-16 14:27:36 -04004261 /**
4262 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4263 * augmented with any stateful capabilities implied from {@code networkAgent}
4264 * (e.g., validated status and captive portal status).
4265 *
Paul Jensene0988542015-06-25 15:30:08 -04004266 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004267 * @param networkCapabilities the new network capabilities.
4268 */
Paul Jensene0988542015-06-25 15:30:08 -04004269 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004270 // Don't modify caller's NetworkCapabilities.
4271 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004272 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004273 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4274 } else {
4275 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4276 }
Paul Jensene0988542015-06-25 15:30:08 -04004277 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004278 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4279 } else {
4280 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4281 }
Paul Jensene0988542015-06-25 15:30:08 -04004282 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4283 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004284 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4285 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4286 try {
4287 mNetd.setNetworkPermission(nai.network.netId,
4288 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4289 null : NetworkManagementService.PERMISSION_SYSTEM);
4290 } catch (RemoteException e) {
4291 loge("Exception in setNetworkPermission: " + e);
4292 }
4293 }
Paul Jensene0988542015-06-25 15:30:08 -04004294 synchronized (nai) {
4295 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004296 }
Paul Jensene0988542015-06-25 15:30:08 -04004297 rematchAllNetworksAndRequests(nai, oldScore);
4298 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004299 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004300 }
4301
Paul Jensenc8b9a742014-09-30 15:37:41 -04004302 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4303 for (int i = 0; i < nai.networkRequests.size(); i++) {
4304 NetworkRequest nr = nai.networkRequests.valueAt(i);
4305 // Don't send listening requests to factories. b/17393458
4306 if (!isRequest(nr)) continue;
4307 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4308 }
4309 }
4310
Robert Greenwalt7b816022014-04-18 15:25:25 -07004311 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4312 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004313 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004314 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4315 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004316 }
4317 }
4318
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004319 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4320 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004321 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004322 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004323 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4324 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004325 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004326 sendIntent(nri.mPendingIntent, intent);
4327 }
4328 // else not handled
4329 }
4330
4331 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4332 mPendingIntentWakeLock.acquire();
4333 try {
4334 if (DBG) log("Sending " + pendingIntent);
4335 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4336 } catch (PendingIntent.CanceledException e) {
4337 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4338 mPendingIntentWakeLock.release();
4339 releasePendingNetworkRequest(pendingIntent);
4340 }
4341 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4342 }
4343
4344 @Override
4345 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4346 String resultData, Bundle resultExtras) {
4347 if (DBG) log("Finished sending " + pendingIntent);
4348 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004349 // Release with a delay so the receiving client has an opportunity to put in its
4350 // own request.
4351 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004352 }
4353
Robert Greenwalt9258c642014-03-26 16:47:06 -07004354 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004356 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004357 Bundle bundle = new Bundle();
4358 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4359 new NetworkRequest(nri.request));
4360 Message msg = Message.obtain();
4361 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4362 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4363 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4364 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004365 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004366 case ConnectivityManager.CALLBACK_LOSING: {
4367 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4368 break;
4369 }
4370 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4371 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4372 new NetworkCapabilities(networkAgent.networkCapabilities));
4373 break;
4374 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004375 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004376 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4377 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004378 break;
4379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004381 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004382 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004383 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004384 if (VDBG) {
4385 log("sending notification " + notifyTypeToName(notificationType) +
4386 " for " + nri.request);
4387 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004388 nri.messenger.send(msg);
4389 } catch (RemoteException e) {
4390 // may occur naturally in the race of binder death.
4391 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 }
4394
Paul Jensenc8b9a742014-09-30 15:37:41 -04004395 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4396 for (int i = 0; i < nai.networkRequests.size(); i++) {
4397 NetworkRequest nr = nai.networkRequests.valueAt(i);
4398 // Ignore listening requests.
4399 if (!isRequest(nr)) continue;
4400 loge("Dead network still had at least " + nr);
4401 break;
4402 }
4403 nai.asyncChannel.disconnect();
4404 }
4405
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4407 if (oldNetwork == null) {
4408 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4409 return;
4410 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004411 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4412 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004413 }
4414
Paul Jensen27b02b72014-07-14 12:03:33 -04004415 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004416 if (DBG) log("Switching to new default network: " + newNetwork);
Pierre Imai55618be2016-02-19 15:25:54 +09004417 ConnectivityServiceChangeEvent.logEvent(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04004418 setupDataActivityTracking(newNetwork);
4419 try {
4420 mNetd.setDefaultNetId(newNetwork.network.netId);
4421 } catch (Exception e) {
4422 loge("Exception setting default network :" + e);
4423 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004424 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004425 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004426 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004427 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004428 }
4429
Paul Jensen2161a8e2014-09-11 11:00:39 -04004430 // Handles a network appearing or improving its score.
4431 //
4432 // - Evaluates all current NetworkRequests that can be
4433 // satisfied by newNetwork, and reassigns to newNetwork
4434 // any such requests for which newNetwork is the best.
4435 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004436 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004437 // needed. A network is needed if it is the best network for
4438 // one or more NetworkRequests, or if it is a VPN.
4439 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004440 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004441 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004442 //
4443 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4444 // networks that have no chance (i.e. even if validated)
4445 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004446 //
4447 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4448 // it does not remove NetworkRequests that other Networks could better satisfy.
4449 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4450 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4451 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004452 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004453 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004454 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4455 // performed to tear down unvalidated networks that have no chance (i.e. even if
4456 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004457 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004458 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004459 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004460 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004461 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004462 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004463 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004464 // Find and migrate to this Network any NetworkRequests for
4465 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004466 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004467 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004468 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004469 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004470 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4471 final boolean satisfies = newNetwork.satisfies(nri.request);
4472 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004473 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004474 log("Network " + newNetwork.name() + " was already satisfying" +
4475 " request " + nri.request.requestId + ". No change.");
4476 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004477 keep = true;
4478 continue;
4479 }
4480
4481 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004482 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004483 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004484 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004485 // This is not a request, it's a callback listener.
4486 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004487 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004488 continue;
4489 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004490
Robert Greenwalt7b816022014-04-18 15:25:25 -07004491 // next check if it's better than any current network we're using for
4492 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004493 if (VDBG) {
4494 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004495 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4496 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 }
4498 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004499 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004500 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004501 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004502 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004503 currentNetwork.networkRequests.remove(nri.request.requestId);
4504 currentNetwork.networkLingered.add(nri.request);
4505 affectedNetworks.add(currentNetwork);
4506 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004507 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004508 }
Paul Jensen573a0352015-01-08 10:49:34 -05004509 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004510 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004511 if (!newNetwork.addRequest(nri.request)) {
4512 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4513 }
4514 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004516 // Tell NetworkFactories about the new score, so they can stop
4517 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004518 // TODO - this could get expensive if we have alot of requests for this
4519 // network. Think about if there is a way to reduce this. Push
4520 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004521 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004522 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004524 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 }
4526 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004527 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4528 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4529 // mark it as no longer satisfying "nri". Because networks are processed by
4530 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4531 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4532 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4533 // This means this code doesn't have to handle the case where "currentNetwork" no
4534 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4535 if (DBG) {
4536 log("Network " + newNetwork.name() + " stopped satisfying" +
4537 " request " + nri.request.requestId);
4538 }
4539 newNetwork.networkRequests.remove(nri.request.requestId);
4540 if (currentNetwork == newNetwork) {
4541 mNetworkForRequestId.remove(nri.request.requestId);
4542 sendUpdatedScoreToFactories(nri.request, 0);
4543 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004544 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004545 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4546 newNetwork.name() +
4547 " without updating mNetworkForRequestId or factories!");
4548 }
4549 }
4550 // TODO: technically, sending CALLBACK_LOST here is
4551 // incorrect if nri is a request (not a listen) and there
4552 // is a replacement network currently connected that can
4553 // satisfy it. However, the only capability that can both
4554 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4555 // so this code is only incorrect for a network that loses
4556 // the TRUSTED capability, which is a rare case.
4557 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 }
4559 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004560 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004561 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004562 if (nai.lingering) {
4563 // Already lingered. Nothing to do. This can only happen if "nai" is in
4564 // "affectedNetworks" twice. The reasoning being that to get added to
4565 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4566 // (i.e. not lingered) so it could have only been lingered by this loop.
4567 // unneeded(nai) will be false and we'll call unlinger() below which would
4568 // be bad, so handle it here.
4569 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004570 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004571 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004572 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004573 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004574 }
4575 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004576 if (isNewDefault) {
4577 // Notify system services that this network is up.
4578 makeDefault(newNetwork);
4579 synchronized (ConnectivityService.this) {
4580 // have a new default network, release the transition wakelock in
4581 // a second if it's held. The second pause is to allow apps
4582 // to reconnect over the new network
4583 if (mNetTransitionWakeLock.isHeld()) {
4584 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4585 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4586 mNetTransitionWakeLockSerialNumber, 0),
4587 1000);
4588 }
4589 }
4590 }
4591
4592 // do this after the default net is switched, but
4593 // before LegacyTypeTracker sends legacy broadcasts
4594 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4595
4596 if (isNewDefault) {
4597 // Maintain the illusion: since the legacy API only
4598 // understands one network at a time, we must pretend
4599 // that the current default network disconnected before
4600 // the new one connected.
4601 if (oldDefaultNetwork != null) {
4602 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4603 oldDefaultNetwork, true);
4604 }
4605 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4606 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4607 notifyLockdownVpn(newNetwork);
4608 }
4609
Robert Greenwalt7b816022014-04-18 15:25:25 -07004610 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004611 // Notify battery stats service about this network, both the normal
4612 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004613 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004614 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004615 final IBatteryStats bs = BatteryStatsService.getService();
4616 final int type = newNetwork.networkInfo.getType();
4617
4618 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4619 bs.noteNetworkInterfaceType(baseIface, type);
4620 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4621 final String stackedIface = stacked.getInterfaceName();
4622 bs.noteNetworkInterfaceType(stackedIface, type);
4623 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4624 }
4625 } catch (RemoteException ignored) {
4626 }
4627
Robert Greenwalt152ed372014-12-17 17:19:53 -08004628 // This has to happen after the notifyNetworkCallbacks as that tickles each
4629 // ConnectivityManager instance so that legacy requests correctly bind dns
4630 // requests to this network. The legacy users are listening for this bcast
4631 // and will generally do a dns request so they can ensureRouteToHost and if
4632 // they do that before the callbacks happen they'll use the default network.
4633 //
4634 // TODO: Is there still a race here? We send the broadcast
4635 // after sending the callback, but if the app can receive the
4636 // broadcast before the callback, it might still break.
4637 //
4638 // This *does* introduce a race where if the user uses the new api
4639 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4640 // they may get old info. Reverse this after the old startUsing api is removed.
4641 // This is on top of the multiple intent sequencing referenced in the todo above.
4642 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4643 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4644 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4645 // legacy type tracker filters out repeat adds
4646 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4647 }
4648 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004649
4650 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4651 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4652 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4653 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4654 if (newNetwork.isVPN()) {
4655 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4656 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004657 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004658 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4659 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004660 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004661 if (DBG) log("Reaping " + nai.name());
4662 teardownUnneededNetwork(nai);
4663 }
4664 }
4665 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004666 }
4667
Paul Jensen1c7ba022015-06-16 14:27:36 -04004668 /**
4669 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4670 * being disconnected.
4671 * @param changed If only one Network's score or capabilities have been modified since the last
4672 * time this function was called, pass this Network in this argument, otherwise pass
4673 * null.
4674 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4675 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4676 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4677 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4678 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004679 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004680 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004681 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4682 // to avoid the slowness. It is not simply enough to process just "changed", for
4683 // example in the case where "changed"'s score decreases and another network should begin
4684 // satifying a NetworkRequest that "changed" currently satisfies.
4685
4686 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4687 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4688 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004689 if (changed != null && oldScore < changed.getCurrentScore()) {
4690 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004691 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004692 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4693 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4694 // Rematch higher scoring networks first to prevent requests first matching a lower
4695 // scoring network and then a higher scoring network, which could produce multiple
4696 // callbacks and inadvertently unlinger networks.
4697 Arrays.sort(nais);
4698 for (NetworkAgentInfo nai : nais) {
4699 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004700 // Only reap the last time through the loop. Reaping before all rematching
4701 // is complete could incorrectly teardown a network that hasn't yet been
4702 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004703 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004704 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004705 }
4706 }
4707 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004708
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004709 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004710 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004711 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004712 // For now only update icons for default connection.
4713 // TODO: Update WiFi and cellular icons separately. b/17237507
4714 if (!isDefaultNetwork(nai)) return;
4715
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004716 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004717 // Don't repeat publish.
4718 if (newInetCondition == mDefaultInetConditionPublished) return;
4719
4720 mDefaultInetConditionPublished = newInetCondition;
4721 sendInetConditionBroadcast(nai.networkInfo);
4722 }
4723
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004724 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4725 if (mLockdownTracker != null) {
4726 if (nai != null && nai.isVPN()) {
4727 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4728 } else {
4729 mLockdownTracker.onNetworkInfoChanged();
4730 }
4731 }
4732 }
4733
Robert Greenwalt7b816022014-04-18 15:25:25 -07004734 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4735 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004736 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004737 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004738 synchronized (networkAgent) {
4739 oldInfo = networkAgent.networkInfo;
4740 networkAgent.networkInfo = newInfo;
4741 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004742 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743
4744 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004745 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4746 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4747 notifyIfacesChangedForNetworkStats();
4748 } else if (VDBG) log("ignoring duplicate network state non-change");
4749 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004750 return;
4751 }
4752 if (DBG) {
4753 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4754 (oldInfo == null ? "null" : oldInfo.getState()) +
4755 " to " + state);
4756 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004757
Paul Jenseneec75412014-08-04 12:21:19 -04004758 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004760 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004761 if (networkAgent.isVPN()) {
4762 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004763 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4764 (networkAgent.networkMisc == null ||
4765 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004766 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004767 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4768 networkAgent.networkCapabilities.hasCapability(
4769 NET_CAPABILITY_NOT_RESTRICTED) ?
4770 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004771 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004772 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004773 loge("Error creating network " + networkAgent.network.netId + ": "
4774 + e.getMessage());
4775 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004776 }
Paul Jenseneec75412014-08-04 12:21:19 -04004777 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004778 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004779 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004780
Paul Jensenca8f16a2014-05-09 12:47:55 -04004781 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004782 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004783
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004784 if (networkAgent.isVPN()) {
4785 // Temporarily disable the default proxy (not global).
4786 synchronized (mProxyLock) {
4787 if (!mDefaultProxyDisabled) {
4788 mDefaultProxyDisabled = true;
4789 if (mGlobalProxy == null && mDefaultProxy != null) {
4790 sendProxyBroadcast(null);
4791 }
4792 }
4793 }
4794 // TODO: support proxy per network.
4795 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004796
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004797 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4798 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4799 // capabilities, so it only needs to be done once on initial connect, not every time the
4800 // network's capabilities change. Note that we do this before rematching the network,
4801 // so we could decide to tear it down immediately afterwards. That's fine though - on
4802 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4803 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004804 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004805
Paul Jensen2161a8e2014-09-11 11:00:39 -04004806 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004807 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004808
4809 // This has to happen after matching the requests, because callbacks are just requests.
4810 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004811 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004812 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004813 if (networkAgent.isVPN()) {
4814 synchronized (mProxyLock) {
4815 if (mDefaultProxyDisabled) {
4816 mDefaultProxyDisabled = false;
4817 if (mGlobalProxy == null && mDefaultProxy != null) {
4818 sendProxyBroadcast(mDefaultProxy);
4819 }
4820 }
4821 }
4822 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004823 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4824 state == NetworkInfo.State.SUSPENDED) {
4825 // going into or coming out of SUSPEND: rescore and notify
4826 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004827 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004828 }
4829 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4830 ConnectivityManager.CALLBACK_SUSPENDED :
4831 ConnectivityManager.CALLBACK_RESUMED));
4832 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004833 }
4834 }
4835
Robert Greenwaltac96c522014-06-03 16:43:57 -07004836 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004837 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004838 if (score < 0) {
4839 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4840 "). Bumping score to min of 0");
4841 score = 0;
4842 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004843
Paul Jensen2161a8e2014-09-11 11:00:39 -04004844 final int oldScore = nai.getCurrentScore();
4845 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004846
Paul Jensen85cf78e2015-06-25 13:25:07 -04004847 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004848
Paul Jensenc8b9a742014-09-30 15:37:41 -04004849 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004850 }
4851
Robert Greenwalt9258c642014-03-26 16:47:06 -07004852 // notify only this one new request of the current state
4853 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4854 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4855 // TODO - read state from monitor to decide what to send.
4856// if (nai.networkMonitor.isLingering()) {
4857// notifyType = NetworkCallbacks.LOSING;
4858// } else if (nai.networkMonitor.isEvaluating()) {
4859// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4860// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004861 if (nri.mPendingIntent == null) {
4862 callCallbackForRequest(nri, nai, notifyType);
4863 } else {
4864 sendPendingIntentForRequest(nri, nai, notifyType);
4865 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004866 }
4867
Robert Greenwalt8d482522015-06-24 13:23:42 -07004868 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004869 // The NetworkInfo we actually send out has no bearing on the real
4870 // state of affairs. For example, if the default connection is mobile,
4871 // and a request for HIPRI has just gone away, we need to pretend that
4872 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4873 // the state to DISCONNECTED, even though the network is of type MOBILE
4874 // and is still connected.
4875 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4876 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004877 if (state != DetailedState.DISCONNECTED) {
4878 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004879 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004880 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004881 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004882 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4883 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4884 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4885 if (info.isFailover()) {
4886 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4887 nai.networkInfo.setFailover(false);
4888 }
4889 if (info.getReason() != null) {
4890 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4891 }
4892 if (info.getExtraInfo() != null) {
4893 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4894 }
4895 NetworkAgentInfo newDefaultAgent = null;
4896 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004897 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004898 if (newDefaultAgent != null) {
4899 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4900 newDefaultAgent.networkInfo);
4901 } else {
4902 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4903 }
4904 }
4905 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4906 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004907 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004908 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004909 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004910 }
4911 }
4912 }
4913
Robert Greenwalt7b816022014-04-18 15:25:25 -07004914 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004915 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004916 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004917 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4918 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4919 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004920 if (nri.mPendingIntent == null) {
4921 callCallbackForRequest(nri, networkAgent, notifyType);
4922 } else {
4923 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4924 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004927
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004928 private String notifyTypeToName(int notifyType) {
4929 switch (notifyType) {
4930 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4931 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4932 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4933 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4934 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4935 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4936 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4937 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4938 }
4939 return "UNKNOWN";
4940 }
4941
Jeff Sharkey69736342014-12-08 14:50:12 -08004942 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004943 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4944 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004945 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004946 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004947 try {
4948 mStatsService.forceUpdateIfaces();
4949 } catch (Exception ignored) {
4950 }
4951 }
4952
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004953 @Override
4954 public boolean addVpnAddress(String address, int prefixLength) {
4955 throwIfLockdownEnabled();
4956 int user = UserHandle.getUserId(Binder.getCallingUid());
4957 synchronized (mVpns) {
4958 return mVpns.get(user).addAddress(address, prefixLength);
4959 }
4960 }
4961
4962 @Override
4963 public boolean removeVpnAddress(String address, int prefixLength) {
4964 throwIfLockdownEnabled();
4965 int user = UserHandle.getUserId(Binder.getCallingUid());
4966 synchronized (mVpns) {
4967 return mVpns.get(user).removeAddress(address, prefixLength);
4968 }
4969 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004970
4971 @Override
4972 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4973 throwIfLockdownEnabled();
4974 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004975 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004976 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004977 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004978 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004979 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004980 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004981 }
4982 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004983 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004984
4985 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08004986 public String getCaptivePortalServerUrl() {
4987 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
4988 }
4989
4990 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004991 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4992 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4993 enforceKeepalivePermission();
4994 mKeepaliveTracker.startNattKeepalive(
4995 getNetworkAgentInfoForNetwork(network),
4996 intervalSeconds, messenger, binder,
4997 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4998 }
4999
5000 @Override
5001 public void stopKeepalive(Network network, int slot) {
5002 mHandler.sendMessage(mHandler.obtainMessage(
5003 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5004 }
5005
5006 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005007 public void factoryReset() {
5008 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005009
5010 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5011 return;
5012 }
5013
Robin Lee3b3dd942015-05-12 18:14:58 +01005014 final int userId = UserHandle.getCallingUserId();
5015
Stuart Scottf1fb3972015-04-02 18:00:02 -07005016 // Turn airplane mode off
5017 setAirplaneMode(false);
5018
Stuart Scotte3e314d2015-04-20 14:07:45 -07005019 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5020 // Untether
5021 for (String tether : getTetheredIfaces()) {
5022 untether(tether);
5023 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005024 }
5025
Stuart Scotte3e314d2015-04-20 14:07:45 -07005026 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5027 // Turn VPN off
5028 VpnConfig vpnConfig = getVpnConfig(userId);
5029 if (vpnConfig != null) {
5030 if (vpnConfig.legacy) {
5031 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5032 } else {
5033 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5034 // in the future without user intervention.
5035 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005036
Stuart Scotte3e314d2015-04-20 14:07:45 -07005037 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5038 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005039 }
5040 }
5041 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005042
5043 @VisibleForTesting
5044 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5045 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5046 return new NetworkMonitor(context, handler, nai, defaultRequest);
5047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048}