blob: f5710e3271256e481b6866a80e6274fc7f0d3c9a [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;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
lucasline252a742019-03-12 13:08:03 +080028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090029import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040030import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090032import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
34import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080038import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060040import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080041import static android.net.NetworkPolicyManager.RULE_NONE;
42import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090043import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070044import static android.os.Process.INVALID_UID;
45import static android.system.OsConstants.IPPROTO_TCP;
46import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060047
Hugo Benichia0385682017-03-22 17:07:57 +090048import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060049
Chalard Jeanff46a252019-04-10 23:07:55 +090050import android.annotation.NonNull;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080051import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080052import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090053import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070054import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070055import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ContentResolver;
57import android.content.Context;
58import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070059import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070060import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070061import android.database.ContentObserver;
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +090062import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070063import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.ConnectivityManager;
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +090065import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.IConnectivityManager;
Luke Huang65914772019-03-16 00:31:46 +080067import android.net.IDnsResolver;
dalyk7301aa42018-03-05 12:42:22 -050068import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080069import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050070import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070071import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090072import android.net.INetworkMonitor;
73import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070074import android.net.INetworkPolicyListener;
75import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070076import android.net.INetworkStatsService;
junyulai7c469172019-01-16 20:23:34 +080077import android.net.ISocketKeepaliveCallback;
markchien6ea34542019-02-27 14:56:11 +080078import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090079import android.net.InetAddresses;
80import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080081import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070082import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010083import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080084import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070085import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070086import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070087import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070088import android.net.NetworkConfig;
Chalard Jean08577fc2018-05-02 21:14:54 +090089import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070092import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090093import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070094import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070095import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070096import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090097import android.net.NetworkStack;
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +090098import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070099import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700100import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +0000101import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900102import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400103import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700104import android.net.RouteInfo;
junyulaie4135282019-01-03 18:50:15 +0800105import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400106import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400107import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600108import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900109import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900110import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700111import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900112import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900113import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900114import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800116import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700117import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700119import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700120import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700121import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.os.Looper;
123import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700124import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700125import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900126import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700127import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700128import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700129import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800130import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900131import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900132import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700133import android.os.ShellCallback;
134import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900135import android.os.SystemClock;
Anil Admale41992c2019-04-08 12:36:02 -0700136import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700137import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400138import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700140import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700141import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700142import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700143import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900144import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700145import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600146import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900147import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800148import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700149import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500150import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700151import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Wink Savilleab9321d2013-06-29 21:10:57 -0700154import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400155import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400156import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700157import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANd4a9de202019-01-30 22:01:20 +0900158import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700159import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700160import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800161import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700162import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900163import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700164import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600165import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700166import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900167import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900168import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700170import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400171import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900172import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500173import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900174import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900175import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100176import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700177import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900178import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700179import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600180import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900181import com.android.server.connectivity.NetworkNotificationManager;
182import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700183import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900184import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800185import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700186import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100187import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500188import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700189import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700190import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900191import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700192import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600193
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700194import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700195
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700196import org.xmlpull.v1.XmlPullParser;
197import org.xmlpull.v1.XmlPullParserException;
198
199import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700201import java.io.FileNotFoundException;
202import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700203import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700205import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700206import java.net.InetAddress;
207import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700208import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700209import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700210import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900211import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800212import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700213import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700214import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700215import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700216import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700217import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900218import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600219import java.util.SortedSet;
220import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222/**
223 * @hide
224 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800225public class ConnectivityService extends IConnectivityManager.Stub
226 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900227 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
Chalard Jean4133a122018-06-04 13:33:12 +0900229 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900230 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900231 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900232 private static final String NETWORK_ARG = "networks";
233 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900234
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900235 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900236 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
237 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900239 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700240
Remi NGUYEN VAN9ca4c622019-04-09 02:04:54 -0700241 /**
242 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
243 * by OEMs for configuration purposes, as this value is overridden by
244 * Settings.Global.CAPTIVE_PORTAL_HTTP_URL.
245 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
246 * (preferably via runtime resource overlays).
247 */
248 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
249 "http://connectivitycheck.gstatic.com/generate_204";
250
Jeff Sharkey899223b2012-08-04 15:24:58 -0700251 // TODO: create better separation between radio types and network types
252
Robert Greenwalt42acef32009-08-12 16:08:25 -0700253 // how long to wait before switching back to a radio's default network
254 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
255 // system property that can override the above value
256 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
257 "android.telephony.apn-restore";
258
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900259 // How long to wait before putting up a "This network doesn't have an Internet connection,
260 // connect anyway?" dialog after the user selects a network that doesn't validate.
261 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
262
lucaslind2e045e02019-01-24 15:55:30 +0800263 // How long to dismiss network notification.
264 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
265
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900266 // Default to 30s linger time-out. Modifiable only for testing.
267 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
268 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
269 @VisibleForTesting
270 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
271
Jeremy Joslin79294842014-12-03 17:15:28 -0800272 // How long to delay to removal of a pending intent based request.
273 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
274 private final int mReleasePendingIntentDelayMs;
275
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900276 private MockableSystemProperties mSystemProperties;
277
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800278 private Tethering mTethering;
279
Rubin Xu9a3f7242019-04-11 11:45:43 -0700280 @VisibleForTesting
281 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700282
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700283 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700284
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900285 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700286 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900287 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700288
Hugo Benichi69744342017-11-27 10:57:16 +0900289 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
290 // a direct call to LockdownVpnTracker.isEnabled().
291 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700292 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900293 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700294 private LockdownVpnTracker mLockdownTracker;
295
junyulai05986c62018-08-07 19:50:45 +0800296 /**
297 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
298 * handler thread, they don't need a lock.
299 */
300 private SparseIntArray mUidRules = new SparseIntArray();
301 /** Flag indicating if background data is restricted. */
302 private boolean mRestrictBackground;
303
Erik Klineda4bfa82015-04-30 12:58:40 +0900304 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700305 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700306 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307
Luke Huang4e25ec62018-09-27 16:58:23 +0800308 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800309 @VisibleForTesting
Luke Huang65914772019-03-16 00:31:46 +0800310 protected IDnsResolver mDnsResolver;
311 @VisibleForTesting
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800312 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800313 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700314 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900315 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700316
Benedict Wong99a48412018-11-09 14:45:34 -0800317 /**
318 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
319 * instances.
320 */
321 @GuardedBy("mTNSLock")
322 private TestNetworkService mTNS;
323
324 private final Object mTNSLock = new Object();
325
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700326 private String mCurrentTcpBufferSizes;
327
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900328 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900329 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
330 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900331
Paul Jensenb10e37f2014-11-25 12:33:08 -0500332 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400333 // Tear down networks that have no chance (e.g. even if validated) of becoming
334 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500335 // all networks have been rematched against all NetworkRequests.
336 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400337 // Don't reap networks. This should be passed when some networks have not yet been
338 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500339 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900340 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500341
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900342 private enum UnneededFor {
343 LINGER, // Determine whether this network is unneeded and should be lingered.
344 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
345 }
346
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700347 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700348 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700349 * from one net to another. Clear happens when we get a new
350 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
351 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700352 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700353 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700354
Robert Greenwalt434203a2010-10-11 16:00:27 -0700355 /**
356 * used internally to reload global proxy settings
357 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700358 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700359
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700360 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400361 * PAC manager has received new port.
362 */
363 private static final int EVENT_PROXY_HAS_CHANGED = 16;
364
Robert Greenwalte049c232014-04-11 15:53:27 -0700365 /**
366 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700367 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700368 */
369 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
370
Robert Greenwalt7b816022014-04-18 15:25:25 -0700371 /**
372 * used internally when registering NetworkAgents
373 * obj = Messenger
374 */
375 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
376
Robert Greenwalt9258c642014-03-26 16:47:06 -0700377 /**
378 * used to add a network request
379 * includes a NetworkRequestInfo
380 */
381 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
382
383 /**
384 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900385 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700386 * cancel it.
387 * includes a NetworkRequestInfo
388 */
389 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
390
391 /**
392 * used to add a network listener - no request
393 * includes a NetworkRequestInfo
394 */
395 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
396
397 /**
398 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400399 * arg1 = UID of caller
400 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700401 */
402 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
403
Robert Greenwalta67be032014-05-16 15:49:14 -0700404 /**
405 * used internally when registering NetworkFactories
406 * obj = Messenger
407 */
408 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
409
Robert Greenwalt27711812014-06-25 16:45:57 -0700410 /**
411 * used internally to expire a wakelock when transitioning
412 * from one net to another. Expire happens when we fail to find
413 * a new network (typically after 1 minute) -
414 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
415 * a replacement network.
416 */
417 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
418
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700419 /**
420 * Used internally to indicate the system is ready.
421 */
422 private static final int EVENT_SYSTEM_READY = 25;
423
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800424 /**
425 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400426 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800427 */
428 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
429
430 /**
431 * used to remove a pending intent and its associated network request.
432 * arg1 = UID of caller
433 * obj = PendingIntent
434 */
435 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
436
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900437 /**
438 * used to specify whether a network should be used even if unvalidated.
439 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
440 * arg2 = whether to remember this choice in the future (1 or 0)
441 * obj = network
442 */
443 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
444
445 /**
446 * used to ask the user to confirm a connection to an unvalidated network.
447 * obj = network
448 */
449 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700450
Erik Klineda4bfa82015-04-30 12:58:40 +0900451 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700452 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900453 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700454 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900455
Paul Jensen694f2b82015-06-17 14:15:39 -0400456 /**
457 * used to add a network listener with a pending intent
458 * obj = NetworkRequestInfo
459 */
460 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
461
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900462 /**
463 * used to specify whether a network should not be penalized when it becomes unvalidated.
464 */
465 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
466
467 /**
468 * used to trigger revalidation of a network.
469 */
470 private static final int EVENT_REVALIDATE_NETWORK = 36;
471
Erik Klinea24d4592018-01-11 21:07:29 +0900472 // Handle changes in Private DNS settings.
473 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
474
dalyk7301aa42018-03-05 12:42:22 -0500475 // Handle private DNS validation status updates.
476 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
477
junyulai05986c62018-08-07 19:50:45 +0800478 /**
479 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
480 */
481 private static final int EVENT_UID_RULES_CHANGED = 39;
482
483 /**
484 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
485 */
486 private static final int EVENT_DATA_SAVER_CHANGED = 40;
487
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900488 /**
489 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
490 * been tested.
491 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
492 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
493 * arg2 = NetID.
494 */
495 public static final int EVENT_NETWORK_TESTED = 41;
496
497 /**
498 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
499 * config was resolved.
500 * obj = PrivateDnsConfig
501 * arg2 = netid
502 */
503 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
504
505 /**
506 * Request ConnectivityService display provisioning notification.
507 * arg1 = Whether to make the notification visible.
508 * arg2 = NetID.
509 * obj = Intent to be launched when notification selected by user, null if !arg1.
510 */
511 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
512
513 /**
lucaslind2e045e02019-01-24 15:55:30 +0800514 * This event can handle dismissing notification by given network id.
515 */
516 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
517
518 /**
lucasline252a742019-03-12 13:08:03 +0800519 * Used to specify whether a network should be used even if connectivity is partial.
520 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
521 * false)
522 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
523 * obj = network
524 */
525 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
526
527 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900528 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
529 * should be shown.
530 */
531 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
532
533 /**
534 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
535 * should be hidden.
536 */
537 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
538
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900539 private static String eventName(int what) {
540 return sMagicDecoderRing.get(what, Integer.toString(what));
541 }
542
Luke Huang65914772019-03-16 00:31:46 +0800543 private static IDnsResolver getDnsResolver() {
544 return IDnsResolver.Stub
545 .asInterface(ServiceManager.getService("dnsresolver"));
546 }
547
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900548 /** Handler thread used for both of the handlers below. */
549 @VisibleForTesting
550 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700551 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700552 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700553 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700554 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900555 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700556
Mike Lockwood0f79b542009-08-14 14:18:49 -0400557 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800558 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400559
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700560 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700561 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800562 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700563
Chalard Jean52c2aa72018-06-07 16:44:04 +0900564 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
565 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000566 @VisibleForTesting
567 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400568
Erik Klineda4bfa82015-04-30 12:58:40 +0900569 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700570
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400571 private UserManager mUserManager;
572
Chalard Jean4133a122018-06-04 13:33:12 +0900573 private NetworkConfig[] mNetConfigs;
574 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700575
Robert Greenwalt50393202011-06-21 17:26:14 -0700576 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900577 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700578
Chalard Jean4133a122018-06-04 13:33:12 +0900579 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400580
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900581 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900582 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900583 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900584
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700585 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800586 private static final int MIN_NET_ID = 100; // some reserved marks
587 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700588 private int mNextNetId = MIN_NET_ID;
589
Robert Greenwalt34524f02014-05-18 16:22:10 -0700590 // sequence number of NetworkRequests
591 private int mNextNetworkRequestId = 1;
592
Erik Kline7523eb32015-07-09 18:24:03 +0900593 // NetworkRequest activity String log entries.
594 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
595 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
596
Hugo Benichic2ae2872016-07-11 11:05:12 +0900597 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900598 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900599 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
600
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900601 private static final int MAX_WAKELOCK_LOGS = 20;
602 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900603 private int mTotalWakelockAcquisitions = 0;
604 private int mTotalWakelockReleases = 0;
605 private long mTotalWakelockDurationMs = 0;
606 private long mMaxWakelockDurationMs = 0;
607 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900608
Hugo Benichif9fdf872016-07-28 17:53:06 +0900609 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900610
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700611 @GuardedBy("mBandwidthRequests")
612 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
613
Erik Kline065ab6e2016-10-02 18:02:14 +0900614 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900615 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900616
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900617 @VisibleForTesting
618 final MultipathPolicyTracker mMultipathPolicyTracker;
619
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700620 /**
621 * Implements support for the legacy "one network per network type" model.
622 *
623 * We used to have a static array of NetworkStateTrackers, one for each
624 * network type, but that doesn't work any more now that we can have,
625 * for example, more that one wifi network. This class stores all the
626 * NetworkAgentInfo objects that support a given type, but the legacy
627 * API will only see the first one.
628 *
629 * It serves two main purposes:
630 *
631 * 1. Provide information about "the network for a given type" (since this
632 * API only supports one).
633 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
634 * the first network for a given type changes, or if the default network
635 * changes.
636 */
Chalard Jeanff46a252019-04-10 23:07:55 +0900637 @VisibleForTesting
638 static class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900640 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900642
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643 /**
644 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
645 * Each list holds references to all NetworkAgentInfos that are used to
646 * satisfy requests for that network type.
647 *
648 * This array is built out at startup such that an unsupported network
649 * doesn't get an ArrayList instance, making this a tristate:
650 * unsupported, supported but not active and active.
651 *
652 * The actual lists are populated when we scan the network types that
653 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900654 *
655 * Threading model:
656 * - addSupportedType() is only called in the constructor
657 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
658 * They are therefore not thread-safe with respect to each other.
659 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
660 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
661 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700662 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900663 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jeanff46a252019-04-10 23:07:55 +0900664 @NonNull
665 private final ConnectivityService mService;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666
Chalard Jeanff46a252019-04-10 23:07:55 +0900667 LegacyTypeTracker(@NonNull ConnectivityService service) {
668 mService = service;
669 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700670 }
671
672 public void addSupportedType(int type) {
673 if (mTypeLists[type] != null) {
674 throw new IllegalStateException(
675 "legacy list for type " + type + "already initialized");
676 }
Chalard Jean4133a122018-06-04 13:33:12 +0900677 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700678 }
679
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700680 public boolean isTypeSupported(int type) {
681 return isNetworkTypeValid(type) && mTypeLists[type] != null;
682 }
683
684 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900685 synchronized (mTypeLists) {
686 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
687 return mTypeLists[type].get(0);
688 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700689 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900690 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700691 }
692
Robert Greenwalt8d482522015-06-24 13:23:42 -0700693 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900694 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900695 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700696 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900697 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900698 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900699 }
700 }
701
702 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700703 public void add(int type, NetworkAgentInfo nai) {
704 if (!isTypeSupported(type)) {
705 return; // Invalid network type.
706 }
707 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
708
709 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
710 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700711 return;
712 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900713 synchronized (mTypeLists) {
714 list.add(nai);
715 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900716
717 // Send a broadcast if this is the first network of its type or if it's the default.
Chalard Jeanff46a252019-04-10 23:07:55 +0900718 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900719 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700720 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
Chalard Jeanff46a252019-04-10 23:07:55 +0900721 mService.sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700722 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700723 }
724
Lorenzo Colittia793a672014-07-31 23:20:17 +0900725 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900726 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900727 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
728 if (list == null || list.isEmpty()) {
729 return;
730 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900731 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900732
Hugo Benichi78caa2582016-06-21 09:48:07 +0900733 synchronized (mTypeLists) {
734 if (!list.remove(nai)) {
735 return;
736 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900737 }
738
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900739 if (wasFirstNetwork || wasDefault) {
Chalard Jean98c59fa2019-04-11 14:09:07 +0900740 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
741 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900742 }
743
744 if (!list.isEmpty() && wasFirstNetwork) {
745 if (DBG) log("Other network available for type " + type +
746 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900747 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean98c59fa2019-04-11 14:09:07 +0900748 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
749 mService.isDefaultNetwork(replacement));
750 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900751 }
752 }
753
754 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900755 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
756 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700757 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900758 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700759 }
760 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700761
Robert Greenwalt8d482522015-06-24 13:23:42 -0700762 // send out another legacy broadcast - currently only used for suspend/unsuspend
763 // toggle
764 public void update(NetworkAgentInfo nai) {
Chalard Jeanff46a252019-04-10 23:07:55 +0900765 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700766 final DetailedState state = nai.networkInfo.getDetailedState();
767 for (int type = 0; type < mTypeLists.length; type++) {
768 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700769 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900770 final boolean isFirst = contains && (nai == list.get(0));
771 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700772 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jeanff46a252019-04-10 23:07:55 +0900773 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700774 }
775 }
776 }
777
Lorenzo Colittia793a672014-07-31 23:20:17 +0900778 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900779 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900780 String state = (nai.networkInfo != null) ?
781 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
782 "???/???";
783 return name + " " + state;
784 }
785
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700786 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900787 pw.println("mLegacyTypeTracker:");
788 pw.increaseIndent();
789 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700790 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900791 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700792 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900793 pw.println();
794 pw.println("Current state:");
795 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900796 synchronized (mTypeLists) {
797 for (int type = 0; type < mTypeLists.length; type++) {
798 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
799 for (NetworkAgentInfo nai : mTypeLists[type]) {
800 pw.println(type + " " + naiToString(nai));
801 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900802 }
803 }
804 pw.decreaseIndent();
805 pw.decreaseIndent();
806 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700807 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700808 }
Chalard Jeanff46a252019-04-10 23:07:55 +0900809 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700810
Vishnu Nair5c010902017-10-26 10:08:50 -0700811 /**
812 * Helper class which parses out priority arguments and dumps sections according to their
813 * priority. If priority arguments are omitted, function calls the legacy dump command.
814 */
815 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
816 @Override
817 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
818 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
819 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
820 }
821
822 @Override
823 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
824 doDump(fd, pw, args, asProto);
825 }
826
827 @Override
828 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
829 doDump(fd, pw, args, asProto);
830 }
831 };
832
Jeff Sharkey899223b2012-08-04 15:24:58 -0700833 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700834 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Luke Huang65914772019-03-16 00:31:46 +0800835 this(context, netManager, statsService, policyManager,
Rubin Xu9a3f7242019-04-11 11:45:43 -0700836 getDnsResolver(), new IpConnectivityLog(), NetdService.getInstance());
Hugo Benichif9fdf872016-07-28 17:53:06 +0900837 }
838
839 @VisibleForTesting
840 protected ConnectivityService(Context context, INetworkManagementService netManager,
841 INetworkStatsService statsService, INetworkPolicyManager policyManager,
Rubin Xu9a3f7242019-04-11 11:45:43 -0700842 IDnsResolver dnsresolver, IpConnectivityLog logger, INetd netd) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800843 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800844
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900845 mSystemProperties = getSystemProperties();
846
Hugo Benichif9fdf872016-07-28 17:53:06 +0900847 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900848 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900849 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900850 mNetworkRequests.put(mDefaultRequest, defaultNRI);
851 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900852
Chalard Jeandda156a2018-01-10 21:19:32 +0900853 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900854 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700855
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700856 // The default WiFi request is a background request so that apps using WiFi are
857 // migrated to a better network (typically ethernet) when one comes up, instead
858 // of staying on WiFi forever.
859 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
860 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
861
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900862 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900863 mHandlerThread.start();
864 mHandler = new InternalHandler(mHandlerThread.getLooper());
865 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700866
Jeremy Joslin79294842014-12-03 17:15:28 -0800867 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
868 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
869
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900870 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900871
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700872 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800873 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800874 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900876 mPolicyManagerInternal = checkNotNull(
877 LocalServices.getService(NetworkPolicyManagerInternal.class),
878 "missing NetworkPolicyManagerInternal");
Luke Huang65914772019-03-16 00:31:46 +0800879 mDnsResolver = checkNotNull(dnsresolver, "missing IDnsResolver");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000880 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900881
Rubin Xu9a3f7242019-04-11 11:45:43 -0700882 mNetd = netd;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700883 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700884 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700885
junyulai05986c62018-08-07 19:50:45 +0800886 // To ensure uid rules are synchronized with Network Policy, register for
887 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
888 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700889 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900890 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700891 } catch (RemoteException e) {
892 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700893 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700894 }
895
896 final PowerManager powerManager = (PowerManager) context.getSystemService(
897 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700898 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
899 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
900 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800901 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700902
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700903 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700904
Wink Saville51f456f2013-04-23 14:26:51 -0700905 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900906 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700907 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700908 String[] naStrings = context.getResources().getStringArray(
909 com.android.internal.R.array.networkAttributes);
910 for (String naString : naStrings) {
911 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700912 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700913 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700914 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800915 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700916 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700917 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700918 }
Wink Saville51f456f2013-04-23 14:26:51 -0700919 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
920 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
921 n.type);
922 continue;
923 }
Wink Saville975c8482011-04-07 14:23:45 -0700924 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800925 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700926 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700927 continue;
928 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700929 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700930
Wink Saville975c8482011-04-07 14:23:45 -0700931 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700932 mNetworksDefined++;
933 } catch(Exception e) {
934 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700935 }
936 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700937
938 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
939 if (mNetConfigs[TYPE_VPN] == null) {
940 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
941 // don't need to add TYPE_VPN to mNetConfigs.
942 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
943 mNetworksDefined++; // used only in the log() statement below.
944 }
945
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900946 // Do the same for Ethernet, since it's often not specified in the configs, although many
947 // devices can use it via USB host adapters.
948 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
949 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
950 mNetworksDefined++;
951 }
952
Wink Saville5e56bc52013-07-29 15:00:57 -0700953 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700954
Robert Greenwalt50393202011-06-21 17:26:14 -0700955 mProtectedNetworks = new ArrayList<Integer>();
956 int[] protectedNetworks = context.getResources().getIntArray(
957 com.android.internal.R.array.config_protectedNetworks);
958 for (int p : protectedNetworks) {
959 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
960 mProtectedNetworks.add(p);
961 } else {
962 if (DBG) loge("Ignoring protectedNetwork " + p);
963 }
964 }
965
Erik Kline47222fc2017-04-30 19:36:15 +0900966 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800967
Rubin Xu9a3f7242019-04-11 11:45:43 -0700968 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700969
Varun Anand4fa80e82019-02-06 10:13:38 -0800970 // Set up the listener for user state for creating user VPNs.
971 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700972 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100973 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700974 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700975 intentFilter.addAction(Intent.ACTION_USER_ADDED);
976 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000977 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700978 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800979 mIntentReceiver,
980 UserHandle.ALL,
981 intentFilter,
982 null /* broadcastPermission */,
983 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000984 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
985 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900986
junyulai2454b692018-11-01 17:16:31 +0800987 // Listen to package add and removal events for all users.
988 intentFilter = new IntentFilter();
989 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800990 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800991 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
992 intentFilter.addDataScheme("package");
993 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800994 mIntentReceiver,
995 UserHandle.ALL,
996 intentFilter,
997 null /* broadcastPermission */,
998 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800999
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001000 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001001 mNMS.registerObserver(mTethering);
1002 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001003 } catch (RemoteException e) {
1004 loge("Error registering observer :" + e);
1005 }
1006
Erik Klineda4bfa82015-04-30 12:58:40 +09001007 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1008 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -08001009
Chalard Jean4133a122018-06-04 13:33:12 +09001010 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
1011 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -04001012
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04001013 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001014
junyulai0c666972019-03-04 22:45:36 +08001015 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +09001016 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
1017 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +09001018
1019 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1020 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1021 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1022 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1023 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1024 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1025 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001026
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001027 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001028 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001029 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001030
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001031 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1032
Luke Huang65914772019-03-16 00:31:46 +08001033 mDnsManager = new DnsManager(mContext, mDnsResolver, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001034 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001036
Mike Yuf9729752018-08-17 15:22:05 +08001037 @VisibleForTesting
1038 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001039 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001040 final TetheringDependencies deps = new TetheringDependencies() {
1041 @Override
1042 public boolean isTetheringSupported() {
1043 return ConnectivityService.this.isTetheringSupported();
1044 }
Erik Kline72302902018-06-14 17:36:40 +09001045 @Override
1046 public NetworkRequest getDefaultNetworkRequest() {
1047 return mDefaultRequest;
1048 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001049 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001050 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001051 IoThread.get().getLooper(), new MockableSystemProperties(),
1052 deps);
1053 }
1054
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001055 @VisibleForTesting
1056 protected ProxyTracker makeProxyTracker() {
1057 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1058 }
1059
Chalard Jean26400492018-04-18 20:18:38 +09001060 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1061 final NetworkCapabilities netCap = new NetworkCapabilities();
1062 netCap.addCapability(NET_CAPABILITY_INTERNET);
1063 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1064 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1065 netCap.setSingleUid(uid);
1066 return netCap;
1067 }
1068
Chalard Jeandda156a2018-01-10 21:19:32 +09001069 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001070 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001071 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001072 netCap.addCapability(NET_CAPABILITY_INTERNET);
1073 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001074 if (transportType > -1) {
1075 netCap.addTransportType(transportType);
1076 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001077 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001078 }
1079
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001080 // Used only for testing.
1081 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001082 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001083 // changing ContentResolver to make registerContentObserver non-final).
1084 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1085 // by subclassing SettingsObserver.
1086 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001087 void updateAlwaysOnNetworks() {
1088 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001089 }
1090
Erik Kline736353a2018-03-21 07:18:33 -07001091 // See FakeSettingsProvider comment above.
1092 @VisibleForTesting
1093 void updatePrivateDnsSettings() {
1094 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1095 }
1096
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001097 private void handleAlwaysOnNetworkRequest(
1098 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001099 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001100 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1101 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001102 if (enable == isEnabled) {
1103 return; // Nothing to do.
1104 }
1105
1106 if (enable) {
1107 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001108 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001109 } else {
Etan Cohenae574a82019-01-08 12:09:18 -08001110 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1111 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001112 }
1113 }
1114
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001115 private void handleConfigureAlwaysOnNetworks() {
1116 handleAlwaysOnNetworkRequest(
1117 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1118 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1119 false);
1120 }
1121
Erik Klineda4bfa82015-04-30 12:58:40 +09001122 private void registerSettingsCallbacks() {
1123 // Watch for global HTTP proxy changes.
1124 mSettingsObserver.observe(
1125 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1126 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1127
1128 // Watch for whether or not to keep mobile data always on.
1129 mSettingsObserver.observe(
1130 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001131 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1132
1133 // Watch for whether or not to keep wifi always on.
1134 mSettingsObserver.observe(
1135 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1136 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001137 }
1138
Erik Klinea24d4592018-01-11 21:07:29 +09001139 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001140 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1141 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001142 }
1143 }
1144
Robert Greenwalt34524f02014-05-18 16:22:10 -07001145 private synchronized int nextNetworkRequestId() {
1146 return mNextNetworkRequestId++;
1147 }
1148
Paul Jensen67b0b072015-06-10 11:22:17 -04001149 @VisibleForTesting
1150 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001151 synchronized (mNetworkForNetId) {
1152 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1153 int netId = mNextNetId;
1154 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1155 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001156 if (!mNetIdInUse.get(netId)) {
1157 mNetIdInUse.put(netId, true);
1158 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001159 }
1160 }
1161 }
1162 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001163 }
1164
Chalard Jeanc0982912018-06-07 16:11:34 +09001165 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1168 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 state = nai.getNetworkState();
1171 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 final NetworkInfo info = new NetworkInfo(networkType, 0,
1174 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1176 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001177 final NetworkCapabilities capabilities = new NetworkCapabilities();
1178 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1179 !info.isRoaming());
1180 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001181 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001183 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 return state;
1185 } else {
1186 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001188 }
1189
junyulai4a192e22018-06-13 15:00:37 +08001190 @VisibleForTesting
1191 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001192 if (network == null) {
1193 return null;
1194 }
Erik Kline736353a2018-03-21 07:18:33 -07001195 return getNetworkAgentInfoForNetId(network.netId);
1196 }
1197
1198 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001200 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001202 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001204 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001205 synchronized (mVpns) {
1206 if (!mLockdownEnabled) {
1207 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001208 Vpn vpn = mVpns.get(user);
1209 if (vpn != null && vpn.appliesToUid(uid)) {
1210 return vpn.getUnderlyingNetworks();
1211 }
1212 }
1213 }
1214 return null;
1215 }
1216
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001218 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001219
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001220 final Network[] networks = getVpnUnderlyingNetworks(uid);
1221 if (networks != null) {
1222 // getUnderlyingNetworks() returns:
1223 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1224 // empty array => the VPN explicitly said "no default network".
1225 // non-empty array => the VPN specified one or more default networks; we use the
1226 // first one.
1227 if (networks.length > 0) {
1228 nai = getNetworkAgentInfoForNetwork(networks[0]);
1229 } else {
1230 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001231 }
1232 }
1233
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001234 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001235 return nai.getNetworkState();
1236 } else {
1237 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001239 }
1240
1241 /**
1242 * Check if UID should be blocked from using the network with the given LinkProperties.
1243 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001244 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1245 boolean ignoreBlocked) {
1246 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001247 if (ignoreBlocked) {
1248 return false;
1249 }
Robin Lee17e61832016-05-09 13:46:28 +01001250 synchronized (mVpns) {
1251 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001252 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001253 return true;
1254 }
1255 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001256 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001257 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001258 }
1259
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001260 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001261 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1262 return;
1263 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001264 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001265 synchronized (mBlockedAppUids) {
1266 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001267 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001268 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001269 blocked = false;
1270 } else {
1271 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001272 }
1273 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001274 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1275 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1276 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001277 }
1278
junyulai05986c62018-08-07 19:50:45 +08001279 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1280 boolean blocked) {
1281 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1282 return;
1283 }
1284 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1285 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1286 nri.mUid, nri.request.requestId, net.netId));
1287 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1288 }
1289
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001290 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001291 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1292 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001293 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001294 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001295 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001296 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1297
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001298 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001299 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001300 }
Hugo Benichi69744342017-11-27 10:57:16 +09001301 synchronized (mVpns) {
1302 if (mLockdownTracker != null) {
1303 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1304 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001305 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001306 }
1307
1308 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 * Return NetworkInfo for the active (i.e., connected) network interface.
1310 * It is assumed that at most one network is active at a time. If more
1311 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001312 * @return the info for the active network, or {@code null} if none is
1313 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001315 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001317 enforceAccessPermission();
1318 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001319 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001320 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001321 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1322 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
Paul Jensen31a94f42015-02-13 14:18:39 -05001325 @Override
1326 public Network getActiveNetwork() {
1327 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001328 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001329 }
1330
1331 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001332 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001333 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001334 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001335 }
1336
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001337 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001338 final int user = UserHandle.getUserId(uid);
1339 int vpnNetId = NETID_UNSET;
1340 synchronized (mVpns) {
1341 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001342 // TODO : now that capabilities contain the UID, the appliesToUid test should
1343 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001344 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1345 }
1346 NetworkAgentInfo nai;
1347 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001348 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001349 if (nai != null) {
1350 final NetworkCapabilities requiredCaps =
1351 createDefaultNetworkCapabilitiesForUid(uid);
1352 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1353 return nai.network;
1354 }
1355 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001356 }
1357 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001358 if (nai != null
1359 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1360 nai = null;
1361 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001362 return nai != null ? nai.network : null;
1363 }
1364
Lorenzo Colitti18660282016-07-04 12:55:44 +09001365 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001366 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1367 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001368 final int uid = Binder.getCallingUid();
1369 NetworkState state = getUnfilteredActiveNetworkState(uid);
1370 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001371 }
1372
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001373 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001374 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001376 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001377 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001378 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 }
1380
1381 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 public NetworkInfo getNetworkInfo(int networkType) {
1383 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001385 if (getVpnUnderlyingNetworks(uid) != null) {
1386 // A VPN is active, so we may need to return one of its underlying networks. This
1387 // information is not available in LegacyTypeTracker, so we have to get it from
1388 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001389 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001390 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001391 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001392 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001393 }
1394 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001395 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001396 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 }
1398
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001399 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001400 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001401 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001402 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001403 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001404 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001405 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001406 return state.networkInfo;
1407 } else {
1408 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001409 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001410 }
1411
1412 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 public NetworkInfo[] getAllNetworkInfo() {
1414 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001415 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001416 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1417 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001418 NetworkInfo info = getNetworkInfo(networkType);
1419 if (info != null) {
1420 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001423 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001426 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001427 public Network getNetworkForType(int networkType) {
1428 enforceAccessPermission();
1429 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001430 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001431 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001432 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001433 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001434 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001435 }
1436
1437 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 public Network[] getAllNetworks() {
1439 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001440 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001441 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001442 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001443 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001444 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001445 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001446 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001447 }
1448
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001449 @Override
1450 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1451 // The basic principle is: if an app's traffic could possibly go over a
1452 // network, without the app doing anything multinetwork-specific,
1453 // (hence, by "default"), then include that network's capabilities in
1454 // the array.
1455 //
1456 // In the normal case, app traffic only goes over the system's default
1457 // network connection, so that's the only network returned.
1458 //
1459 // With a VPN in force, some app traffic may go into the VPN, and thus
1460 // over whatever underlying networks the VPN specifies, while other app
1461 // traffic may go over the system default network (e.g.: a split-tunnel
1462 // VPN, or an app disallowed by the VPN), so the set of networks
1463 // returned includes the VPN's underlying networks and the system
1464 // default.
1465 enforceAccessPermission();
1466
Chalard Jean4133a122018-06-04 13:33:12 +09001467 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001468
1469 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001470 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001471 if (nc != null) {
1472 result.put(nai.network, nc);
1473 }
1474
Hugo Benichi69744342017-11-27 10:57:16 +09001475 synchronized (mVpns) {
1476 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001477 Vpn vpn = mVpns.get(userId);
1478 if (vpn != null) {
1479 Network[] networks = vpn.getUnderlyingNetworks();
1480 if (networks != null) {
1481 for (Network network : networks) {
1482 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001483 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001484 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001485 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001486 }
1487 }
1488 }
1489 }
1490 }
1491 }
1492
1493 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1494 out = result.values().toArray(out);
1495 return out;
1496 }
1497
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001498 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001499 public boolean isNetworkSupported(int networkType) {
1500 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001501 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001502 }
1503
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001504 /**
1505 * Return LinkProperties for the active (i.e., connected) default
1506 * network interface. It is assumed that at most one default network
1507 * is active at a time. If more than one is active, it is indeterminate
1508 * which will be returned.
1509 * @return the ip properties for the active network, or {@code null} if
1510 * none is active
1511 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001512 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001513 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001514 enforceAccessPermission();
1515 final int uid = Binder.getCallingUid();
1516 NetworkState state = getUnfilteredActiveNetworkState(uid);
1517 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001518 }
1519
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001520 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001521 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001522 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001523 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1524 if (nai != null) {
1525 synchronized (nai) {
1526 return new LinkProperties(nai.linkProperties);
1527 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001528 }
1529 return null;
1530 }
1531
Robert Greenwalt12e67352014-05-13 21:41:06 -07001532 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001533 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001534 public LinkProperties getLinkProperties(Network network) {
1535 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001536 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1537 }
1538
1539 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1540 if (nai == null) {
1541 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001542 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001543 synchronized (nai) {
1544 return new LinkProperties(nai.linkProperties);
1545 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001546 }
1547
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001548 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001549 if (nai != null) {
1550 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001551 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001552 return networkCapabilitiesRestrictedForCallerPermissions(
1553 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001554 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001555 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001556 }
1557 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001558 return null;
1559 }
1560
1561 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001562 public NetworkCapabilities getNetworkCapabilities(Network network) {
1563 enforceAccessPermission();
1564 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1565 }
1566
Chalard Jeanb03a6222018-04-11 21:09:10 +09001567 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001568 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001569 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001570 if (!checkSettingsPermission(callerPid, callerUid)) {
1571 newNc.setUids(null);
1572 newNc.setSSID(null);
1573 }
Etan Cohen836ad572018-12-30 17:59:59 -08001574 if (newNc.getNetworkSpecifier() != null) {
1575 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1576 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001577 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001578 }
1579
Chalard Jeanb552c462018-02-21 18:43:54 +09001580 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1581 if (!checkSettingsPermission()) {
1582 nc.setSingleUid(Binder.getCallingUid());
1583 }
1584 }
1585
Chalard Jean26aa91a2018-03-20 19:13:57 +09001586 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1587 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1588 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1589 }
1590 }
1591
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001592 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001593 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001594 // Require internal since we're handing out IMSI details
1595 enforceConnectivityInternalPermission();
1596
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001597 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001598 for (Network network : getAllNetworks()) {
1599 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1600 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001601 // TODO (b/73321673) : NetworkState contains a copy of the
1602 // NetworkCapabilities, which may contain UIDs of apps to which the
1603 // network applies. Should the UIDs be cleared so as not to leak or
1604 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001605 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001606 }
1607 }
1608 return result.toArray(new NetworkState[result.size()]);
1609 }
1610
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001611 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001612 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001613 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001614 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1615 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1616 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001617 }
1618
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001619 @Override
1620 public boolean isActiveNetworkMetered() {
1621 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001622
Varun Anandc51b06d2019-02-25 17:22:02 -08001623 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001624 if (caps != null) {
1625 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1626 } else {
1627 // Always return the most conservative value
1628 return true;
1629 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001630 }
1631
Jeff Sharkey216c1812012-08-05 14:29:23 -07001632 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1633 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001634 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001635 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001636 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001637 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001638 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001639
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001640 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001641 * Ensures that the system cannot call a particular method.
1642 */
1643 private boolean disallowedBecauseSystemCaller() {
1644 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale41992c2019-04-08 12:36:02 -07001645 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
1646 // for devices launched with Q and above. However, existing devices upgrading to Q and
1647 // above must continued to be supported for few more releases.
1648 if (isSystem(Binder.getCallingUid()) && SystemProperties.getInt(
1649 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001650 log("This method exists only for app backwards compatibility"
1651 + " and must not be called by system services.");
1652 return true;
1653 }
1654 return false;
1655 }
1656
1657 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 * Ensure that a network route exists to deliver traffic to the specified
1659 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001660 * @param networkType the type of the network over which traffic to the
1661 * specified host is to be routed
1662 * @param hostAddress the IP address of the host to which the route is
1663 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * @return {@code true} on success, {@code false} on failure
1665 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001666 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001667 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001668 if (disallowedBecauseSystemCaller()) {
1669 return false;
1670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001672 if (mProtectedNetworks.contains(networkType)) {
1673 enforceConnectivityInternalPermission();
1674 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001675
Chad Brubakerc0234532014-02-14 13:24:29 -08001676 InetAddress addr;
1677 try {
1678 addr = InetAddress.getByAddress(hostAddress);
1679 } catch (UnknownHostException e) {
1680 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1681 return false;
1682 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001685 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 return false;
1687 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001688
1689 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1690 if (nai == null) {
1691 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1692 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1693 } else {
1694 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1695 }
1696 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001697 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001698
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001699 DetailedState netState;
1700 synchronized (nai) {
1701 netState = nai.networkInfo.getDetailedState();
1702 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001703
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001704 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001705 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001706 log("requestRouteToHostAddress on down network "
1707 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001708 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001709 }
1710 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001712
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001713 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001714 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001715 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001716 LinkProperties lp;
1717 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001718 synchronized (nai) {
1719 lp = nai.linkProperties;
1720 netId = nai.network.netId;
1721 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001722 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001723 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1724 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001725 } finally {
1726 Binder.restoreCallingIdentity(token);
1727 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001728 }
1729
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001730 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001731 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001732 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001733 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001734 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001735 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001736 if (bestRoute.getGateway().equals(addr)) {
1737 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001738 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001739 } else {
1740 // if we will connect to this through another route, add a direct route
1741 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001742 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001743 }
1744 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001745 if (DBG) log("Adding legacy route " + bestRoute +
1746 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001747 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001748 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001749 } catch (Exception e) {
1750 // never crash - catch them all
1751 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001752 return false;
1753 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001754 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756
dalyk7301aa42018-03-05 12:42:22 -05001757 @VisibleForTesting
1758 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1759 @Override
1760 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1761 String hostname, boolean validated) {
1762 try {
1763 mHandler.sendMessage(mHandler.obtainMessage(
1764 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1765 new PrivateDnsValidationUpdate(netId,
1766 InetAddress.parseNumericAddress(ipAddress),
1767 hostname, validated)));
1768 } catch (IllegalArgumentException e) {
1769 loge("Error parsing ip address in validation event");
1770 }
1771 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001772
1773 @Override
1774 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1775 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1776 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1777 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1778 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1779 // event callback for certain nai. e.g. cellular. Register here to pass to
1780 // NetworkMonitor instead.
1781 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1782 // registerNetworkAgent to have NetworkMonitor created with system process as design
1783 // expectation. Also, NetdEventListenerService only allow one callback from each
1784 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1785 // NetworkMonitor registrants.
1786 if (nai != null && nai.satisfies(mDefaultRequest)) {
Chalard Jean971d9c92019-04-08 20:28:44 +09001787 Binder.withCleanCallingIdentity(() ->
1788 nai.networkMonitor().notifyDnsResponse(returnCode));
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001789 }
1790 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001791
1792 @Override
1793 public void onNat64PrefixEvent(int netId, boolean added,
1794 String prefixString, int prefixLength) {
1795 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1796 }
dalyk7301aa42018-03-05 12:42:22 -05001797 };
1798
1799 @VisibleForTesting
1800 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001801 final IIpConnectivityMetrics ipConnectivityMetrics =
1802 IIpConnectivityMetrics.Stub.asInterface(
1803 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1804 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001805 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001806 return;
dalyk7301aa42018-03-05 12:42:22 -05001807 }
1808
1809 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001810 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001811 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1812 mNetdEventCallback);
1813 } catch (Exception e) {
1814 loge("Error registering netd callback: " + e);
1815 }
1816 }
1817
Jeff Sharkey75d31892018-01-18 22:01:59 +09001818 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001819 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001820 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001821 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001822 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001823 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001824 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001825 // caller is NPMS, since we only register with them
1826 if (LOGD_BLOCKED_NETWORKINFO) {
1827 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1828 }
1829 mHandler.sendMessage(mHandler.obtainMessage(
1830 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1831
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001832 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001833 if (restrictBackground) {
1834 log("onRestrictBackgroundChanged(true): disabling tethering");
1835 mTethering.untetherAll();
1836 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001837 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001838 };
1839
junyulai05986c62018-08-07 19:50:45 +08001840 void handleUidRulesChanged(int uid, int newRules) {
1841 // skip update when we've already applied rules
1842 final int oldRules = mUidRules.get(uid, RULE_NONE);
1843 if (oldRules == newRules) return;
1844
1845 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1846
1847 if (newRules == RULE_NONE) {
1848 mUidRules.delete(uid);
1849 } else {
1850 mUidRules.put(uid, newRules);
1851 }
1852 }
1853
1854 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1855 if (mRestrictBackground == restrictBackground) return;
1856
1857 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1858 final boolean curMetered = nai.networkCapabilities.isMetered();
1859 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1860 restrictBackground);
1861 }
1862
1863 mRestrictBackground = restrictBackground;
1864 }
1865
1866 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1867 boolean isBackgroundRestricted) {
1868 synchronized (mVpns) {
1869 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1870 // Because the return value of this function depends on the list of UIDs the
1871 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1872 // list all state depending on the return value of this function has to be recomputed.
1873 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1874 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001875 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001876 return true;
1877 }
1878 }
1879
1880 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1881 isNetworkMetered, isBackgroundRestricted);
1882 }
1883
Robin Lee3b3dd942015-05-12 18:14:58 +01001884 /**
1885 * Require that the caller is either in the same user or has appropriate permission to interact
1886 * across users.
1887 *
1888 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1889 */
1890 private void enforceCrossUserPermission(int userId) {
1891 if (userId == UserHandle.getCallingUserId()) {
1892 // Not a cross-user call.
1893 return;
1894 }
1895 mContext.enforceCallingOrSelfPermission(
1896 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1897 "ConnectivityService");
1898 }
1899
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001900 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001901 for (String permission : permissions) {
1902 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001903 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001904 }
1905 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001906 return false;
1907 }
1908
paulhu3d67f532019-03-22 16:35:06 +08001909 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
1910 for (String permission : permissions) {
1911 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
1912 return true;
1913 }
1914 }
1915 return false;
1916 }
1917
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001918 private void enforceAnyPermissionOf(String... permissions) {
1919 if (!checkAnyPermissionOf(permissions)) {
1920 throw new SecurityException("Requires one of the following permissions: "
1921 + String.join(", ", permissions) + ".");
1922 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001923 }
1924
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001925 private void enforceInternetPermission() {
1926 mContext.enforceCallingOrSelfPermission(
1927 android.Manifest.permission.INTERNET,
1928 "ConnectivityService");
1929 }
1930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001932 mContext.enforceCallingOrSelfPermission(
1933 android.Manifest.permission.ACCESS_NETWORK_STATE,
1934 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936
1937 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001938 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940
Charles He36738632017-05-15 17:07:18 +01001941 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001942 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001943 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001944 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001945 }
1946
Chalard Jeanb552c462018-02-21 18:43:54 +09001947 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001948 return checkAnyPermissionOf(
1949 android.Manifest.permission.NETWORK_SETTINGS,
1950 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001951 }
1952
1953 private boolean checkSettingsPermission(int pid, int uid) {
1954 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001955 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1956 || PERMISSION_GRANTED == mContext.checkPermission(
1957 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001958 }
1959
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001960 private void enforceTetherAccessPermission() {
1961 mContext.enforceCallingOrSelfPermission(
1962 android.Manifest.permission.ACCESS_NETWORK_STATE,
1963 "ConnectivityService");
1964 }
1965
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001966 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001967 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001968 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001969 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001970 }
1971
Pavel Grafova462bcb2019-01-25 08:50:06 +00001972 private void enforceControlAlwaysOnVpnPermission() {
1973 mContext.enforceCallingOrSelfPermission(
1974 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1975 "ConnectivityService");
1976 }
1977
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001978 private void enforceNetworkStackSettingsOrSetup() {
1979 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001980 android.Manifest.permission.NETWORK_SETTINGS,
1981 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001982 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001983 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001984 }
1985
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001986 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001987 return checkAnyPermissionOf(
1988 android.Manifest.permission.NETWORK_STACK,
1989 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001990 }
1991
paulhu3d67f532019-03-22 16:35:06 +08001992 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
1993 return checkAnyPermissionOf(pid, uid,
1994 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
1995 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
1996 }
1997
Hugo Benichi514da602016-07-19 15:59:27 +09001998 private void enforceConnectivityRestrictedNetworksPermission() {
1999 try {
2000 mContext.enforceCallingOrSelfPermission(
2001 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2002 "ConnectivityService");
2003 return;
2004 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2005 enforceConnectivityInternalPermission();
2006 }
2007
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002008 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09002009 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002010 }
2011
Lorenzo Colitti18660282016-07-04 12:55:44 +09002012 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002013 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002014 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07002015 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002016 }
2017
2018 private void sendInetConditionBroadcast(NetworkInfo info) {
2019 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2020 }
2021
Wink Saville628b0852011-08-04 15:01:58 -07002022 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09002023 synchronized (mVpns) {
2024 if (mLockdownTracker != null) {
2025 info = new NetworkInfo(info);
2026 mLockdownTracker.augmentNetworkInfo(info);
2027 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002028 }
2029
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002030 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002031 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002032 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 if (info.isFailover()) {
2034 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2035 info.setFailover(false);
2036 }
2037 if (info.getReason() != null) {
2038 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2039 }
2040 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002041 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2042 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002044 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002045 return intent;
2046 }
2047
2048 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2049 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2050 }
2051
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002052 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002053 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2054 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2055 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002056 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002057 final long ident = Binder.clearCallingIdentity();
2058 try {
2059 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2060 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2061 } finally {
2062 Binder.restoreCallingIdentity(ident);
2063 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002064 }
2065
Mike Lockwood0f79b542009-08-14 14:18:49 -04002066 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002067 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002068 if (!mSystemReady
2069 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002070 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002071 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002072 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002073 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002074 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002075 }
2076
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002077 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002078 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002079 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002080 final NetworkInfo ni = intent.getParcelableExtra(
2081 ConnectivityManager.EXTRA_NETWORK_INFO);
2082 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2083 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2084 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002085 } else {
2086 BroadcastOptions opts = BroadcastOptions.makeBasic();
2087 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2088 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002089 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002090 final IBatteryStats bs = BatteryStatsService.getService();
2091 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002092 bs.noteConnectivityChanged(intent.getIntExtra(
2093 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002094 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002095 } catch (RemoteException e) {
2096 }
Chad Brubakerac925012018-03-08 10:37:09 -08002097 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002098 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002099 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002100 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002104 }
2105 }
2106
2107 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002108 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002109 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002110 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002111
Hugo Benichi20035e02017-04-26 14:53:28 +09002112 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002113 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002114 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002115 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002116 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002117 }
2118 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002119
Robin Lee244ce8e2016-01-05 18:03:46 +00002120 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2121 // for user to unlock device too.
2122 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002123
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002124 // Create network requests for always-on networks.
2125 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002126
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002128
2129 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002134 *
2135 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002136 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002137 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2139 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002140
2141 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002143
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 if (networkAgent.networkCapabilities.hasTransport(
2145 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002146 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2147 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002148 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002149 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 } else if (networkAgent.networkCapabilities.hasTransport(
2151 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002152 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2153 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002154 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002156 } else {
2157 // do not track any other networks
2158 timeout = 0;
2159 }
2160
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002162 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002163 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002164 } catch (Exception e) {
2165 // You shall not crash!
2166 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002167 }
2168 }
2169 }
2170
2171 /**
2172 * Remove data activity tracking when network disconnects.
2173 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002174 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2175 final String iface = networkAgent.linkProperties.getInterfaceName();
2176 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002177
Robert Greenwalt7b816022014-04-18 15:25:25 -07002178 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2179 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002180 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002181 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002182 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002183 } catch (Exception e) {
2184 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002185 }
2186 }
2187 }
2188
2189 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002190 * Update data activity tracking when network state is updated.
2191 */
2192 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2193 NetworkAgentInfo oldNetwork) {
2194 if (newNetwork != null) {
2195 setupDataActivityTracking(newNetwork);
2196 }
2197 if (oldNetwork != null) {
2198 removeDataActivityTracking(oldNetwork);
2199 }
2200 }
2201 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002202 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002203 * and set it on it's iface.
2204 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2206 final String iface = newLp.getInterfaceName();
2207 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002208 if (oldLp == null && mtu == 0) {
2209 // Silently ignore unset MTU value.
2210 return;
2211 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002212 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2213 if (VDBG) log("identical MTU - not setting");
2214 return;
2215 }
paulhud9736de2019-03-08 16:35:20 +08002216 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002217 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002218 return;
2219 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002220
w1997615afd812014-08-05 15:18:11 -07002221 // Cannot set MTU without interface name
2222 if (TextUtils.isEmpty(iface)) {
2223 loge("Setting MTU size with null iface.");
2224 return;
2225 }
2226
Robert Greenwalt7b816022014-04-18 15:25:25 -07002227 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002228 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002229 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002230 } catch (Exception e) {
2231 Slog.e(TAG, "exception in setMtu()" + e);
2232 }
2233 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002234
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002235 @VisibleForTesting
2236 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002237 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2238
2239 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002240 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002241 protected MockableSystemProperties getSystemProperties() {
2242 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002243 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002244
lucaslin041a1af2018-11-28 19:27:52 +08002245 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002246 String[] values = null;
2247 if (tcpBufferSizes != null) {
2248 values = tcpBufferSizes.split(",");
2249 }
2250
2251 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002252 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002253 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2254 values = tcpBufferSizes.split(",");
2255 }
2256
2257 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2258
2259 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002260 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002261
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002262 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2263 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2264 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002265 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002266 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002267 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002268 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002269
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002270 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002271 Settings.Global.TCP_DEFAULT_INIT_RWND,
2272 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002273 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2274 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002275 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002276 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002277 }
2278
Robert Greenwalt562cc542014-05-15 18:07:26 -07002279 @Override
2280 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002281 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002282 NETWORK_RESTORE_DELAY_PROP_NAME);
2283 if(restoreDefaultNetworkDelayStr != null &&
2284 restoreDefaultNetworkDelayStr.length() != 0) {
2285 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002286 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002287 } catch (NumberFormatException e) {
2288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002290 // if the system property isn't set, use the value for the apn type
2291 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2292
2293 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2294 (mNetConfigs[networkType] != null)) {
2295 ret = mNetConfigs[networkType].restoreTime;
2296 }
2297 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 }
2299
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002300 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2301 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2302 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002303 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002304 // Start gathering diagnostic information.
2305 netDiags.add(new NetworkDiagnostics(
2306 nai.network,
2307 new LinkProperties(nai.linkProperties), // Must be a copy.
2308 DIAG_TIME_MS));
2309 }
2310
2311 for (NetworkDiagnostics netDiag : netDiags) {
2312 pw.println();
2313 netDiag.waitForMeasurements();
2314 netDiag.dump(pw);
2315 }
2316 }
2317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002319 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002320 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2321 }
2322
2323 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002324 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002325 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002326 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002327
Erik Kline3f8306b2018-05-01 16:51:44 +09002328 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002329 dumpNetworkDiagnostics(pw);
2330 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002331 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002332 mTethering.dump(fd, pw, args);
2333 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002334 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2335 dumpNetworks(pw);
2336 return;
2337 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2338 dumpNetworkRequests(pw);
2339 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002340 }
Erik Kline379747a2015-06-05 17:47:34 +09002341
Lorenzo Colittie3805462015-06-03 11:18:24 +09002342 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002343 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002344 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002345 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002346 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002347 pw.println();
2348
Paul Jensen85cf78e2015-06-25 13:25:07 -04002349 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002350 pw.print("Active default network: ");
2351 if (defaultNai == null) {
2352 pw.println("none");
2353 } else {
2354 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002356 pw.println();
2357
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002358 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002359 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002360 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002361 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002362 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002363
junyulai05986c62018-08-07 19:50:45 +08002364 pw.print("Restrict background: ");
2365 pw.println(mRestrictBackground);
2366 pw.println();
2367
2368 pw.println("Status for known UIDs:");
2369 pw.increaseIndent();
2370 final int size = mUidRules.size();
2371 for (int i = 0; i < size; i++) {
2372 // Don't crash if the array is modified while dumping in bugreports.
2373 try {
2374 final int uid = mUidRules.keyAt(i);
2375 final int uidRules = mUidRules.get(uid, RULE_NONE);
2376 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2377 } catch (ArrayIndexOutOfBoundsException e) {
2378 pw.println(" ArrayIndexOutOfBoundsException");
2379 } catch (ConcurrentModificationException e) {
2380 pw.println(" ConcurrentModificationException");
2381 }
2382 }
2383 pw.println();
2384 pw.decreaseIndent();
2385
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002386 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002387 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002388 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002389 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002390 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002391
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002392 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002393
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002394 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002395 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002396
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002397 pw.println();
2398 mKeepaliveTracker.dump(pw);
2399
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002400 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002401 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002402
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002403 pw.println();
2404 mMultipathPolicyTracker.dump(pw);
2405
Erik Kline3f8306b2018-05-01 16:51:44 +09002406 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002407 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002408 pw.println("mNetworkRequestInfoLogs (most recent first):");
2409 pw.increaseIndent();
2410 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2411 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002412
2413 pw.println();
2414 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2415 pw.increaseIndent();
2416 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2417 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002418
2419 pw.println();
2420 pw.println("NetTransition WakeLock activity (most recent first):");
2421 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002422 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2423 pw.println("total releases: " + mTotalWakelockReleases);
2424 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2425 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2426 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2427 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2428 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2429 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002430 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002431
2432 pw.println();
2433 pw.println("bandwidth update requests (by uid):");
2434 pw.increaseIndent();
2435 synchronized (mBandwidthRequests) {
2436 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2437 pw.println("[" + mBandwidthRequests.keyAt(i)
2438 + "]: " + mBandwidthRequests.valueAt(i));
2439 }
2440 }
2441 pw.decreaseIndent();
2442
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002443 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002444 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002445
2446 pw.println();
2447 pw.println("NetworkStackClient logs:");
2448 pw.increaseIndent();
2449 NetworkStackClient.getInstance().dump(pw);
Rubin Xu9a3f7242019-04-11 11:45:43 -07002450 pw.decreaseIndent();
2451
2452 pw.println();
2453 pw.println("Permission Monitor:");
2454 pw.increaseIndent();
2455 mPermissionMonitor.dump(pw);
2456 pw.decreaseIndent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 }
2458
Hugo Benichi14683812018-09-03 08:32:56 +09002459 private void dumpNetworks(IndentingPrintWriter pw) {
2460 for (NetworkAgentInfo nai : networksSortedById()) {
2461 pw.println(nai.toString());
2462 pw.increaseIndent();
2463 pw.println(String.format(
2464 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2465 nai.numForegroundNetworkRequests(),
2466 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2467 nai.numBackgroundNetworkRequests(),
2468 nai.numNetworkRequests()));
2469 pw.increaseIndent();
2470 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2471 pw.println(nai.requestAt(i).toString());
2472 }
2473 pw.decreaseIndent();
2474 pw.println("Lingered:");
2475 pw.increaseIndent();
2476 nai.dumpLingerTimers(pw);
2477 pw.decreaseIndent();
2478 pw.decreaseIndent();
2479 }
2480 }
2481
2482 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2483 for (NetworkRequestInfo nri : requestsSortedById()) {
2484 pw.println(nri.toString());
2485 }
2486 }
2487
Hugo Benichia2a917c2018-09-03 08:19:02 +09002488 /**
2489 * Return an array of all current NetworkAgentInfos sorted by network id.
2490 */
2491 private NetworkAgentInfo[] networksSortedById() {
2492 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2493 networks = mNetworkAgentInfos.values().toArray(networks);
2494 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2495 return networks;
2496 }
2497
2498 /**
2499 * Return an array of all current NetworkRequest sorted by request id.
2500 */
2501 private NetworkRequestInfo[] requestsSortedById() {
2502 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2503 requests = mNetworkRequests.values().toArray(requests);
2504 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2505 return requests;
2506 }
2507
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002508 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002509 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002510 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002511 if (officialNai != null && officialNai.equals(nai)) return true;
2512 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002513 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002514 " - " + nai);
2515 }
2516 return false;
2517 }
2518
Robert Greenwalt42acef32009-08-12 16:08:25 -07002519 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002520 private class NetworkStateTrackerHandler extends Handler {
2521 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002522 super(looper);
2523 }
2524
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002525 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002527 default:
2528 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002529 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002530 handleAsyncChannelHalfConnect(msg);
2531 break;
2532 }
2533 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2534 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2535 if (nai != null) nai.asyncChannel.disconnect();
2536 break;
2537 }
2538 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2539 handleAsyncChannelDisconnected(msg);
2540 break;
2541 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002542 }
2543 return true;
2544 }
2545
2546 private void maybeHandleNetworkAgentMessage(Message msg) {
2547 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2548 if (nai == null) {
2549 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002550 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002551 }
2552 return;
2553 }
2554
2555 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002556 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002557 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002558 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002559 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002560 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002561 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002562 break;
2563 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002564 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002565 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002566 break;
2567 }
2568 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002569 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002570 updateNetworkInfo(nai, info);
2571 break;
2572 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002573 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002574 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002575 break;
2576 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002577 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002578 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2579 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002580 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002581 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002582 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002583 // Mark the network as temporarily accepting partial connectivity so that it
2584 // will be validated (and possibly become default) even if it only provides
2585 // partial internet access. Note that if user connects to partial connectivity
2586 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2587 // out of wifi coverage) and if the same wifi is available again, the device
2588 // will auto connect to this wifi even though the wifi has "no internet".
2589 // TODO: Evaluate using a separate setting in IpMemoryStore.
2590 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002591 break;
2592 }
junyulaie4135282019-01-03 18:50:15 +08002593 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2594 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002595 break;
2596 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002597 }
2598 }
2599
2600 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2601 switch (msg.what) {
2602 default:
2603 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002604 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002605 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002606 if (nai == null) break;
2607
lucasline252a742019-03-12 13:08:03 +08002608 final boolean partialConnectivity =
2609 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002610 || (nai.networkMisc.acceptPartialConnectivity
2611 && nai.partialConnectivity);
2612 // Once a network is determined to have partial connectivity, it cannot
lucaslin975b7d32019-03-21 11:59:22 +08002613 // go back to full connectivity without a disconnect. This is because
2614 // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
2615 // but not both.
2616 // TODO: Provide multi-testResult to improve the communication between
2617 // ConnectivityService and NetworkMonitor, so that ConnectivityService could
2618 // know the real status of network.
lucaslin43338992019-03-20 18:21:59 +08002619 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002620 (partialConnectivity && !nai.partialConnectivity);
2621
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002622 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002623 final boolean wasValidated = nai.lastValidated;
2624 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002625 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2626 && valid) {
2627 nai.captivePortalLoginNotified = true;
2628 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2629 }
Erik Klinea24d4592018-01-11 21:07:29 +09002630
Erik Klinea24d4592018-01-11 21:07:29 +09002631 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2632
Erik Klinea24d4592018-01-11 21:07:29 +09002633 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002634 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2635 ? " with redirect to " + redirectUrl
2636 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002637 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2638 }
Erik Klinea24d4592018-01-11 21:07:29 +09002639 if (valid != nai.lastValidated) {
2640 if (wasDefault) {
2641 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2642 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002643 }
Erik Klinea24d4592018-01-11 21:07:29 +09002644 final int oldScore = nai.getCurrentScore();
2645 nai.lastValidated = valid;
2646 nai.everValidated |= valid;
2647 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2648 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2649 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002650 if (valid) {
2651 handleFreshlyValidatedNetwork(nai);
2652 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2653 // valid.
2654 mNotifier.clearNotification(nai.network.netId,
2655 NotificationType.NO_INTERNET);
2656 mNotifier.clearNotification(nai.network.netId,
2657 NotificationType.LOST_INTERNET);
2658 }
lucaslin43338992019-03-20 18:21:59 +08002659 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002660 nai.partialConnectivity = partialConnectivity;
2661 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002662 }
2663 updateInetCondition(nai);
2664 // Let the NetworkAgent know the state of its network
2665 Bundle redirectUrlBundle = new Bundle();
2666 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2667 nai.asyncChannel.sendMessage(
2668 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2669 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2670 0, redirectUrlBundle);
2671 if (wasValidated && !nai.lastValidated) {
2672 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002673 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002674 break;
2675 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002676 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002677 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002678 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002679 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002680 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002681 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002682 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002683 nai.lastCaptivePortalDetected = visible;
2684 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002685 if (visible) {
2686 nai.captivePortalLoginNotified = false;
2687 }
Calvin Onbe96da12016-10-11 15:10:46 -07002688 if (nai.lastCaptivePortalDetected &&
2689 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2690 if (DBG) log("Avoiding captive portal network: " + nai.name());
2691 nai.asyncChannel.sendMessage(
2692 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2693 teardownUnneededNetwork(nai);
2694 break;
2695 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002696 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002697 }
2698 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002699 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002700 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002701 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2702 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002703 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002704 if (nai == null) {
2705 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2706 break;
2707 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002708 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002709 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002710 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002711 }
Paul Jensen869868be2014-05-15 10:33:05 -04002712 }
Paul Jensen869868be2014-05-15 10:33:05 -04002713 break;
2714 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002715 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002716 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002717 if (nai == null) break;
2718
Erik Kline736353a2018-03-21 07:18:33 -07002719 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002720 break;
2721 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002722 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002723 return true;
2724 }
2725
Calvin Onbe96da12016-10-11 15:10:46 -07002726 private int getCaptivePortalMode() {
2727 return Settings.Global.getInt(mContext.getContentResolver(),
2728 Settings.Global.CAPTIVE_PORTAL_MODE,
2729 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2730 }
2731
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002732 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2733 switch (msg.what) {
2734 default:
2735 return false;
2736 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2737 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2738 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2739 handleLingerComplete(nai);
2740 }
2741 break;
2742 }
2743 }
2744 return true;
2745 }
2746
Etan Cohenae574a82019-01-08 12:09:18 -08002747 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2748 switch (msg.what) {
2749 default:
2750 return false;
2751 case NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2752 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2753 /* callOnUnavailable */ true);
2754 break;
2755 }
2756 }
2757 return true;
2758 }
2759
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002760 @Override
2761 public void handleMessage(Message msg) {
Etan Cohenae574a82019-01-08 12:09:18 -08002762 if (!maybeHandleAsyncChannelMessage(msg)
2763 && !maybeHandleNetworkMonitorMessage(msg)
2764 && !maybeHandleNetworkAgentInfoMessage(msg)
2765 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002766 maybeHandleNetworkAgentMessage(msg);
2767 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002768 }
2769 }
2770
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002771 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2772 private final NetworkAgentInfo mNai;
2773
2774 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2775 mNai = nai;
2776 }
2777
2778 @Override
2779 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2780 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2781 new Pair<>(mNai, networkMonitor)));
2782 }
2783
2784 @Override
2785 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2786 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2787 testResult, mNai.network.netId, redirectUrl));
2788 }
2789
2790 @Override
2791 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2792 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2793 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2794 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2795 }
2796
2797 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002798 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002799 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002800 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002801
2802 final PendingIntent pendingIntent;
2803 // Only the system server can register notifications with package "android"
2804 final long token = Binder.clearCallingIdentity();
2805 try {
2806 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2807 } finally {
2808 Binder.restoreCallingIdentity(token);
2809 }
2810 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2811 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2812 mNai.network.netId,
2813 pendingIntent));
2814 }
2815
2816 @Override
2817 public void hideProvisioningNotification() {
2818 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2819 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2820 mNai.network.netId));
2821 }
Lorenzo Colittie8660ef2019-04-23 01:55:01 -07002822
2823 @Override
2824 public int getInterfaceVersion() {
2825 return this.VERSION;
2826 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002827 }
2828
Erik Kline736353a2018-03-21 07:18:33 -07002829 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002830 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002831 }
2832
Erik Klinec6d00222018-06-26 18:53:43 +09002833 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2834 if (nai == null) return;
2835 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2836 // in order to restart a validation pass from within netd.
2837 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2838 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2839 updateDnses(nai.linkProperties, null, nai.network.netId);
2840 }
2841 }
2842
Erik Klinea24d4592018-01-11 21:07:29 +09002843 private void handlePrivateDnsSettingsChanged() {
2844 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2845
2846 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002847 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002848 if (networkRequiresValidation(nai)) {
2849 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2850 }
Erik Klinea24d4592018-01-11 21:07:29 +09002851 }
2852 }
2853
Erik Kline736353a2018-03-21 07:18:33 -07002854 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2855 // Private DNS only ever applies to networks that might provide
2856 // Internet access and therefore also require validation.
2857 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002858
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002859 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002860 // schedule DNS resolutions. If a DNS resolution is required the
2861 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002862 try {
2863 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2864 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07002865 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002866 }
Erik Kline736353a2018-03-21 07:18:33 -07002867
2868 // With Private DNS bypass support, we can proceed to update the
2869 // Private DNS config immediately, even if we're in strict mode
2870 // and have not yet resolved the provider name into a set of IPs.
2871 updatePrivateDns(nai, cfg);
2872 }
2873
2874 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2875 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002876 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002877 }
2878
dalyk7301aa42018-03-05 12:42:22 -05002879 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2880 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2881 if (nai == null) {
2882 return;
2883 }
2884 mDnsManager.updatePrivateDnsValidation(update);
2885 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2886 }
2887
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002888 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2889 int prefixLength) {
2890 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2891 if (nai == null) return;
2892
2893 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2894 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2895
2896 IpPrefix prefix = null;
2897 if (added) {
2898 try {
2899 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2900 prefixLength);
2901 } catch (IllegalArgumentException e) {
2902 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2903 return;
2904 }
2905 }
2906
2907 nai.clatd.setNat64Prefix(prefix);
2908 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2909 }
2910
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002911 private void updateLingerState(NetworkAgentInfo nai, long now) {
2912 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2913 // 2. If the network was lingering and there are now requests, unlinger it.
2914 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2915 // one lingered request, start lingering.
2916 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002917 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002918 if (DBG) log("Unlingering " + nai.name());
2919 nai.unlinger();
2920 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002921 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002922 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002923 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002924 nai.linger();
2925 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2926 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2927 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002928 }
2929
Robert Greenwalt7b816022014-04-18 15:25:25 -07002930 private void handleAsyncChannelHalfConnect(Message msg) {
2931 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002932 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002933 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2934 if (VDBG) log("NetworkFactory connected");
Etan Cohenae574a82019-01-08 12:09:18 -08002935 // Finish setting up the full connection
2936 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2937 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002938 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002939 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002940 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002941 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002942 final int score;
2943 final int serial;
2944 if (nai != null) {
2945 score = nai.getCurrentScore();
2946 serial = nai.factorySerialNumber;
2947 } else {
2948 score = 0;
2949 serial = NetworkFactory.SerialNumber.NONE;
2950 }
2951 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2952 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002953 }
2954 } else {
2955 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002956 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002957 }
2958 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2959 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2960 if (VDBG) log("NetworkAgent connected");
2961 // A network agent has requested a connection. Establish the connection.
2962 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2963 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2964 } else {
2965 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002966 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002967 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002968 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002969 synchronized (mNetworkForNetId) {
2970 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002971 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002972 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002973 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002974 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002975 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002976 }
2977 }
2978 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002979
Chalard Jean392971c2018-05-11 20:19:20 +09002980 // This is a no-op if it's called with a message designating a network that has
2981 // already been destroyed, because its reference will not be found in the relevant
2982 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002983 private void handleAsyncChannelDisconnected(Message msg) {
2984 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2985 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002986 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002987 } else {
2988 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2989 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002990 }
2991 }
2992
Chalard Jean392971c2018-05-11 20:19:20 +09002993 // Destroys a network, remove references to it from the internal state managed by
2994 // ConnectivityService, free its interfaces and clean up.
2995 // Must be called on the Handler thread.
2996 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2997 if (DBG) {
2998 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2999 }
lucaslinf80b83b2019-02-12 15:30:13 +08003000 // Clear all notifications of this network.
3001 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003002 // A network agent has disconnected.
3003 // TODO - if we move the logic to the network agent (have them disconnect
3004 // because they lost all their requests or because their score isn't good)
3005 // then they would disconnect organically, report their new state and then
3006 // disconnect the channel.
3007 if (nai.networkInfo.isConnected()) {
3008 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3009 null, null);
3010 }
3011 final boolean wasDefault = isDefaultNetwork(nai);
3012 if (wasDefault) {
3013 mDefaultInetConditionPublished = 0;
3014 // Log default network disconnection before required book-keeping.
3015 // Let rematchAllNetworksAndRequests() below record a new default network event
3016 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
3017 // whose timestamps tell how long it takes to recover a default network.
3018 long now = SystemClock.elapsedRealtime();
3019 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
3020 }
3021 notifyIfacesChangedForNetworkStats();
3022 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3023 // by other networks that are already connected. Perhaps that can be done by
3024 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3025 // of rematchAllNetworksAndRequests
3026 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulaie4135282019-01-03 18:50:15 +08003027 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09003028 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3029 // Disable wakeup packet monitoring for each interface.
3030 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3031 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003032 try {
3033 nai.networkMonitor().notifyNetworkDisconnected();
3034 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07003035 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003036 }
Chalard Jean392971c2018-05-11 20:19:20 +09003037 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09003038 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09003039 synchronized (mNetworkForNetId) {
3040 // Remove the NetworkAgent, but don't mark the netId as
3041 // available until we've told netd to delete it below.
3042 mNetworkForNetId.remove(nai.network.netId);
3043 }
3044 // Remove all previously satisfied requests.
3045 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3046 NetworkRequest request = nai.requestAt(i);
3047 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3048 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3049 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09003050 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003051 }
3052 }
3053 nai.clearLingerState();
3054 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003055 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003056 notifyLockdownVpn(nai);
3057 ensureNetworkTransitionWakelock(nai.name());
3058 }
3059 mLegacyTypeTracker.remove(nai, wasDefault);
3060 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3061 updateAllVpnsCapabilities();
3062 }
3063 rematchAllNetworksAndRequests(null, 0);
3064 mLingerMonitor.noteDisconnect(nai);
3065 if (nai.created) {
3066 // Tell netd to clean up the configuration for this network
3067 // (routing rules, DNS, etc).
3068 // This may be slow as it requires a lot of netd shelling out to ip and
3069 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3070 // after we've rematched networks with requests which should make a potential
3071 // fallback network the default or requested a new network from the
3072 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3073 // long time.
3074 try {
Luke Huang65914772019-03-16 00:31:46 +08003075 mNetd.networkDestroy(nai.network.netId);
3076 } catch (RemoteException | ServiceSpecificException e) {
3077 loge("Exception destroying network: " + e);
Chalard Jean392971c2018-05-11 20:19:20 +09003078 }
3079 mDnsManager.removeNetwork(nai.network);
3080 }
3081 synchronized (mNetworkForNetId) {
3082 mNetIdInUse.delete(nai.network.netId);
3083 }
3084 }
3085
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003086 // If this method proves to be too slow then we can maintain a separate
3087 // pendingIntent => NetworkRequestInfo map.
3088 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3089 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3090 Intent intent = pendingIntent.getIntent();
3091 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3092 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3093 if (existingPendingIntent != null &&
3094 existingPendingIntent.getIntent().filterEquals(intent)) {
3095 return entry.getValue();
3096 }
3097 }
3098 return null;
3099 }
3100
3101 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3102 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3103
3104 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3105 if (existingRequest != null) { // remove the existing request.
3106 if (DBG) log("Replacing " + existingRequest.request + " with "
3107 + nri.request + " because their intents matched.");
Etan Cohenae574a82019-01-08 12:09:18 -08003108 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3109 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003110 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003111 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003112 }
3113
Erik Klineda4bfa82015-04-30 12:58:40 +09003114 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003115 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003116 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003117 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003118 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003119 if (nri.request.networkCapabilities.hasSignalStrength() &&
3120 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3121 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003122 }
3123 }
3124 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003125 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003126 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09003127 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003128 }
3129 }
3130
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003131 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3132 int callingUid) {
3133 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3134 if (nri != null) {
Etan Cohenae574a82019-01-08 12:09:18 -08003135 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003136 }
3137 }
3138
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003139 // Determines whether the network is the best (or could become the best, if it validated), for
3140 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3141 // on the value of reason:
3142 //
3143 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3144 // then it should be torn down.
3145 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3146 // then it should be lingered.
3147 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3148 final int numRequests;
3149 switch (reason) {
3150 case TEARDOWN:
3151 numRequests = nai.numRequestNetworkRequests();
3152 break;
3153 case LINGER:
3154 numRequests = nai.numForegroundNetworkRequests();
3155 break;
3156 default:
3157 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3158 return true;
3159 }
3160
3161 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003162 return false;
3163 }
Paul Jensene0988542015-06-25 15:30:08 -04003164 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003165 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3166 // Background requests don't affect lingering.
3167 continue;
3168 }
3169
Paul Jensene0988542015-06-25 15:30:08 -04003170 // If this Network is already the highest scoring Network for a request, or if
3171 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003172 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003173 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003174 // Note that this catches two important cases:
3175 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3176 // is currently satisfying the request. This is desirable when
3177 // cellular ends up validating but WiFi does not.
3178 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003179 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003180 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003181 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003182 nai.getCurrentScoreAsValidated())) {
3183 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003184 }
3185 }
Paul Jensene0988542015-06-25 15:30:08 -04003186 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003187 }
3188
Erik Klineacdd6392016-07-07 16:50:58 +09003189 private NetworkRequestInfo getNriForAppRequest(
3190 NetworkRequest request, int callingUid, String requestedOperation) {
3191 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3192
Robert Greenwalt9258c642014-03-26 16:47:06 -07003193 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003194 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003195 log(String.format("UID %d attempted to %s for unowned request %s",
3196 callingUid, requestedOperation, nri));
3197 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003198 }
Erik Klineacdd6392016-07-07 16:50:58 +09003199 }
3200
3201 return nri;
3202 }
3203
Erik Kline57faba92015-11-25 12:49:38 +09003204 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003205 if (mNetworkRequests.get(nri.request) == null) {
3206 return;
Erik Kline57faba92015-11-25 12:49:38 +09003207 }
Hugo Benichicd952782017-09-20 11:20:14 +09003208 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003209 return;
3210 }
3211 if (VDBG || (DBG && nri.request.isRequest())) {
3212 log("releasing " + nri.request + " (timeout)");
3213 }
3214 handleRemoveNetworkRequest(nri);
3215 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003216 }
3217
Etan Cohenae574a82019-01-08 12:09:18 -08003218 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3219 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003220 final NetworkRequestInfo nri =
3221 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3222 if (nri == null) {
3223 return;
Erik Kline57faba92015-11-25 12:49:38 +09003224 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003225 if (VDBG || (DBG && nri.request.isRequest())) {
3226 log("releasing " + nri.request + " (release request)");
3227 }
3228 handleRemoveNetworkRequest(nri);
Etan Cohenae574a82019-01-08 12:09:18 -08003229 if (callOnUnavailable) {
3230 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3231 }
Erik Kline57faba92015-11-25 12:49:38 +09003232 }
Erik Klineacdd6392016-07-07 16:50:58 +09003233
Hugo Benichidba33db2017-03-23 22:40:44 +09003234 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003235 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003236 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003237
Erik Klineacdd6392016-07-07 16:50:58 +09003238 synchronized (mUidToNetworkRequestCount) {
3239 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3240 if (requests < 1) {
3241 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3242 nri.mUid);
3243 } else if (requests == 1) {
3244 mUidToNetworkRequestCount.removeAt(
3245 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3246 } else {
3247 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3248 }
3249 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003250
Erik Klineacdd6392016-07-07 16:50:58 +09003251 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3252 if (nri.request.isRequest()) {
3253 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003254 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003255 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003256 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003257 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003258 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003259 log(" Removing from current network " + nai.name() +
3260 ", leaving " + nai.numNetworkRequests() + " requests.");
3261 }
3262 // If there are still lingered requests on this network, don't tear it down,
3263 // but resume lingering instead.
3264 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003265 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003266 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3267 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003268 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003269 wasKept = true;
3270 }
Hugo Benichicd952782017-09-20 11:20:14 +09003271 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003272 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3273 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003274 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003275 }
Erik Klineacdd6392016-07-07 16:50:58 +09003276 }
3277
Erik Klineacdd6392016-07-07 16:50:58 +09003278 // Maintain the illusion. When this request arrived, we might have pretended
3279 // that a network connected to serve it, even though the network was already
3280 // connected. Now that this request has gone away, we might have to pretend
3281 // that the network disconnected. LegacyTypeTracker will generate that
3282 // phantom disconnect for this type.
3283 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3284 boolean doRemove = true;
3285 if (wasKept) {
3286 // check if any of the remaining requests for this network are for the
3287 // same legacy type - if so, don't remove the nai
3288 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3289 NetworkRequest otherRequest = nai.requestAt(i);
3290 if (otherRequest.legacyType == nri.request.legacyType &&
3291 otherRequest.isRequest()) {
3292 if (DBG) log(" still have other legacy request - leaving");
3293 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003294 }
3295 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003296 }
3297
Erik Klineacdd6392016-07-07 16:50:58 +09003298 if (doRemove) {
3299 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003300 }
3301 }
Erik Klineacdd6392016-07-07 16:50:58 +09003302
3303 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3304 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3305 nri.request);
3306 }
3307 } else {
3308 // listens don't have a singular affectedNetwork. Check all networks to see
3309 // if this listen request applies and remove it.
3310 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3311 nai.removeRequest(nri.request.requestId);
3312 if (nri.request.networkCapabilities.hasSignalStrength() &&
3313 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3314 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3315 }
3316 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003317 }
3318 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003319
Lorenzo Colitti18660282016-07-04 12:55:44 +09003320 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003321 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003322 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003323 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003324 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003325 }
3326
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003327 @Override
lucasline252a742019-03-12 13:08:03 +08003328 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3329 enforceNetworkStackSettingsOrSetup();
3330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3331 encodeBool(accept), encodeBool(always), network));
3332 }
3333
3334 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003335 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003336 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003337 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3338 }
3339
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003340 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3341 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3342 " accept=" + accept + " always=" + always);
3343
3344 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3345 if (nai == null) {
3346 // Nothing to do.
3347 return;
3348 }
3349
3350 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003351 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003352 return;
3353 }
3354
3355 if (!nai.networkMisc.explicitlySelected) {
3356 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3357 }
3358
3359 if (accept != nai.networkMisc.acceptUnvalidated) {
3360 int oldScore = nai.getCurrentScore();
3361 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003362 // If network becomes partial connectivity and user already accepted to use this
3363 // network, we should respect the user's option and don't need to popup the
3364 // PARTIAL_CONNECTIVITY notification to user again.
3365 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003366 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003367 sendUpdatedScoreToFactories(nai);
3368 }
3369
3370 if (always) {
3371 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003372 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003373 }
3374
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003375 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003376 // Tell the NetworkAgent to not automatically reconnect to the network.
3377 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003378 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003379 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003380 }
3381
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003382 }
3383
lucasline252a742019-03-12 13:08:03 +08003384 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3385 boolean always) {
3386 if (DBG) {
3387 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3388 + " always=" + always);
3389 }
3390
3391 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3392 if (nai == null) {
3393 // Nothing to do.
3394 return;
3395 }
3396
3397 if (nai.lastValidated) {
3398 // The network validated while the dialog box was up. Take no action.
3399 return;
3400 }
3401
3402 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3403 nai.networkMisc.acceptPartialConnectivity = accept;
3404 }
3405
3406 // TODO: Use the current design or save the user choice into IpMemoryStore.
3407 if (always) {
3408 nai.asyncChannel.sendMessage(
3409 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3410 }
3411
3412 if (!accept) {
3413 // Tell the NetworkAgent to not automatically reconnect to the network.
3414 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3415 // Tear down the network.
3416 teardownUnneededNetwork(nai);
3417 } else {
lucaslin43338992019-03-20 18:21:59 +08003418 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3419 // result in a partial connectivity result which will be processed by
3420 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003421 try {
lucaslin43338992019-03-20 18:21:59 +08003422 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003423 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07003424 e.rethrowAsRuntimeException();
lucasline252a742019-03-12 13:08:03 +08003425 }
3426 }
3427 }
3428
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003429 private void handleSetAvoidUnvalidated(Network network) {
3430 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3431 if (nai == null || nai.lastValidated) {
3432 // Nothing to do. The network either disconnected or revalidated.
3433 return;
3434 }
3435 if (!nai.avoidUnvalidated) {
3436 int oldScore = nai.getCurrentScore();
3437 nai.avoidUnvalidated = true;
3438 rematchAllNetworksAndRequests(nai, oldScore);
3439 sendUpdatedScoreToFactories(nai);
3440 }
3441 }
3442
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003443 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003444 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003445 mHandler.sendMessageDelayed(
3446 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3447 PROMPT_UNVALIDATED_DELAY_MS);
3448 }
3449
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003450 @Override
3451 public void startCaptivePortalApp(Network network) {
3452 enforceConnectivityInternalPermission();
3453 mHandler.post(() -> {
3454 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3455 if (nai == null) return;
3456 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003457 try {
3458 nai.networkMonitor().launchCaptivePortalApp();
3459 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07003460 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003461 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003462 });
3463 }
3464
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003465 /**
3466 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3467 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003468 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003469 * @param appExtras Bundle to use as intent extras for the captive portal application.
3470 * Must be treated as opaque to avoid preventing the captive portal app to
3471 * update its arguments.
3472 */
3473 @Override
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003474 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003475 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3476
3477 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3478 appIntent.putExtras(appExtras);
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003479 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3480 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003481 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3482
3483 Binder.withCleanCallingIdentity(() ->
3484 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3485 }
3486
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003487 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3488 private final Network mNetwork;
3489
3490 private CaptivePortalImpl(Network network) {
3491 mNetwork = network;
3492 }
3493
3494 @Override
3495 public void appResponse(final int response) throws RemoteException {
3496 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3497 enforceSettingsPermission();
3498 }
3499
3500 // getNetworkAgentInfoForNetwork is thread-safe
3501 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3502 if (nai == null) return;
3503
3504 // nai.networkMonitor() is thread-safe
3505 final INetworkMonitor nm = nai.networkMonitor();
3506 if (nm == null) return;
3507
3508 final long token = Binder.clearCallingIdentity();
3509 try {
3510 nm.notifyCaptivePortalAppFinished(response);
3511 } finally {
3512 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3513 Binder.restoreCallingIdentity(token);
3514 }
3515 }
3516
3517 @Override
3518 public void logEvent(int eventId, String packageName) {
3519 enforceSettingsPermission();
3520
3521 new MetricsLogger().action(eventId, packageName);
3522 }
3523 }
3524
Hugo Benichic8e9e122016-09-14 23:23:08 +00003525 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003526 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003527 }
3528
Remi NGUYEN VAN24ec3ff2019-03-22 17:16:52 +09003529 /**
3530 * Return whether the device should maintain continuous, working connectivity by switching away
3531 * from WiFi networks having no connectivity.
3532 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3533 */
3534 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003535 if (!checkNetworkStackPermission()) {
3536 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3537 }
3538 return avoidBadWifi();
3539 }
3540
3541
Erik Kline065ab6e2016-10-02 18:02:14 +09003542 private void rematchForAvoidBadWifiUpdate() {
3543 rematchAllNetworksAndRequests(null, 0);
3544 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3545 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3546 sendUpdatedScoreToFactories(nai);
3547 }
3548 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003549 }
3550
Erik Kline065ab6e2016-10-02 18:02:14 +09003551 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003552 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003553 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003554 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003555 if (!configRestrict) {
3556 pw.println("Bad Wi-Fi avoidance: unrestricted");
3557 return;
3558 }
3559
3560 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3561 pw.increaseIndent();
3562 pw.println("Config restrict: " + configRestrict);
3563
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003564 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003565 String description;
3566 // Can't use a switch statement because strings are legal case labels, but null is not.
3567 if ("0".equals(value)) {
3568 description = "get stuck";
3569 } else if (value == null) {
3570 description = "prompt";
3571 } else if ("1".equals(value)) {
3572 description = "avoid";
3573 } else {
3574 description = value + " (?)";
3575 }
3576 pw.println("User setting: " + description);
3577 pw.println("Network overrides:");
3578 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003579 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003580 if (nai.avoidUnvalidated) {
3581 pw.println(nai.name());
3582 }
3583 }
3584 pw.decreaseIndent();
3585 pw.decreaseIndent();
3586 }
3587
lucaslind2e045e02019-01-24 15:55:30 +08003588 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003589 final String action;
3590 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003591 case LOGGED_IN:
3592 action = Settings.ACTION_WIFI_SETTINGS;
3593 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3594 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3595 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3596 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003597 case NO_INTERNET:
3598 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3599 break;
3600 case LOST_INTERNET:
3601 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3602 break;
lucasline252a742019-03-12 13:08:03 +08003603 case PARTIAL_CONNECTIVITY:
3604 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3605 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003606 default:
3607 Slog.wtf(TAG, "Unknown notification type " + type);
3608 return;
3609 }
3610
3611 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003612 if (type != NotificationType.LOGGED_IN) {
3613 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3614 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3615 intent.setClassName("com.android.settings",
3616 "com.android.settings.wifi.WifiNoInternetDialog");
3617 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003618
3619 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3620 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3621 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3622 }
3623
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003624 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003625 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003626 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3627
lucasline252a742019-03-12 13:08:03 +08003628 // Only prompt if the network is unvalidated or network has partial internet connectivity
3629 // and was explicitly selected by the user, and if we haven't already been told to switch
3630 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3631 // because we're already prompting the user to sign in.
3632 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3633 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003634 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3635 // we should reevaluate how to handle acceptPartialConnectivity when network just
3636 // connected.
lucasline252a742019-03-12 13:08:03 +08003637 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003638 return;
3639 }
lucasline252a742019-03-12 13:08:03 +08003640 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3641 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3642 // popup the notification immediately when the network is partial connectivity.
3643 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003644 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003645 } else {
3646 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3647 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003648 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003649
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003650 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3651 NetworkCapabilities nc = nai.networkCapabilities;
3652 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003653
lucasline252a742019-03-12 13:08:03 +08003654 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3655 return;
3656 }
3657
3658 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003659 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003660 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003661 }
3662
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003663 @Override
3664 public int getMultipathPreference(Network network) {
3665 enforceAccessPermission();
3666
3667 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003668 if (nai != null && nai.networkCapabilities
3669 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003670 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3671 }
3672
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003673 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3674 if (networkPreference != null) {
3675 return networkPreference;
3676 }
3677
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003678 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3679 }
3680
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003681 @Override
3682 public NetworkRequest getDefaultRequest() {
3683 return mDefaultRequest;
3684 }
3685
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003686 private class InternalHandler extends Handler {
3687 public InternalHandler(Looper looper) {
3688 super(looper);
3689 }
3690
3691 @Override
3692 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003693 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003694 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003695 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003696 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003697 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003698 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003699 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003700 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003701 break;
3702 }
Jason Monkdecd2952013-10-10 14:02:51 -04003703 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003704 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003705 break;
3706 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003707 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003708 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3709 break;
3710 }
3711 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3712 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003713 break;
3714 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003715 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003716 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3717 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3718 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003719 break;
3720 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003721 case EVENT_REGISTER_NETWORK_REQUEST:
3722 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003723 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003724 break;
3725 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003726 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3727 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003728 handleRegisterNetworkRequestWithIntent(msg);
3729 break;
3730 }
Erik Kline57faba92015-11-25 12:49:38 +09003731 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3732 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3733 handleTimedOutNetworkRequest(nri);
3734 break;
3735 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003736 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3737 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3738 break;
3739 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003740 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenae574a82019-01-08 12:09:18 -08003741 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3742 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003743 break;
3744 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003745 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003746 Network network = (Network) msg.obj;
3747 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003748 break;
3749 }
lucasline252a742019-03-12 13:08:03 +08003750 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3751 Network network = (Network) msg.obj;
3752 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3753 toBool(msg.arg2));
3754 break;
3755 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003756 case EVENT_SET_AVOID_UNVALIDATED: {
3757 handleSetAvoidUnvalidated((Network) msg.obj);
3758 break;
3759 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003760 case EVENT_PROMPT_UNVALIDATED: {
3761 handlePromptUnvalidated((Network) msg.obj);
3762 break;
3763 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003764 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3765 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003766 break;
3767 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003768 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003769 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003770 mKeepaliveTracker.handleStartKeepalive(msg);
3771 break;
3772 }
3773 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003774 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003775 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3776 int slot = msg.arg1;
3777 int reason = msg.arg2;
3778 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3779 break;
3780 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003781 case EVENT_SYSTEM_READY: {
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003782 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003783 break;
3784 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003785 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003786 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003787 break;
3788 }
Erik Klinea24d4592018-01-11 21:07:29 +09003789 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3790 handlePrivateDnsSettingsChanged();
3791 break;
dalyk7301aa42018-03-05 12:42:22 -05003792 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3793 handlePrivateDnsValidationUpdate(
3794 (PrivateDnsValidationUpdate) msg.obj);
3795 break;
junyulai05986c62018-08-07 19:50:45 +08003796 case EVENT_UID_RULES_CHANGED:
3797 handleUidRulesChanged(msg.arg1, msg.arg2);
3798 break;
3799 case EVENT_DATA_SAVER_CHANGED:
3800 handleRestrictBackgroundChanged(toBool(msg.arg1));
3801 break;
lucaslind2e045e02019-01-24 15:55:30 +08003802 case EVENT_TIMEOUT_NOTIFICATION:
3803 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3804 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
3806 }
3807 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003808
3809 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003810 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003811 public int tether(String iface, String callerPkg) {
3812 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003813 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003814 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003815 } else {
3816 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3817 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003818 }
3819
3820 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003821 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003822 public int untether(String iface, String callerPkg) {
3823 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003824
3825 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003826 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003827 } else {
3828 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3829 }
3830 }
3831
3832 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003833 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003834 public int getLastTetherError(String iface) {
3835 enforceTetherAccessPermission();
3836
3837 if (isTetheringSupported()) {
3838 return mTethering.getLastTetherError(iface);
3839 } else {
3840 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3841 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003842 }
3843
3844 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003845 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003846 public String[] getTetherableUsbRegexs() {
3847 enforceTetherAccessPermission();
3848 if (isTetheringSupported()) {
3849 return mTethering.getTetherableUsbRegexs();
3850 } else {
3851 return new String[0];
3852 }
3853 }
3854
Lorenzo Colitti18660282016-07-04 12:55:44 +09003855 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003856 public String[] getTetherableWifiRegexs() {
3857 enforceTetherAccessPermission();
3858 if (isTetheringSupported()) {
3859 return mTethering.getTetherableWifiRegexs();
3860 } else {
3861 return new String[0];
3862 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003863 }
3864
Lorenzo Colitti18660282016-07-04 12:55:44 +09003865 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003866 public String[] getTetherableBluetoothRegexs() {
3867 enforceTetherAccessPermission();
3868 if (isTetheringSupported()) {
3869 return mTethering.getTetherableBluetoothRegexs();
3870 } else {
3871 return new String[0];
3872 }
3873 }
3874
Lorenzo Colitti18660282016-07-04 12:55:44 +09003875 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003876 public int setUsbTethering(boolean enable, String callerPkg) {
3877 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003878 if (isTetheringSupported()) {
3879 return mTethering.setUsbTethering(enable);
3880 } else {
3881 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3882 }
3883 }
3884
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003885 // TODO - move iface listing, queries, etc to new module
3886 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003887 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003888 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003889 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003890 return mTethering.getTetherableIfaces();
3891 }
3892
Lorenzo Colitti18660282016-07-04 12:55:44 +09003893 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003894 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003895 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003896 return mTethering.getTetheredIfaces();
3897 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003898
Lorenzo Colitti18660282016-07-04 12:55:44 +09003899 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003900 public String[] getTetheringErroredIfaces() {
3901 enforceTetherAccessPermission();
3902 return mTethering.getErroredIfaces();
3903 }
3904
Lorenzo Colitti18660282016-07-04 12:55:44 +09003905 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003906 public String[] getTetheredDhcpRanges() {
3907 enforceConnectivityInternalPermission();
3908 return mTethering.getTetheredDhcpRanges();
3909 }
3910
Udam Saini0e94c362017-06-07 12:06:28 -07003911 @Override
3912 public boolean isTetheringSupported(String callerPkg) {
3913 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3914 return isTetheringSupported();
3915 }
3916
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003917 // if ro.tether.denied = true we default to no tethering
3918 // gservices could set the secure setting to 1 though to enable it on a build where it
3919 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003920 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003921 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3922 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3923 Settings.Global.TETHER_SUPPORTED, defaultVal));
3924 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003925 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003926
3927 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3928 boolean adminUser = false;
3929 final long token = Binder.clearCallingIdentity();
3930 try {
3931 adminUser = mUserManager.isAdminUser();
3932 } finally {
3933 Binder.restoreCallingIdentity(token);
3934 }
3935
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003936 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003937 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003938
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003939 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003940 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3941 String callerPkg) {
3942 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003943 if (!isTetheringSupported()) {
3944 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3945 return;
3946 }
3947 mTethering.startTethering(type, receiver, showProvisioningUi);
3948 }
3949
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003950 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003951 public void stopTethering(int type, String callerPkg) {
3952 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003953 mTethering.stopTethering(type);
3954 }
3955
markchienf2731272019-01-16 17:44:13 +08003956 /**
3957 * Get the latest value of the tethering entitlement check.
3958 *
3959 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3960 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3961 * if it's really needed.
3962 */
3963 @Override
markchien9554abf2019-03-06 16:25:00 +08003964 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003965 boolean showEntitlementUi, String callerPkg) {
3966 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003967 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003968 }
3969
markchien6ea34542019-02-27 14:56:11 +08003970 /** Register tethering event callback. */
3971 @Override
3972 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3973 String callerPkg) {
3974 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3975 mTethering.registerTetheringEventCallback(callback);
3976 }
3977
3978 /** Unregister tethering event callback. */
3979 @Override
3980 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3981 String callerPkg) {
3982 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3983 mTethering.unregisterTetheringEventCallback(callback);
3984 }
3985
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003986 // Called when we lose the default network and have no replacement yet.
3987 // This will automatically be cleared after X seconds or a new default network
3988 // becomes CONNECTED, whichever happens first. The timer is started by the
3989 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003990 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003991 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003992 if (mNetTransitionWakeLock.isHeld()) {
3993 return;
3994 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003995 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003996 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3997 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003998 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003999 mWakelockLogs.log("ACQUIRE for " + forWhom);
4000 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4001 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07004002 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07004003
Hugo Benichi4c31b342017-03-30 23:18:10 +09004004 // Called when we gain a new default network to release the network transition wakelock in a
4005 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4006 // message is cancelled.
4007 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004008 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09004009 if (!mNetTransitionWakeLock.isHeld()) {
4010 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004011 }
4012 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004013 // Cancel self timeout on wakelock hold.
4014 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4015 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4016 mHandler.sendMessageDelayed(msg, 1000);
4017 }
4018
4019 // Called when either message of ensureNetworkTransitionWakelock or
4020 // scheduleReleaseNetworkTransitionWakelock is processed.
4021 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4022 String event = eventName(eventId);
4023 synchronized (this) {
4024 if (!mNetTransitionWakeLock.isHeld()) {
4025 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4026 Slog.w(TAG, "expected Net Transition WakeLock to be held");
4027 return;
4028 }
4029 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09004030 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4031 mTotalWakelockDurationMs += lockDuration;
4032 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4033 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004034 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004035 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004036 }
4037
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004038 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004039 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004040 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004041 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004042 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004043 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004044 }
4045
Lorenzo Colitti18660282016-07-04 12:55:44 +09004046 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004047 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004048 enforceAccessPermission();
4049 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004050 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004051 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004052 mHandler.sendMessage(
4053 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4054 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004055
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004056 private void handleReportNetworkConnectivity(
4057 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004058 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004059 if (network == null) {
4060 nai = getDefaultNetwork();
4061 } else {
4062 nai = getNetworkAgentInfoForNetwork(network);
4063 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004064 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4065 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4066 return;
4067 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004068 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004069 if (hasConnectivity == nai.lastValidated) {
4070 return;
4071 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004072 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004073 int netid = nai.network.netId;
4074 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004075 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004076 // Validating a network that has not yet connected could result in a call to
4077 // rematchNetworkAndRequests() which is not meant to work on such networks.
4078 if (!nai.everConnected) {
4079 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004080 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004081 LinkProperties lp = getLinkProperties(nai);
4082 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4083 return;
4084 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004085 try {
4086 nai.networkMonitor().forceReevaluation(uid);
4087 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07004088 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004089 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 }
4091
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004092 /**
4093 * Returns information about the proxy a certain network is using. If given a null network, it
4094 * it will return the proxy for the bound network for the caller app or the default proxy if
4095 * none.
4096 *
4097 * @param network the network we want to get the proxy information for.
4098 * @return Proxy information if a network has a proxy configured, or otherwise null.
4099 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004100 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004101 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004102 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004103 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004104 if (network == null) {
4105 // Get the network associated with the calling UID.
4106 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4107 true);
4108 if (activeNetwork == null) {
4109 return null;
4110 }
4111 return getLinkPropertiesProxyInfo(activeNetwork);
4112 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4113 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4114 // caller may not have.
4115 return getLinkPropertiesProxyInfo(network);
4116 }
4117 // No proxy info available if the calling UID does not have network access.
4118 return null;
4119 }
4120
4121 @VisibleForTesting
4122 protected boolean queryUserAccess(int uid, int netId) {
4123 return NetworkUtils.queryUserAccess(uid, netId);
4124 }
4125
4126 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004127 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4128 if (nai == null) return null;
4129 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004130 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4131 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004132 }
4133 }
4134
Chalard Jean3c443fc2018-06-07 18:37:59 +09004135 @Override
4136 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004137 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004138 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004139 }
4140
Chalard Jean5afbc832018-06-07 18:02:37 +09004141 @Override
4142 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004143 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004144 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004145 }
4146
Jason Monk207900c2014-04-25 15:00:09 -04004147 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004148 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004149 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004150 proxy = null;
4151 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004152 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004153 }
4154
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004155 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4156 // when any network changes proxy.
4157 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4158 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004159 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004160 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4161 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4162
Chalard Jean4949dd72018-06-07 17:41:29 +09004163 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004164 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004165 }
4166 }
4167
Robert Greenwalt434203a2010-10-11 16:00:27 -07004168 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004169 final private HashMap<Uri, Integer> mUriEventMap;
4170 final private Context mContext;
4171 final private Handler mHandler;
4172
4173 SettingsObserver(Context context, Handler handler) {
4174 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004175 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004176 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004177 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004178 }
4179
Erik Klineda4bfa82015-04-30 12:58:40 +09004180 void observe(Uri uri, int what) {
4181 mUriEventMap.put(uri, what);
4182 final ContentResolver resolver = mContext.getContentResolver();
4183 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004184 }
4185
4186 @Override
4187 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004188 Slog.wtf(TAG, "Should never be reached.");
4189 }
4190
4191 @Override
4192 public void onChange(boolean selfChange, Uri uri) {
4193 final Integer what = mUriEventMap.get(uri);
4194 if (what != null) {
4195 mHandler.obtainMessage(what.intValue()).sendToTarget();
4196 } else {
4197 loge("No matching event to send for URI=" + uri);
4198 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004199 }
4200 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004201
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004202 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004203 Slog.d(TAG, s);
4204 }
4205
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004206 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004207 Slog.e(TAG, s);
4208 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004209
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004210 private static void loge(String s, Throwable t) {
4211 Slog.e(TAG, s, t);
4212 }
4213
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004214 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004215 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004216 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4217 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4218 *
4219 * @param oldPackage Package name of the application which currently controls VPN, which will
4220 * be replaced. If there is no such application, this should should either be
4221 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4222 * @param newPackage Package name of the application which should gain control of VPN, or
4223 * {@code null} to disable.
4224 * @param userId User for whom to prepare the new VPN.
4225 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004226 * @hide
4227 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004228 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004229 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4230 int userId) {
4231 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004232
Hugo Benichi20035e02017-04-26 14:53:28 +09004233 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004234 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004235 Vpn vpn = mVpns.get(userId);
4236 if (vpn != null) {
4237 return vpn.prepare(oldPackage, newPackage);
4238 } else {
4239 return false;
4240 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004241 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004242 }
4243
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004244 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004245 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4246 * This method is used by system-privileged apps.
4247 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4248 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4249 *
4250 * @param packageName The package for which authorization state should change.
4251 * @param userId User for whom {@code packageName} is installed.
4252 * @param authorized {@code true} if this app should be able to start a VPN connection without
4253 * explicit user approval, {@code false} if not.
4254 *
Jeff Davidson05542602014-08-11 14:07:27 -07004255 * @hide
4256 */
4257 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004258 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4259 enforceCrossUserPermission(userId);
4260
Hugo Benichi20035e02017-04-26 14:53:28 +09004261 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004262 Vpn vpn = mVpns.get(userId);
4263 if (vpn != null) {
4264 vpn.setPackageAuthorization(packageName, authorized);
4265 }
Jeff Davidson05542602014-08-11 14:07:27 -07004266 }
4267 }
4268
4269 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004270 * Configure a TUN interface and return its file descriptor. Parameters
4271 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004272 * and not available in ConnectivityManager. Permissions are checked in
4273 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004274 * @hide
4275 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004276 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004277 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004278 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004279 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004280 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004281 return mVpns.get(user).establish(config);
4282 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004283 }
4284
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004285 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004286 * Start legacy VPN, controlling native daemons as needed. Creates a
4287 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004288 */
4289 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004290 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004291 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004292 final LinkProperties egress = getActiveLinkProperties();
4293 if (egress == null) {
4294 throw new IllegalStateException("Missing active network connection");
4295 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004296 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004297 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004298 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4299 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004300 }
4301
4302 /**
4303 * Return the information of the ongoing legacy VPN. This method is used
4304 * by VpnSettings and not available in ConnectivityManager. Permissions
4305 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004306 */
4307 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004308 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4309 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004310
Hugo Benichi20035e02017-04-26 14:53:28 +09004311 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004312 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004313 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004314 }
4315
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004316 /**
Varun Anand02c50ef2019-02-07 14:13:13 -08004317 * Return the information of all ongoing VPNs.
4318 *
4319 * <p>This method is used to update NetworkStatsService.
4320 *
4321 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004322 */
Varun Anand02c50ef2019-02-07 14:13:13 -08004323 private VpnInfo[] getAllVpnInfo() {
4324 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004325 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004326 if (mLockdownEnabled) {
4327 return new VpnInfo[0];
4328 }
4329
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004330 List<VpnInfo> infoList = new ArrayList<>();
4331 for (int i = 0; i < mVpns.size(); i++) {
4332 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4333 if (info != null) {
4334 infoList.add(info);
4335 }
4336 }
4337 return infoList.toArray(new VpnInfo[infoList.size()]);
4338 }
4339 }
4340
4341 /**
4342 * @return VPN information for accounting, or null if we can't retrieve all required
4343 * information, e.g primary underlying iface.
4344 */
4345 @Nullable
4346 private VpnInfo createVpnInfo(Vpn vpn) {
4347 VpnInfo info = vpn.getVpnInfo();
4348 if (info == null) {
4349 return null;
4350 }
4351 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4352 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4353 // the underlyingNetworks list.
4354 if (underlyingNetworks == null) {
4355 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4356 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4357 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4358 }
4359 } else if (underlyingNetworks.length > 0) {
4360 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4361 if (linkProperties != null) {
4362 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4363 }
4364 }
4365 return info.primaryUnderlyingIface == null ? null : info;
4366 }
4367
4368 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004369 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4370 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004371 * Permissions are checked in Vpn class.
4372 * @hide
4373 */
4374 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004375 public VpnConfig getVpnConfig(int userId) {
4376 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004377 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004378 Vpn vpn = mVpns.get(userId);
4379 if (vpn != null) {
4380 return vpn.getVpnConfig();
4381 } else {
4382 return null;
4383 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004384 }
4385 }
4386
Chalard Jean6b65ec72018-05-18 22:02:56 +09004387 /**
4388 * Ask all VPN objects to recompute and update their capabilities.
4389 *
4390 * When underlying networks change, VPNs may have to update capabilities to reflect things
4391 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4392 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4393 * handler thread through their agent, this is asynchronous. When the capabilities objects
4394 * are computed they will be up-to-date as they are computed synchronously from here and
4395 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004396 */
4397 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004398 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004399 synchronized (mVpns) {
4400 for (int i = 0; i < mVpns.size(); i++) {
4401 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004402 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4403 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004404 }
4405 }
4406 }
4407
Varun Anand4fa80e82019-02-06 10:13:38 -08004408 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4409 ensureRunningOnConnectivityServiceThread();
4410 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4411 if (vpnNai == null || nc == null) {
4412 return;
4413 }
4414 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4415 }
4416
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004417 @Override
4418 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004419 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4420 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4421 return false;
4422 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004423
Hugo Benichi69744342017-11-27 10:57:16 +09004424 synchronized (mVpns) {
4425 // Tear down existing lockdown if profile was removed
4426 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4427 if (mLockdownEnabled) {
4428 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4429 if (profileTag == null) {
4430 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4431 return false;
4432 }
4433 String profileName = new String(profileTag);
4434 final VpnProfile profile = VpnProfile.decode(
4435 profileName, mKeyStore.get(Credentials.VPN + profileName));
4436 if (profile == null) {
4437 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4438 setLockdownTracker(null);
4439 return true;
4440 }
4441 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004442 Vpn vpn = mVpns.get(user);
4443 if (vpn == null) {
4444 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4445 return false;
4446 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004447 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004448 } else {
4449 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004450 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004451 }
4452
4453 return true;
4454 }
4455
4456 /**
4457 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4458 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4459 */
Hugo Benichi69744342017-11-27 10:57:16 +09004460 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004461 private void setLockdownTracker(LockdownVpnTracker tracker) {
4462 // Shutdown any existing tracker
4463 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004464 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4465 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004466 mLockdownTracker = null;
4467 if (existing != null) {
4468 existing.shutdown();
4469 }
4470
Robin Leec3736bc2017-03-10 16:19:54 +00004471 if (tracker != null) {
4472 mLockdownTracker = tracker;
4473 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004474 }
4475 }
4476
Hugo Benichi69744342017-11-27 10:57:16 +09004477 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004478 private void throwIfLockdownEnabled() {
4479 if (mLockdownEnabled) {
4480 throw new IllegalStateException("Unavailable in lockdown mode");
4481 }
4482 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004483
Robin Lee244ce8e2016-01-05 18:03:46 +00004484 /**
Robin Lee17e61832016-05-09 13:46:28 +01004485 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4486 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004487 *
Robin Lee17e61832016-05-09 13:46:28 +01004488 * @return {@code true} if the service was started, the service was already connected, or there
4489 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004490 */
Robin Lee17e61832016-05-09 13:46:28 +01004491 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004492 synchronized (mVpns) {
4493 Vpn vpn = mVpns.get(userId);
4494 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004495 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004496 // exists already.
4497 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4498 return false;
4499 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004500
Robin Lee812800c2016-05-13 15:38:08 +01004501 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004502 }
4503 }
4504
4505 @Override
Charles He36738632017-05-15 17:07:18 +01004506 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4507 enforceSettingsPermission();
4508 enforceCrossUserPermission(userId);
4509
4510 synchronized (mVpns) {
4511 Vpn vpn = mVpns.get(userId);
4512 if (vpn == null) {
4513 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4514 return false;
4515 }
4516 return vpn.isAlwaysOnPackageSupported(packageName);
4517 }
4518 }
4519
4520 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004521 public boolean setAlwaysOnVpnPackage(
4522 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4523 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004524 enforceCrossUserPermission(userId);
4525
Robin Lee244ce8e2016-01-05 18:03:46 +00004526 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004527 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4528 if (LockdownVpnTracker.isEnabled()) {
4529 return false;
4530 }
4531
Robin Lee244ce8e2016-01-05 18:03:46 +00004532 Vpn vpn = mVpns.get(userId);
4533 if (vpn == null) {
4534 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4535 return false;
4536 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004537 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004538 return false;
4539 }
Robin Lee17e61832016-05-09 13:46:28 +01004540 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004541 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004542 return false;
4543 }
4544 }
4545 return true;
4546 }
4547
4548 @Override
4549 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004550 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004551 enforceCrossUserPermission(userId);
4552
4553 synchronized (mVpns) {
4554 Vpn vpn = mVpns.get(userId);
4555 if (vpn == null) {
4556 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4557 return null;
4558 }
4559 return vpn.getAlwaysOnPackage();
4560 }
4561 }
4562
Wink Savilleab9321d2013-06-29 21:10:57 -07004563 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004564 public boolean isVpnLockdownEnabled(int userId) {
4565 enforceControlAlwaysOnVpnPermission();
4566 enforceCrossUserPermission(userId);
4567
4568 synchronized (mVpns) {
4569 Vpn vpn = mVpns.get(userId);
4570 if (vpn == null) {
4571 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4572 return false;
4573 }
4574 return vpn.getLockdown();
4575 }
4576 }
4577
4578 @Override
4579 public List<String> getVpnLockdownWhitelist(int userId) {
4580 enforceControlAlwaysOnVpnPermission();
4581 enforceCrossUserPermission(userId);
4582
4583 synchronized (mVpns) {
4584 Vpn vpn = mVpns.get(userId);
4585 if (vpn == null) {
4586 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4587 return null;
4588 }
4589 return vpn.getLockdownWhitelist();
4590 }
4591 }
4592
4593 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004594 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004595 // TODO: Remove? Any reason to trigger a provisioning check?
4596 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004597 }
4598
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004599 /** Location to an updatable file listing carrier provisioning urls.
4600 * An example:
4601 *
4602 * <?xml version="1.0" encoding="utf-8"?>
4603 * <provisioningUrls>
4604 * <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 -07004605 * </provisioningUrls>
4606 */
4607 private static final String PROVISIONING_URL_PATH =
4608 "/data/misc/radio/provisioning_urls.xml";
4609 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004610
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004611 /** XML tag for root element. */
4612 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4613 /** XML tag for individual url */
4614 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004615 /** XML attribute for mcc */
4616 private static final String ATTR_MCC = "mcc";
4617 /** XML attribute for mnc */
4618 private static final String ATTR_MNC = "mnc";
4619
Paul Jensen434dde82015-06-11 09:43:30 -04004620 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004621 FileReader fileReader = null;
4622 XmlPullParser parser = null;
4623 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004624
4625 try {
4626 fileReader = new FileReader(mProvisioningUrlFile);
4627 parser = Xml.newPullParser();
4628 parser.setInput(fileReader);
4629 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4630
4631 while (true) {
4632 XmlUtils.nextElement(parser);
4633
4634 String element = parser.getName();
4635 if (element == null) break;
4636
Paul Jensen434dde82015-06-11 09:43:30 -04004637 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004638 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4639 try {
4640 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4641 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4642 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4643 parser.next();
4644 if (parser.getEventType() == XmlPullParser.TEXT) {
4645 return parser.getText();
4646 }
4647 }
4648 }
4649 } catch (NumberFormatException e) {
4650 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4651 }
4652 }
4653 }
4654 return null;
4655 } catch (FileNotFoundException e) {
4656 loge("Carrier Provisioning Urls file not found");
4657 } catch (XmlPullParserException e) {
4658 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4659 } catch (IOException e) {
4660 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4661 } finally {
4662 if (fileReader != null) {
4663 try {
4664 fileReader.close();
4665 } catch (IOException e) {}
4666 }
4667 }
4668 return null;
4669 }
4670
Wink Saville42d4f082013-07-20 20:31:59 -07004671 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004672 public String getMobileProvisioningUrl() {
4673 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004674 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004675 if (TextUtils.isEmpty(url)) {
4676 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004677 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004678 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004679 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004680 }
Wink Saville8cf35602013-07-10 23:00:07 -07004681 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004682 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004683 String phoneNumber = mTelephonyManager.getLine1Number();
4684 if (TextUtils.isEmpty(phoneNumber)) {
4685 phoneNumber = "0000000000";
4686 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004687 url = String.format(url,
4688 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4689 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004690 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004691 }
4692
Wink Savilleab9321d2013-06-29 21:10:57 -07004693 return url;
4694 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004695
Wink Saville948282b2013-08-29 08:55:16 -07004696 @Override
4697 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004698 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004699 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004700 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4701 return;
4702 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004703 final long ident = Binder.clearCallingIdentity();
4704 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004705 // Concatenate the range of types onto the range of NetIDs.
4706 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4707 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004708 } finally {
4709 Binder.restoreCallingIdentity(ident);
4710 }
Wink Saville948282b2013-08-29 08:55:16 -07004711 }
Wink Saville7788c612013-08-29 14:57:08 -07004712
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004713 @Override
4714 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004715 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004716 final long ident = Binder.clearCallingIdentity();
4717 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004718 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004719 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004720 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4721 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004722 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004723 } finally {
4724 Binder.restoreCallingIdentity(ident);
4725 }
4726 }
4727
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004728 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004729 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004730 Vpn userVpn = mVpns.get(userId);
4731 if (userVpn != null) {
4732 loge("Starting user already has a VPN");
4733 return;
4734 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004735 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004736 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004737 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4738 updateLockdownVpn();
4739 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004740 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004741 }
4742
4743 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004744 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004745 Vpn userVpn = mVpns.get(userId);
4746 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004747 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004748 return;
4749 }
Robin Lee17e61832016-05-09 13:46:28 +01004750 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004751 mVpns.delete(userId);
4752 }
4753 }
4754
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004755 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004756 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004757 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004758 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004759 final int vpnsSize = mVpns.size();
4760 for (int i = 0; i < vpnsSize; i++) {
4761 Vpn vpn = mVpns.valueAt(i);
4762 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004763 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4764 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004765 }
4766 }
4767 }
4768
4769 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004770 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004771 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004772 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004773 final int vpnsSize = mVpns.size();
4774 for (int i = 0; i < vpnsSize; i++) {
4775 Vpn vpn = mVpns.valueAt(i);
4776 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004777 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4778 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004779 }
4780 }
4781 }
4782
junyulai2454b692018-11-01 17:16:31 +08004783 private void onPackageAdded(String packageName, int uid) {
4784 if (TextUtils.isEmpty(packageName) || uid < 0) {
4785 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4786 return;
4787 }
4788 mPermissionMonitor.onPackageAdded(packageName, uid);
4789 }
4790
junyulaiefb04d32018-11-12 22:39:30 +08004791 private void onPackageReplaced(String packageName, int uid) {
4792 if (TextUtils.isEmpty(packageName) || uid < 0) {
4793 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4794 return;
4795 }
4796 final int userId = UserHandle.getUserId(uid);
4797 synchronized (mVpns) {
4798 final Vpn vpn = mVpns.get(userId);
4799 if (vpn == null) {
4800 return;
4801 }
4802 // Legacy always-on VPN won't be affected since the package name is not set.
4803 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4804 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4805 + userId);
4806 vpn.startAlwaysOnVpn();
4807 }
4808 }
4809 }
4810
4811 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004812 if (TextUtils.isEmpty(packageName) || uid < 0) {
4813 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4814 return;
4815 }
4816 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004817
4818 final int userId = UserHandle.getUserId(uid);
4819 synchronized (mVpns) {
4820 final Vpn vpn = mVpns.get(userId);
4821 if (vpn == null) {
4822 return;
4823 }
4824 // Legacy always-on VPN won't be affected since the package name is not set.
4825 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4826 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4827 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004828 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004829 }
4830 }
junyulai2454b692018-11-01 17:16:31 +08004831 }
4832
Robin Lee89e7a692016-02-29 14:38:17 +00004833 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004834 synchronized (mVpns) {
4835 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4836 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4837 updateLockdownVpn();
4838 } else {
4839 startAlwaysOnVpn(userId);
4840 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004841 }
4842 }
4843
junyulai2454b692018-11-01 17:16:31 +08004844 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004845 @Override
4846 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004847 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004848 final String action = intent.getAction();
4849 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004850 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4851 final Uri packageData = intent.getData();
4852 final String packageName =
4853 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004854 if (userId == UserHandle.USER_NULL) return;
4855
Robin Lee323f29d2016-05-04 16:38:06 +01004856 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004857 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004858 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004859 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004860 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4861 onUserAdded(userId);
4862 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4863 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004864 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4865 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004866 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4867 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004868 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4869 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004870 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004871 final boolean isReplacing = intent.getBooleanExtra(
4872 Intent.EXTRA_REPLACING, false);
4873 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004874 }
4875 }
4876 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004877
Robin Lee95204e02017-01-27 11:59:22 +00004878 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4879 @Override
4880 public void onReceive(Context context, Intent intent) {
4881 // Try creating lockdown tracker, since user present usually means
4882 // unlocked keystore.
4883 updateLockdownVpn();
4884 mContext.unregisterReceiver(this);
4885 }
4886 };
4887
Chalard Jean4133a122018-06-04 13:33:12 +09004888 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4889 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004890
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004891 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4892 // Map from UID to number of NetworkRequests that UID has filed.
4893 @GuardedBy("mUidToNetworkRequestCount")
4894 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4895
Robert Greenwalta67be032014-05-16 15:49:14 -07004896 private static class NetworkFactoryInfo {
4897 public final String name;
4898 public final Messenger messenger;
4899 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004900 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004901
Chalard Jean08577fc2018-05-02 21:14:54 +09004902 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4903 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004904 this.name = name;
4905 this.messenger = messenger;
4906 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004907 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004908 }
4909 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004910
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004911 private void ensureNetworkRequestHasType(NetworkRequest request) {
4912 if (request.type == NetworkRequest.Type.NONE) {
4913 throw new IllegalArgumentException(
4914 "All NetworkRequests in ConnectivityService must have a type");
4915 }
4916 }
4917
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004918 /**
4919 * Tracks info about the requester.
4920 * Also used to notice when the calling process dies so we can self-expire
4921 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004922 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004924 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004925 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004926 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004927 final int mPid;
4928 final int mUid;
4929 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004931 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004932 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004933 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004934 mPendingIntent = pi;
4935 messenger = null;
4936 mBinder = null;
4937 mPid = getCallingPid();
4938 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004939 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004940 }
4941
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004942 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004943 super();
4944 messenger = m;
4945 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004946 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004947 mBinder = binder;
4948 mPid = getCallingPid();
4949 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004950 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004951 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004952
4953 try {
4954 mBinder.linkToDeath(this, 0);
4955 } catch (RemoteException e) {
4956 binderDied();
4957 }
4958 }
4959
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004960 private void enforceRequestCountLimit() {
4961 synchronized (mUidToNetworkRequestCount) {
4962 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4963 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004964 throw new ServiceSpecificException(
4965 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004966 }
4967 mUidToNetworkRequestCount.put(mUid, networkRequests);
4968 }
4969 }
4970
Robert Greenwalt9258c642014-03-26 16:47:06 -07004971 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004972 if (mBinder != null) {
4973 mBinder.unlinkToDeath(this, 0);
4974 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004975 }
4976
4977 public void binderDied() {
4978 log("ConnectivityService NetworkRequestInfo binderDied(" +
4979 request + ", " + mBinder + ")");
4980 releaseNetworkRequest(request);
4981 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004982
4983 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004984 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004985 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004986 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004987 }
4988
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004989 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4990 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4991 if (badCapability != null) {
4992 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004993 }
4994 }
4995
paulhu3d67f532019-03-22 16:35:06 +08004996 // This checks that the passed capabilities either do not request a specific SSID/SignalStrength
4997 // , or the calling app has permission to do so.
Chalard Jeanb03a6222018-04-11 21:09:10 +09004998 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4999 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09005000 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09005001 throw new SecurityException("Insufficient permissions to request a specific SSID");
5002 }
paulhu3d67f532019-03-22 16:35:06 +08005003
5004 if (nc.hasSignalStrength()
5005 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5006 throw new SecurityException(
5007 "Insufficient permissions to request a specific signal strength");
5008 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09005009 }
5010
Erik Kline9d598e12015-07-13 16:37:51 +09005011 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09005012 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005013 synchronized (nai) {
5014 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5015 if (nri.request.networkCapabilities.hasSignalStrength() &&
5016 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
5017 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
5018 }
5019 }
5020 }
Chalard Jean4133a122018-06-04 13:33:12 +09005021 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005022 }
5023
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005024 private void updateSignalStrengthThresholds(
5025 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5026 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09005027 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005028 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
5029
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005030 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005031 String detail;
5032 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5033 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5034 } else {
5035 detail = reason;
5036 }
5037 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5038 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
5039 }
5040
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005041 nai.asyncChannel.sendMessage(
5042 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005043 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005044 }
5045
Etan Cohen859748f2017-04-03 17:42:34 -07005046 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5047 if (nc == null) {
5048 return;
5049 }
5050 NetworkSpecifier ns = nc.getNetworkSpecifier();
5051 if (ns == null) {
5052 return;
5053 }
5054 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5055 ns.assertValidFromUid(Binder.getCallingUid());
5056 }
5057
Robert Greenwalt9258c642014-03-26 16:47:06 -07005058 @Override
5059 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005060 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005061 final NetworkRequest.Type type = (networkCapabilities == null)
5062 ? NetworkRequest.Type.TRACK_DEFAULT
5063 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005064 // If the requested networkCapabilities is null, take them instead from
5065 // the default network request. This allows callers to keep track of
5066 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005067 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005068 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005069 enforceAccessPermission();
5070 } else {
5071 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5072 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005073 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5074 // of the app when the request is filed, but we never change the request if the app
5075 // changes network state. http://b/29964605
5076 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005077 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005078 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005079 ensureSufficientPermissionsForRequest(networkCapabilities,
5080 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005081 // Set the UID range for this request to the single UID of the requester, or to an empty
5082 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005083 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5084 // are no visible methods to set the UIDs, an app could use reflection to try and get
5085 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005086 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005087
Etan Cohenba07c8c2017-02-05 10:42:27 -08005088 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005089 throw new IllegalArgumentException("Bad timeout specified");
5090 }
Etan Cohen859748f2017-04-03 17:42:34 -07005091 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005092
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005093 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005094 nextNetworkRequestId(), type);
5095 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005096 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005097
5098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005099 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005100 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005101 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005102 }
5103 return networkRequest;
5104 }
5105
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005106 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005107 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005108 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005109 } else {
5110 enforceChangePermission();
5111 }
5112 }
5113
fenglub15e72b2015-03-20 11:29:56 -07005114 @Override
fengludb571472015-04-21 17:12:05 -07005115 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005116 enforceAccessPermission();
5117 NetworkAgentInfo nai = null;
5118 if (network == null) {
5119 return false;
5120 }
5121 synchronized (mNetworkForNetId) {
5122 nai = mNetworkForNetId.get(network.netId);
5123 }
5124 if (nai != null) {
5125 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005126 synchronized (mBandwidthRequests) {
5127 final int uid = Binder.getCallingUid();
5128 Integer uidReqs = mBandwidthRequests.get(uid);
5129 if (uidReqs == null) {
5130 uidReqs = new Integer(0);
5131 }
5132 mBandwidthRequests.put(uid, ++uidReqs);
5133 }
fenglub15e72b2015-03-20 11:29:56 -07005134 return true;
5135 }
5136 return false;
5137 }
5138
Felipe Lemeee27cab2016-06-20 16:36:29 -07005139 private boolean isSystem(int uid) {
5140 return uid < Process.FIRST_APPLICATION_UID;
5141 }
fenglub15e72b2015-03-20 11:29:56 -07005142
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005143 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005144 final int uid = Binder.getCallingUid();
5145 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005146 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005147 return;
5148 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005149 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5150 // Policy already enforced.
5151 return;
5152 }
5153 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5154 // If UID is restricted, don't allow them to bring up metered APNs.
5155 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005156 }
5157 }
5158
Robert Greenwalt9258c642014-03-26 16:47:06 -07005159 @Override
5160 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5161 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005162 checkNotNull(operation, "PendingIntent cannot be null.");
5163 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5164 enforceNetworkRequestPermissions(networkCapabilities);
5165 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005166 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005167 ensureSufficientPermissionsForRequest(networkCapabilities,
5168 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005169 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005170 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005171
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005172 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005173 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5174 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005175 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005176 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5177 nri));
5178 return networkRequest;
5179 }
5180
Jeremy Joslin79294842014-12-03 17:15:28 -08005181 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5182 mHandler.sendMessageDelayed(
5183 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5184 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5185 }
5186
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005187 @Override
5188 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005189 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005190 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5191 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005192 }
5193
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005194 // In order to implement the compatibility measure for pre-M apps that call
5195 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5196 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5197 // This ensures it has permission to do so.
5198 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5199 if (nc == null) {
5200 return false;
5201 }
5202 int[] transportTypes = nc.getTransportTypes();
5203 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5204 return false;
5205 }
5206 try {
5207 mContext.enforceCallingOrSelfPermission(
5208 android.Manifest.permission.ACCESS_WIFI_STATE,
5209 "ConnectivityService");
5210 } catch (SecurityException e) {
5211 return false;
5212 }
5213 return true;
5214 }
5215
Robert Greenwalt9258c642014-03-26 16:47:06 -07005216 @Override
5217 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5218 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005219 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5220 enforceAccessPermission();
5221 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005222
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005223 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005224 ensureSufficientPermissionsForRequest(networkCapabilities,
5225 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005226 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005227 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5228 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5229 // onLost and onAvailable callbacks when networks move in and out of the background.
5230 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5231 // can't request networks.
5232 restrictBackgroundRequestForCaller(nc);
5233 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005234
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005235 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005236 NetworkRequest.Type.LISTEN);
5237 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005238 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005239
5240 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5241 return networkRequest;
5242 }
5243
5244 @Override
5245 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5246 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005247 checkNotNull(operation, "PendingIntent cannot be null.");
5248 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5249 enforceAccessPermission();
5250 }
Etan Cohen859748f2017-04-03 17:42:34 -07005251 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005252 ensureSufficientPermissionsForRequest(networkCapabilities,
5253 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005254
Chalard Jeandda156a2018-01-10 21:19:32 +09005255 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005256 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005257
5258 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005259 NetworkRequest.Type.LISTEN);
5260 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005261 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005262
5263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005264 }
5265
Erik Klineacdd6392016-07-07 16:50:58 +09005266 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005267 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005268 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005269 mHandler.sendMessage(mHandler.obtainMessage(
5270 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005271 }
5272
5273 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09005274 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005275 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09005276 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5277 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005278 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09005279 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005280 }
5281
Robert Greenwalta67be032014-05-16 15:49:14 -07005282 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005283 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005284 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5285 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5286 }
5287
5288 @Override
5289 public void unregisterNetworkFactory(Messenger messenger) {
5290 enforceConnectivityInternalPermission();
5291 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5292 }
5293
5294 private void handleUnregisterNetworkFactory(Messenger messenger) {
5295 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5296 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005297 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005298 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005299 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005300 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005301 }
5302
Robert Greenwalt7b816022014-04-18 15:25:25 -07005303 /**
5304 * NetworkAgentInfo supporting a request by requestId.
5305 * These have already been vetted (their Capabilities satisfy the request)
5306 * and the are the highest scored network available.
5307 * the are keyed off the Requests requestId.
5308 */
Hugo Benichicd952782017-09-20 11:20:14 +09005309 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5310 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005311 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005312
Paul Jensen31a94f42015-02-13 14:18:39 -05005313 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5314 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005315 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005316 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5317 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5318 // there may not be a strict 1:1 correlation between the two.
5319 @GuardedBy("mNetworkForNetId")
5320 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005321
Robert Greenwalt7b816022014-04-18 15:25:25 -07005322 // NetworkAgentInfo keyed off its connecting messenger
5323 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005324 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005325 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005326
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005327 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005328 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005329
Paul Jensen2c311d62014-11-17 12:34:51 -05005330 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005331 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005332
Erik Klineda4bfa82015-04-30 12:58:40 +09005333 // Request used to optionally keep mobile data active even when higher
5334 // priority networks like Wi-Fi are active.
5335 private final NetworkRequest mDefaultMobileDataRequest;
5336
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005337 // Request used to optionally keep wifi data active even when higher
5338 // priority networks like ethernet are active.
5339 private final NetworkRequest mDefaultWifiRequest;
5340
Hugo Benichicd952782017-09-20 11:20:14 +09005341 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5342 synchronized (mNetworkForRequestId) {
5343 return mNetworkForRequestId.get(requestId);
5344 }
5345 }
5346
5347 private void clearNetworkForRequest(int requestId) {
5348 synchronized (mNetworkForRequestId) {
5349 mNetworkForRequestId.remove(requestId);
5350 }
5351 }
5352
5353 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5354 synchronized (mNetworkForRequestId) {
5355 mNetworkForRequestId.put(requestId, nai);
5356 }
5357 }
5358
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005359 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005360 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005361 }
5362
Varun Anand4fa80e82019-02-06 10:13:38 -08005363 @Nullable
5364 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5365 return nai != null ? nai.network : null;
5366 }
5367
5368 private void ensureRunningOnConnectivityServiceThread() {
5369 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5370 throw new IllegalStateException(
5371 "Not running on ConnectivityService thread: "
5372 + Thread.currentThread().getName());
5373 }
5374 }
5375
Chalard Jeanff46a252019-04-10 23:07:55 +09005376 @VisibleForTesting
5377 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005378 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005379 }
5380
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005381 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5382 return nri.request.requestId == mDefaultRequest.requestId;
5383 }
5384
Chalard Jean08577fc2018-05-02 21:14:54 +09005385 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5386 // changes that would conflict throughout the automerger graph. Having this method temporarily
5387 // helps with the process of going through with all these dependent changes across the entire
5388 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005389 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005390 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005391 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005392 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5393 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5394 }
5395
5396 /**
5397 * Register a new agent with ConnectivityService to handle a network.
5398 *
5399 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5400 * @param networkInfo the initial info associated with this network. It can be updated later :
5401 * see {@link #updateNetworkInfo}.
5402 * @param linkProperties the initial link properties of this network. They can be updated
5403 * later : see {@link #updateLinkProperties}.
5404 * @param networkCapabilities the initial capabilites of this network. They can be updated
5405 * later : see {@link #updateNetworkCapabilities}.
5406 * @param currentScore the initial score of the network. See
5407 * {@link NetworkAgentInfo#getCurrentScore}.
5408 * @param networkMisc metadata about the network. This is never updated.
5409 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5410 */
5411 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5412 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5413 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005414 enforceConnectivityInternalPermission();
5415
Rubin Xu1bb5c082017-09-05 18:40:49 +01005416 LinkProperties lp = new LinkProperties(linkProperties);
5417 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005418 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5419 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005420 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005421 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005422 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Luke Huang65914772019-03-16 00:31:46 +08005423 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mDnsResolver,
5424 mNMS, factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005425 // Make sure the network capabilities reflect what the agent info says.
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005426 nai.setNetworkCapabilities(mixInCapabilities(nai, nc));
Chalard Jeand771aa02018-04-26 16:16:10 +09005427 final String extraInfo = networkInfo.getExtraInfo();
5428 final String name = TextUtils.isEmpty(extraInfo)
5429 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005430 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005431 final long token = Binder.clearCallingIdentity();
5432 try {
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005433 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005434 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005435 } finally {
5436 Binder.restoreCallingIdentity(token);
5437 }
5438 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5439 // If the network disconnects or sends any other event before that, messages are deferred by
5440 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5441 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005442 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005443 }
5444
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005445 @VisibleForTesting
5446 protected NetworkStackClient getNetworkStack() {
5447 return NetworkStackClient.getInstance();
5448 }
5449
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005450 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5451 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005452 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005453 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005454 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005455 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005456 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005457
5458 try {
5459 networkMonitor.start();
5460 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07005461 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005462 }
Erik Klinee5dac902018-03-04 21:01:01 +09005463 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5464 NetworkInfo networkInfo = nai.networkInfo;
5465 nai.networkInfo = null;
5466 updateNetworkInfo(nai, networkInfo);
5467 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005468 }
5469
lucaslin25a4ec32018-11-28 12:51:55 +08005470 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5471 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005472 int netId = networkAgent.network.netId;
5473
Lorenzo Colittidf595632019-01-08 14:43:37 +09005474 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5475 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5476 // are accurate.
5477 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005478
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005479 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Rubin Xu9a3f7242019-04-11 11:45:43 -07005480
5481 // update filtering rules, need to happen after the interface update so netd knows about the
5482 // new interface (the interface name -> index map becomes initialized)
5483 updateVpnFiltering(newLp, oldLp, networkAgent);
5484
Robert Greenwalt7b816022014-04-18 15:25:25 -07005485 updateMtu(newLp, oldLp);
5486 // TODO - figure out what to do for clat
5487// for (LinkProperties lp : newLp.getStackedLinks()) {
5488// updateMtu(lp, null);
5489// }
lucaslin041a1af2018-11-28 19:27:52 +08005490 if (isDefaultNetwork(networkAgent)) {
5491 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5492 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005493
Erik Kline94887872016-04-05 13:30:49 +09005494 updateRoutes(newLp, oldLp, netId);
5495 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005496 // Make sure LinkProperties represents the latest private DNS status.
5497 // This does not need to be done before updateDnses because the
5498 // LinkProperties are not the source of the private DNS configuration.
5499 // updateDnses will fetch the private DNS configuration from DnsManager.
5500 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005501
Paul Jensene0bef712014-12-10 15:12:18 -05005502 if (isDefaultNetwork(networkAgent)) {
5503 handleApplyDefaultProxy(newLp.getHttpProxy());
5504 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005505 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005506 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005507 // TODO - move this check to cover the whole function
5508 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005509 synchronized (networkAgent) {
5510 networkAgent.linkProperties = newLp;
5511 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005512 // Start or stop DNS64 detection and 464xlat according to network state.
5513 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005514 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005515 try {
5516 networkAgent.networkMonitor().notifyLinkPropertiesChanged(newLp);
5517 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07005518 e.rethrowAsRuntimeException();
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005519 }
lucaslin25a4ec32018-11-28 12:51:55 +08005520 if (networkAgent.everConnected) {
5521 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5522 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005523 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005524
5525 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005526 }
5527
Joel Scherpelz668370b2017-06-08 15:35:21 +09005528 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005529 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005530 // marks on unsupported interfaces is harmless.
5531 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5532 return;
5533 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005534
Joel Scherpelz668370b2017-06-08 15:35:21 +09005535 int mark = mContext.getResources().getInteger(
5536 com.android.internal.R.integer.config_networkWakeupPacketMark);
5537 int mask = mContext.getResources().getInteger(
5538 com.android.internal.R.integer.config_networkWakeupPacketMask);
5539
5540 // Mask/mark of zero will not detect anything interesting.
5541 // Don't install rules unless both values are nonzero.
5542 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005543 return;
5544 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005545
5546 final String prefix = "iface:" + iface;
5547 try {
5548 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005549 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005550 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005551 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005552 }
5553 } catch (Exception e) {
5554 loge("Exception modifying wakeup packet monitoring: " + e);
5555 }
5556
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005557 }
5558
5559 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5560 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005561 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005562 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5563 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005564 for (String iface : interfaceDiff.added) {
5565 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005566 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005567 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005568 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005569 } catch (Exception e) {
5570 loge("Exception adding interface: " + e);
5571 }
5572 }
5573 for (String iface : interfaceDiff.removed) {
5574 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005575 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005576 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005577 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005578 } catch (Exception e) {
5579 loge("Exception removing interface: " + e);
5580 }
5581 }
5582 }
5583
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005584 /**
5585 * Have netd update routes from oldLp to newLp.
5586 * @return true if routes changed between oldLp and newLp
5587 */
5588 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005589 // Compare the route diff to determine which routes should be added and removed.
5590 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5591 oldLp != null ? oldLp.getAllRoutes() : null,
5592 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005593
5594 // add routes before removing old in case it helps with continuous connectivity
5595
Chalard Jean4d660112018-06-04 16:52:49 +09005596 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005597 for (RouteInfo route : routeDiff.added) {
5598 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005599 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005600 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005601 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005602 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005603 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5604 loge("Exception in addRoute for non-gateway: " + e);
5605 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005606 }
5607 }
5608 for (RouteInfo route : routeDiff.added) {
5609 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005610 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005611 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005612 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005613 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005614 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5615 loge("Exception in addRoute for gateway: " + e);
5616 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005617 }
5618 }
5619
5620 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005621 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005622 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005623 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005624 } catch (Exception e) {
5625 loge("Exception in removeRoute: " + e);
5626 }
5627 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005628 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005629 }
Erik Kline41368502015-06-17 13:19:54 +09005630
Erik Kline94887872016-04-05 13:30:49 +09005631 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5632 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5633 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005634 }
Erik Kline94887872016-04-05 13:30:49 +09005635
Erik Kline1742fe12017-12-13 19:40:49 +09005636 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5637 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5638
Erik Klinea24d4592018-01-11 21:07:29 +09005639 if (DBG) {
5640 final Collection<InetAddress> dnses = newLp.getDnsServers();
5641 log("Setting DNS servers for network " + netId + " to " + dnses);
5642 }
Erik Kline94887872016-04-05 13:30:49 +09005643 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005644 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005645 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005646 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005647 }
Erik Kline4edba012017-04-07 15:29:29 +09005648 }
5649
Rubin Xu9a3f7242019-04-11 11:45:43 -07005650 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
5651 NetworkAgentInfo nai) {
5652 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
5653 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
5654 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
5655 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
5656
5657 if (!wasFiltering && !needsFiltering) {
5658 // Nothing to do.
5659 return;
5660 }
5661
5662 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
5663 // Nothing changed.
5664 return;
5665 }
5666
5667 final Set<UidRange> ranges = nai.networkCapabilities.getUids();
5668 final int vpnAppUid = nai.networkCapabilities.getEstablishingVpnAppUid();
5669 // TODO: this create a window of opportunity for apps to receive traffic between the time
5670 // when the old rules are removed and the time when new rules are added. To fix this,
5671 // make eBPF support two whitelisted interfaces so here new rules can be added before the
5672 // old rules are being removed.
5673 if (wasFiltering) {
5674 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
5675 }
5676 if (needsFiltering) {
5677 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
5678 }
5679 }
5680
Luke Huang8a462ec2018-08-24 20:33:16 +08005681 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005682 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005683 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005684 }
5685 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005686 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005687 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005688 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005689 }
5690
Paul Jensen3d194ea2015-06-16 14:27:36 -04005691 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005692 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5693 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5694 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005695 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005696 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005697 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005698 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5699 // causing a connect/teardown loop.
5700 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5701 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005702 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005703 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005704 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5705 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005706 // does not cause any request (that is not a listen) currently matching that agent to
5707 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005708 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005709 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005710 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005711 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005712 }
5713
Paul Jensen3d194ea2015-06-16 14:27:36 -04005714 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005715 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005716 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005717 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005718 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005719 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005720 }
Paul Jensene0988542015-06-25 15:30:08 -04005721 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005722 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005723 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005724 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005725 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005726 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005727 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005728 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005729 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005730 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005731 if (nai.isSuspended()) {
5732 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5733 } else {
5734 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5735 }
lucasline252a742019-03-12 13:08:03 +08005736 if (nai.partialConnectivity) {
5737 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5738 } else {
5739 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5740 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005741
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005742 return newNc;
5743 }
5744
5745 /**
5746 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5747 *
5748 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5749 * capabilities we manage and store in {@code nai}, such as validated status and captive
5750 * portal status)
5751 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5752 * potentially triggers rematches.
5753 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5754 * change.)
5755 *
5756 * @param oldScore score of the network before any of the changes that prompted us
5757 * to call this function.
5758 * @param nai the network having its capabilities updated.
5759 * @param nc the new network capabilities.
5760 */
5761 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5762 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5763
5764 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005765
Luke Huang8a462ec2018-08-24 20:33:16 +08005766 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5767 final int newPermission = getNetworkPermission(newNc);
5768 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005769 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005770 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005771 } catch (RemoteException e) {
5772 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005773 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005774 }
5775
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005776 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005777 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005778 prevNc = nai.networkCapabilities;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005779 nai.setNetworkCapabilities(newNc);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005780 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005781
Chalard Jeanf213ca12018-01-16 18:43:05 +09005782 updateUids(nai, prevNc, newNc);
5783
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005784 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005785 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5786 // the change we're processing can't affect any requests, it can only affect the listens
5787 // on this network. We might have been called by rematchNetworkAndRequests when a
5788 // network changed foreground state.
5789 processListenRequests(nai, true);
5790 } else {
5791 // If the requestable capabilities have changed or the score changed, we can't have been
5792 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005793 rematchAllNetworksAndRequests(nai, oldScore);
5794 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005795 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005796
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005797 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005798 final boolean oldMetered = prevNc.isMetered();
5799 final boolean newMetered = newNc.isMetered();
5800 final boolean meteredChanged = oldMetered != newMetered;
5801
5802 if (meteredChanged) {
5803 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5804 mRestrictBackground);
5805 }
5806
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005807 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005808 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005809
5810 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005811 if (meteredChanged || roamingChanged) {
5812 notifyIfacesChangedForNetworkStats();
5813 }
5814 }
5815
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005816 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005817 // Tell VPNs about updated capabilities, since they may need to
5818 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005819 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005820 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005821 }
5822
Rubin Xu9a3f7242019-04-11 11:45:43 -07005823 /**
5824 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
5825 * network.
5826 *
5827 * Ingress interface filtering enforces that all apps under the given network can only receive
5828 * packets from the network's interface (and loopback). This is important for VPNs because
5829 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
5830 * non-VPN interfaces.
5831 *
5832 * As a result, this method should return true iff
5833 * 1. the network is an app VPN (not legacy VPN)
5834 * 2. the VPN does not allow bypass
5835 * 3. the VPN is fully-routed
5836 * 4. the VPN interface is non-null
5837 *
5838 * @See INetd#firewallAddUidInterfaceRules
5839 * @See INetd#firewallRemoveUidInterfaceRules
5840 */
5841 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
5842 LinkProperties lp) {
5843 if (nc == null || lp == null) return false;
5844 return nai.isVPN()
5845 && !nai.networkMisc.allowBypass
5846 && nc.getEstablishingVpnAppUid() != Process.SYSTEM_UID
5847 && lp.getInterfaceName() != null
5848 && (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute());
5849 }
5850
Chalard Jeanf213ca12018-01-16 18:43:05 +09005851 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5852 NetworkCapabilities newNc) {
5853 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5854 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5855 if (null == prevRanges) prevRanges = new ArraySet<>();
5856 if (null == newRanges) newRanges = new ArraySet<>();
5857 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5858
5859 prevRanges.removeAll(newRanges);
5860 newRanges.removeAll(prevRangesCopy);
5861
5862 try {
Rubin Xu9a3f7242019-04-11 11:45:43 -07005863 // When updating the VPN uid routing rules, add the new range first then remove the old
5864 // range. If old range were removed first, there would be a window between the old
5865 // range being removed and the new range being added, during which UIDs contained
5866 // in both ranges are not subject to any VPN routing rules. Adding new range before
5867 // removing old range works because, unlike the filtering rules below, it's possible to
5868 // add duplicate UID routing rules.
Chalard Jeanf213ca12018-01-16 18:43:05 +09005869 if (!newRanges.isEmpty()) {
5870 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5871 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005872 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005873 }
5874 if (!prevRanges.isEmpty()) {
5875 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5876 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005877 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005878 }
Rubin Xu9a3f7242019-04-11 11:45:43 -07005879 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
5880 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
5881 final String iface = nai.linkProperties.getInterfaceName();
5882 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
5883 // be added, due to the range being expanded and stored as invidiual UIDs. For example
5884 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
5885 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
5886 // were added first and then newRanges got removed later, there would be only one uid
5887 // 10013 left. A consequence of removing old ranges before adding new ranges is that
5888 // there is now a window of opportunity when the UIDs are not subject to any filtering.
5889 // Note that this is in contrast with the (more robust) update of VPN routing rules
5890 // above, where the addition of new ranges happens before the removal of old ranges.
5891 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
5892 // to be removed will never overlap with the new range to be added.
5893 if (wasFiltering && !prevRanges.isEmpty()) {
5894 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges,
5895 prevNc.getEstablishingVpnAppUid());
5896 }
5897 if (shouldFilter && !newRanges.isEmpty()) {
5898 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges,
5899 newNc.getEstablishingVpnAppUid());
5900 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005901 } catch (Exception e) {
5902 // Never crash!
Rubin Xu9a3f7242019-04-11 11:45:43 -07005903 loge("Exception in updateUids: ", e);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005904 }
5905 }
5906
Hugo Benichief502882017-09-01 01:23:32 +00005907 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005908 ensureRunningOnConnectivityServiceThread();
5909
Erik Kline736353a2018-03-21 07:18:33 -07005910 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005911 // Ignore updates for disconnected networks
5912 return;
5913 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005914 // newLp is already a defensive copy.
5915 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005916 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005917 log("Update of LinkProperties for " + nai.name() +
5918 "; created=" + nai.created +
5919 "; everConnected=" + nai.everConnected);
5920 }
lucaslin25a4ec32018-11-28 12:51:55 +08005921 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005922 }
5923
Paul Jensenc8b9a742014-09-30 15:37:41 -04005924 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005925 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5926 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005927 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005928 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005929 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005930 }
5931 }
5932
Chalard Jean08577fc2018-05-02 21:14:54 +09005933 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5934 int score = 0;
5935 int serial = 0;
5936 if (nai != null) {
5937 score = nai.getCurrentScore();
5938 serial = nai.factorySerialNumber;
5939 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005940 if (VDBG || DDBG){
5941 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5942 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005943 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005944 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5945 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005946 }
5947 }
5948
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005949 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5950 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005951 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005952 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005953 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5954 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005955 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005956 sendIntent(nri.mPendingIntent, intent);
5957 }
5958 // else not handled
5959 }
5960
5961 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5962 mPendingIntentWakeLock.acquire();
5963 try {
5964 if (DBG) log("Sending " + pendingIntent);
5965 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5966 } catch (PendingIntent.CanceledException e) {
5967 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5968 mPendingIntentWakeLock.release();
5969 releasePendingNetworkRequest(pendingIntent);
5970 }
5971 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5972 }
5973
5974 @Override
5975 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5976 String resultData, Bundle resultExtras) {
5977 if (DBG) log("Finished sending " + pendingIntent);
5978 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005979 // Release with a delay so the receiving client has an opportunity to put in its
5980 // own request.
5981 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005982 }
5983
Chalard Jeanf19db372018-01-26 19:24:40 +09005984 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005985 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005986 if (nri.messenger == null) {
5987 return; // Default request has no msgr
5988 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005989 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005990 // TODO: check if defensive copies of data is needed.
5991 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005992 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005993 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5994 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005995 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005996 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005997 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005998 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5999 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09006000 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08006001 // For this notification, arg1 contains the blocked status.
6002 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09006003 break;
6004 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006005 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006006 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006007 break;
6008 }
6009 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09006010 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09006011 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09006012 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09006013 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006014 break;
6015 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006016 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09006017 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07006018 break;
6019 }
junyulai05986c62018-08-07 19:50:45 +08006020 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08006021 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08006022 msg.arg1 = arg1;
6023 break;
6024 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006025 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006026 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006027 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006028 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07006029 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006030 String notification = ConnectivityManager.getCallbackName(notificationType);
6031 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07006032 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006033 nri.messenger.send(msg);
6034 } catch (RemoteException e) {
6035 // may occur naturally in the race of binder death.
6036 loge("RemoteException caught trying to send a callback msg for " + nri.request);
6037 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006038 }
6039
Hugo Benichidba33db2017-03-23 22:40:44 +09006040 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
6041 bundle.putParcelable(t.getClass().getSimpleName(), t);
6042 }
6043
Paul Jensenc8b9a742014-09-30 15:37:41 -04006044 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006045 if (nai.numRequestNetworkRequests() != 0) {
6046 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6047 NetworkRequest nr = nai.requestAt(i);
6048 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09006049 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006050 loge("Dead network still had at least " + nr);
6051 break;
6052 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04006053 }
6054 nai.asyncChannel.disconnect();
6055 }
6056
Robert Greenwalt7b816022014-04-18 15:25:25 -07006057 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
6058 if (oldNetwork == null) {
6059 loge("Unknown NetworkAgentInfo in handleLingerComplete");
6060 return;
6061 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04006062 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006063
6064 // If we get here it means that the last linger timeout for this network expired. So there
6065 // must be no other active linger timers, and we must stop lingering.
6066 oldNetwork.clearLingerState();
6067
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006068 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006069 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006070 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006071 } else {
6072 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006073 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
6074 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006075 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006076 }
6077
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006078 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07006079 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08006080
Paul Jensen27b02b72014-07-14 12:03:33 -04006081 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08006082 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04006083 } catch (Exception e) {
6084 loge("Exception setting default network :" + e);
6085 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09006086
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006087 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04006088 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08006089 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09006090 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09006091 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08006092 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
6093 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04006094 }
6095
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006096 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006097 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
6098 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6099 NetworkRequest nr = nri.request;
6100 if (!nr.isListen()) continue;
6101 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
6102 nai.removeRequest(nri.request.requestId);
6103 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
6104 }
6105 }
6106
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006107 if (capabilitiesChanged) {
6108 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
6109 }
6110
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006111 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6112 NetworkRequest nr = nri.request;
6113 if (!nr.isListen()) continue;
6114 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6115 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006116 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006117 }
6118 }
6119 }
6120
Paul Jensen2161a8e2014-09-11 11:00:39 -04006121 // Handles a network appearing or improving its score.
6122 //
6123 // - Evaluates all current NetworkRequests that can be
6124 // satisfied by newNetwork, and reassigns to newNetwork
6125 // any such requests for which newNetwork is the best.
6126 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006127 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006128 // needed. A network is needed if it is the best network for
6129 // one or more NetworkRequests, or if it is a VPN.
6130 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006131 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006132 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006133 //
6134 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6135 // networks that have no chance (i.e. even if validated)
6136 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006137 //
6138 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6139 // it does not remove NetworkRequests that other Networks could better satisfy.
6140 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6141 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6142 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006143 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006144 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006145 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6146 // performed to tear down unvalidated networks that have no chance (i.e. even if
6147 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006148 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006149 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006150 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006151 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006152 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006153 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006154
6155 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6156 final int score = newNetwork.getCurrentScore();
6157
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006158 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006159
Paul Jensen2161a8e2014-09-11 11:00:39 -04006160 // Find and migrate to this Network any NetworkRequests for
6161 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006162 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6163 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006164 NetworkCapabilities nc = newNetwork.networkCapabilities;
6165 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006166 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006167 // Process requests in the first pass and listens in the second pass. This allows us to
6168 // change a network's capabilities depending on which requests it has. This is only
6169 // correct if the change in capabilities doesn't affect whether the network satisfies
6170 // requests or not, and doesn't affect the network's score.
6171 if (nri.request.isListen()) continue;
6172
Hugo Benichicd952782017-09-20 11:20:14 +09006173 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006174 final boolean satisfies = newNetwork.satisfies(nri.request);
6175 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006176 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006177 log("Network " + newNetwork.name() + " was already satisfying" +
6178 " request " + nri.request.requestId + ". No change.");
6179 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006180 keep = true;
6181 continue;
6182 }
6183
6184 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006185 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006186 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006187 // next check if it's better than any current network we're using for
6188 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006189 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006190 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006191 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006192 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006193 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006194 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006195 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006196 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006197 if (VDBG || DDBG){
6198 log(" accepting network in place of " + currentNetwork.name());
6199 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006200 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006201 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006202 affectedNetworks.add(currentNetwork);
6203 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006204 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006205 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006206 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006207 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006208 if (!newNetwork.addRequest(nri.request)) {
6209 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6210 }
6211 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006212 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006213 // Tell NetworkFactories about the new score, so they can stop
6214 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006215 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006216 // network. Think about if there is a way to reduce this. Push
6217 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09006218 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006219 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006220 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006221 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006222 if (currentNetwork != null) {
6223 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6224 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006225 }
6226 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006227 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006228 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6229 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006230 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006231 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6232 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6233 // This means this code doesn't have to handle the case where "currentNetwork" no
6234 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6235 if (DBG) {
6236 log("Network " + newNetwork.name() + " stopped satisfying" +
6237 " request " + nri.request.requestId);
6238 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006239 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006240 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006241 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09006242 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006243 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006244 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6245 newNetwork.name() +
6246 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006247 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006248 // TODO: Technically, sending CALLBACK_LOST here is
6249 // incorrect if there is a replacement network currently
6250 // connected that can satisfy nri, which is a request
6251 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006252 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6253 // so this code is only incorrect for a network that loses
6254 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006255 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006256 }
6257 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006258 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006259 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006260 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006261 makeDefault(newNetwork);
6262 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006263 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006264 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006265 // Have a new default network, release the transition wakelock in
6266 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006267 }
6268
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006269 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6270 Slog.wtf(TAG, String.format(
6271 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006272 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006273 }
6274 if (newNetwork.getCurrentScore() != score) {
6275 Slog.wtf(TAG, String.format(
6276 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006277 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006278 }
6279
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006280 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006281 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6282 // If the network went from background to foreground or vice versa, we need to update
6283 // its foreground state. It is safe to do this after rematching the requests because
6284 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6285 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006286 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006287 } else {
6288 processListenRequests(newNetwork, false);
6289 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006290
Paul Jensencf4c2c62015-07-01 14:16:32 -04006291 // do this after the default net is switched, but
6292 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006293 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006294
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006295 // Linger any networks that are no longer needed. This should be done after sending the
6296 // available callback for newNetwork.
6297 for (NetworkAgentInfo nai : affectedNetworks) {
6298 updateLingerState(nai, now);
6299 }
6300 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6301 // does not need to be done in any particular order.
6302 updateLingerState(newNetwork, now);
6303
Paul Jensencf4c2c62015-07-01 14:16:32 -04006304 if (isNewDefault) {
6305 // Maintain the illusion: since the legacy API only
6306 // understands one network at a time, we must pretend
6307 // that the current default network disconnected before
6308 // the new one connected.
6309 if (oldDefaultNetwork != null) {
6310 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6311 oldDefaultNetwork, true);
6312 }
6313 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6314 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6315 notifyLockdownVpn(newNetwork);
6316 }
6317
Robert Greenwalt7b816022014-04-18 15:25:25 -07006318 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006319 // Notify battery stats service about this network, both the normal
6320 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006321 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006322 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006323 final IBatteryStats bs = BatteryStatsService.getService();
6324 final int type = newNetwork.networkInfo.getType();
6325
6326 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6327 bs.noteNetworkInterfaceType(baseIface, type);
6328 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6329 final String stackedIface = stacked.getInterfaceName();
6330 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006331 }
6332 } catch (RemoteException ignored) {
6333 }
6334
Robert Greenwalt152ed372014-12-17 17:19:53 -08006335 // This has to happen after the notifyNetworkCallbacks as that tickles each
6336 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006337 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006338 // and will generally do a dns request so they can ensureRouteToHost and if
6339 // they do that before the callbacks happen they'll use the default network.
6340 //
6341 // TODO: Is there still a race here? We send the broadcast
6342 // after sending the callback, but if the app can receive the
6343 // broadcast before the callback, it might still break.
6344 //
6345 // This *does* introduce a race where if the user uses the new api
6346 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6347 // they may get old info. Reverse this after the old startUsing api is removed.
6348 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006349 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6350 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006351 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006352 // legacy type tracker filters out repeat adds
6353 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6354 }
6355 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006356
6357 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6358 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6359 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6360 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6361 if (newNetwork.isVPN()) {
6362 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6363 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006364 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006365 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6366 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006367 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006368 if (nai.getLingerExpiry() > 0) {
6369 // This network has active linger timers and no requests, but is not
6370 // lingering. Linger it.
6371 //
6372 // One way (the only way?) this can happen if this network is unvalidated
6373 // and became unneeded due to another network improving its score to the
6374 // point where this network will no longer be able to satisfy any requests
6375 // even if it validates.
6376 updateLingerState(nai, now);
6377 } else {
6378 if (DBG) log("Reaping " + nai.name());
6379 teardownUnneededNetwork(nai);
6380 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006381 }
6382 }
6383 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006384 }
6385
Paul Jensen1c7ba022015-06-16 14:27:36 -04006386 /**
6387 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6388 * being disconnected.
6389 * @param changed If only one Network's score or capabilities have been modified since the last
6390 * time this function was called, pass this Network in this argument, otherwise pass
6391 * null.
6392 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6393 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6394 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6395 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6396 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006397 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006398 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006399 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6400 // to avoid the slowness. It is not simply enough to process just "changed", for
6401 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006402 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006403
6404 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6405 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6406 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006407 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006408 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006409 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006410 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006411 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6412 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6413 // Rematch higher scoring networks first to prevent requests first matching a lower
6414 // scoring network and then a higher scoring network, which could produce multiple
6415 // callbacks and inadvertently unlinger networks.
6416 Arrays.sort(nais);
6417 for (NetworkAgentInfo nai : nais) {
6418 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006419 // Only reap the last time through the loop. Reaping before all rematching
6420 // is complete could incorrectly teardown a network that hasn't yet been
6421 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006422 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006423 : ReapUnvalidatedNetworks.REAP,
6424 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006425 }
6426 }
6427 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006428
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006429 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006430 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006431 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006432 // For now only update icons for default connection.
6433 // TODO: Update WiFi and cellular icons separately. b/17237507
6434 if (!isDefaultNetwork(nai)) return;
6435
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006436 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006437 // Don't repeat publish.
6438 if (newInetCondition == mDefaultInetConditionPublished) return;
6439
6440 mDefaultInetConditionPublished = newInetCondition;
6441 sendInetConditionBroadcast(nai.networkInfo);
6442 }
6443
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006444 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006445 synchronized (mVpns) {
6446 if (mLockdownTracker != null) {
6447 if (nai != null && nai.isVPN()) {
6448 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6449 } else {
6450 mLockdownTracker.onNetworkInfoChanged();
6451 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006452 }
6453 }
6454 }
6455
Robert Greenwalt7b816022014-04-18 15:25:25 -07006456 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006457 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006458 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006459 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006460 synchronized (networkAgent) {
6461 oldInfo = networkAgent.networkInfo;
6462 networkAgent.networkInfo = newInfo;
6463 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006464 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006465
Robert Greenwalt7b816022014-04-18 15:25:25 -07006466 if (DBG) {
6467 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6468 (oldInfo == null ? "null" : oldInfo.getState()) +
6469 " to " + state);
6470 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006471
Robin Lee585e2482016-05-01 23:00:00 +01006472 if (!networkAgent.created
6473 && (state == NetworkInfo.State.CONNECTED
6474 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006475
6476 // A network that has just connected has zero requests and is thus a foreground network.
6477 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6478
Robert Greenwalt7b816022014-04-18 15:25:25 -07006479 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006480 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006481 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006482 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006483 (networkAgent.networkMisc == null ||
6484 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006485 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006486 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006487 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006488 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006489 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006490 loge("Error creating network " + networkAgent.network.netId + ": "
6491 + e.getMessage());
6492 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006493 }
Paul Jenseneec75412014-08-04 12:21:19 -04006494 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006495 }
6496
6497 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6498 networkAgent.everConnected = true;
6499
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006500 if (networkAgent.linkProperties == null) {
6501 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6502 }
6503
lucaslin8175ac992019-04-03 17:09:28 +08006504 // NetworkCapabilities need to be set before sending the private DNS config to
6505 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
6506 synchronized (networkAgent) {
6507 networkAgent.setNetworkCapabilities(networkAgent.networkCapabilities);
6508 }
Erik Kline736353a2018-03-21 07:18:33 -07006509 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006510 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6511 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006512
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006513 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6514 // command must be sent after updating LinkProperties to maximize chances of
6515 // NetworkMonitor seeing the correct LinkProperties when starting.
6516 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6517 try {
lucaslin43338992019-03-20 18:21:59 +08006518 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6519 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6520 }
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09006521 networkAgent.networkMonitor().notifyNetworkConnected(
6522 networkAgent.linkProperties, networkAgent.networkCapabilities);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006523 } catch (RemoteException e) {
Chiachang Wangf5b7a852019-04-24 22:35:58 -07006524 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006525 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006526 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006527
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006528 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6529 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6530 // capabilities, so it only needs to be done once on initial connect, not every time the
6531 // network's capabilities change. Note that we do this before rematching the network,
6532 // so we could decide to tear it down immediately afterwards. That's fine though - on
6533 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6534 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006535 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006536
Varun Anand4fa80e82019-02-06 10:13:38 -08006537 if (networkAgent.isVPN()) {
6538 updateAllVpnsCapabilities();
6539 }
6540
Paul Jensen2161a8e2014-09-11 11:00:39 -04006541 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006542 final long now = SystemClock.elapsedRealtime();
6543 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006544
6545 // This has to happen after matching the requests, because callbacks are just requests.
6546 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006547 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006548 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006549 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006550 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006551 }
Chalard Jean392971c2018-05-11 20:19:20 +09006552 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006553 if (networkAgent.isVPN()) {
6554 // As the active or bound network changes for apps, broadcast the default proxy, as
6555 // apps may need to update their proxy data. This is called after disconnecting from
6556 // VPN to make sure we do not broadcast the old proxy data.
6557 // TODO(b/122649188): send the broadcast only to VPN users.
6558 mProxyTracker.sendProxyBroadcast();
6559 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006560 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6561 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006562 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006563 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006564 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006565 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006566 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6567 networkAgent.networkCapabilities);
6568 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6569 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006570 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6571 ConnectivityManager.CALLBACK_SUSPENDED :
6572 ConnectivityManager.CALLBACK_RESUMED));
6573 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006574 }
6575 }
6576
Robert Greenwaltac96c522014-06-03 16:43:57 -07006577 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006578 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006579 if (score < 0) {
6580 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6581 "). Bumping score to min of 0");
6582 score = 0;
6583 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006584
Paul Jensen2161a8e2014-09-11 11:00:39 -04006585 final int oldScore = nai.getCurrentScore();
6586 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006587
Paul Jensen85cf78e2015-06-25 13:25:07 -04006588 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006589
Paul Jensenc8b9a742014-09-30 15:37:41 -04006590 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006591 }
6592
Erik Klinec75d4fa2017-02-15 19:59:17 +09006593 // Notify only this one new request of the current state. Transfer all the
6594 // current state by calling NetworkCapabilities and LinkProperties callbacks
6595 // so that callers can be guaranteed to have as close to atomicity in state
6596 // transfer as can be supported by this current API.
6597 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006598 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006599 if (nri.mPendingIntent != null) {
6600 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6601 // Attempt no subsequent state pushes where intents are involved.
6602 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006603 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006604
junyulai05986c62018-08-07 19:50:45 +08006605 final boolean metered = nai.networkCapabilities.isMetered();
6606 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6607 metered, mRestrictBackground);
6608 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6609 }
6610
6611 /**
6612 * Notify of the blocked state apps with a registered callback matching a given NAI.
6613 *
6614 * Unlike other callbacks, blocked status is different between each individual uid. So for
6615 * any given nai, all requests need to be considered according to the uid who filed it.
6616 *
6617 * @param nai The target NetworkAgentInfo.
6618 * @param oldMetered True if the previous network capabilities is metered.
6619 * @param newRestrictBackground True if data saver is enabled.
6620 */
6621 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6622 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6623
6624 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6625 NetworkRequest nr = nai.requestAt(i);
6626 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6627 final int uidRules = mUidRules.get(nri.mUid);
6628 final boolean oldBlocked, newBlocked;
6629 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6630 // between these two calls.
6631 synchronized (mVpns) {
6632 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6633 oldRestrictBackground);
6634 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6635 newRestrictBackground);
6636 }
6637 if (oldBlocked != newBlocked) {
6638 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6639 encodeBool(newBlocked));
6640 }
6641 }
6642 }
6643
6644 /**
6645 * Notify apps with a given UID of the new blocked state according to new uid rules.
6646 * @param uid The uid for which the rules changed.
6647 * @param newRules The new rules to apply.
6648 */
6649 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6650 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6651 final boolean metered = nai.networkCapabilities.isMetered();
6652 final boolean oldBlocked, newBlocked;
6653 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6654 // rules changed event. And this function actually loop through all connected nai and
6655 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6656 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6657 synchronized (mVpns) {
6658 oldBlocked = isUidNetworkingWithVpnBlocked(
6659 uid, mUidRules.get(uid), metered, mRestrictBackground);
6660 newBlocked = isUidNetworkingWithVpnBlocked(
6661 uid, newRules, metered, mRestrictBackground);
6662 }
6663 if (oldBlocked == newBlocked) {
Junyu Laic685f502019-04-09 08:59:00 -07006664 continue;
junyulai05986c62018-08-07 19:50:45 +08006665 }
6666 final int arg = encodeBool(newBlocked);
6667 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6668 NetworkRequest nr = nai.requestAt(i);
6669 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6670 if (nri != null && nri.mUid == uid) {
6671 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6672 }
6673 }
6674 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006675 }
6676
Chalard Jeanff46a252019-04-10 23:07:55 +09006677 @VisibleForTesting
6678 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006679 // The NetworkInfo we actually send out has no bearing on the real
6680 // state of affairs. For example, if the default connection is mobile,
6681 // and a request for HIPRI has just gone away, we need to pretend that
6682 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6683 // the state to DISCONNECTED, even though the network is of type MOBILE
6684 // and is still connected.
6685 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6686 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006687 if (state != DetailedState.DISCONNECTED) {
6688 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006689 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006690 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006691 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006692 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6693 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6694 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6695 if (info.isFailover()) {
6696 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6697 nai.networkInfo.setFailover(false);
6698 }
6699 if (info.getReason() != null) {
6700 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6701 }
6702 if (info.getExtraInfo() != null) {
6703 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6704 }
6705 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006706 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006707 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006708 if (newDefaultAgent != null) {
6709 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6710 newDefaultAgent.networkInfo);
6711 } else {
6712 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6713 }
6714 }
6715 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6716 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006717 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006718 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006719 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006720 }
6721 }
6722 }
6723
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006724 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006725 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006726 String notification = ConnectivityManager.getCallbackName(notifyType);
6727 log("notifyType " + notification + " for " + networkAgent.name());
6728 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006729 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6730 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006731 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6732 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006733 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6734 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006735 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006736 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006737 } else {
6738 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6739 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006740 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006741 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006742
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006743 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6744 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6745 }
6746
Jeff Sharkey69736342014-12-08 14:50:12 -08006747 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006748 * Returns the list of all interfaces that could be used by network traffic that does not
6749 * explicitly specify a network. This includes the default network, but also all VPNs that are
6750 * currently connected.
6751 *
6752 * Must be called on the handler thread.
6753 */
6754 private Network[] getDefaultNetworks() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006755 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006756 ArrayList<Network> defaultNetworks = new ArrayList<>();
6757 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6758 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6759 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6760 defaultNetworks.add(nai.network);
6761 }
6762 }
6763 return defaultNetworks.toArray(new Network[0]);
6764 }
6765
6766 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006767 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6768 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006769 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006770 private void notifyIfacesChangedForNetworkStats() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006771 ensureRunningOnConnectivityServiceThread();
6772 String activeIface = null;
6773 LinkProperties activeLinkProperties = getActiveLinkProperties();
6774 if (activeLinkProperties != null) {
6775 activeIface = activeLinkProperties.getInterfaceName();
6776 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006777 try {
Varun Anand02c50ef2019-02-07 14:13:13 -08006778 mStatsService.forceUpdateIfaces(
6779 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006780 } catch (Exception ignored) {
6781 }
6782 }
6783
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006784 @Override
6785 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006786 int user = UserHandle.getUserId(Binder.getCallingUid());
6787 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006788 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006789 return mVpns.get(user).addAddress(address, prefixLength);
6790 }
6791 }
6792
6793 @Override
6794 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006795 int user = UserHandle.getUserId(Binder.getCallingUid());
6796 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006797 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006798 return mVpns.get(user).removeAddress(address, prefixLength);
6799 }
6800 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006801
6802 @Override
6803 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006804 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006805 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006806 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006807 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006808 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006809 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006810 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006811 mHandler.post(() -> {
6812 // Update VPN's capabilities based on updated underlying network set.
6813 updateAllVpnsCapabilities();
6814 notifyIfacesChangedForNetworkStats();
6815 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006816 }
6817 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006818 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006819
6820 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006821 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006822 enforceConnectivityInternalPermission();
Remi NGUYEN VAN9ca4c622019-04-09 02:04:54 -07006823 String settingUrl = mContext.getResources().getString(
6824 R.string.config_networkCaptivePortalServerUrl);
6825
6826 if (!TextUtils.isEmpty(settingUrl)) {
6827 return settingUrl;
6828 }
6829
6830 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
6831 Settings.Global.CAPTIVE_PORTAL_HTTP_URL);
6832 if (!TextUtils.isEmpty(settingUrl)) {
6833 return settingUrl;
6834 }
6835
6836 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainib7c24872016-01-04 12:16:14 -08006837 }
6838
6839 @Override
junyulai7c469172019-01-16 20:23:34 +08006840 public void startNattKeepalive(Network network, int intervalSeconds,
6841 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006842 enforceKeepalivePermission();
6843 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006844 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006845 intervalSeconds, cb,
junyulaie4135282019-01-03 18:50:15 +08006846 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006847 }
6848
6849 @Override
junyulai215b8772019-01-15 11:32:44 +08006850 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006851 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006852 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006853 mKeepaliveTracker.startNattKeepalive(
6854 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006855 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006856 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6857 }
6858
6859 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006860 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006861 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006862 enforceKeepalivePermission();
6863 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006864 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006865 }
6866
6867 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006868 public void stopKeepalive(Network network, int slot) {
6869 mHandler.sendMessage(mHandler.obtainMessage(
junyulaie4135282019-01-03 18:50:15 +08006870 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006871 }
6872
6873 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006874 public void factoryReset() {
6875 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006876
6877 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6878 return;
6879 }
6880
Robin Lee3b3dd942015-05-12 18:14:58 +01006881 final int userId = UserHandle.getCallingUserId();
6882
Stuart Scottf1fb3972015-04-02 18:00:02 -07006883 // Turn airplane mode off
6884 setAirplaneMode(false);
6885
Stuart Scotte3e314d2015-04-20 14:07:45 -07006886 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6887 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006888 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006889 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006890 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006891 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006892 }
6893
Stuart Scotte3e314d2015-04-20 14:07:45 -07006894 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006895 // Remove always-on package
6896 synchronized (mVpns) {
6897 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6898 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006899 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006900 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6901 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006902
Hugo Benichi69744342017-11-27 10:57:16 +09006903 // Turn Always-on VPN off
6904 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6905 final long ident = Binder.clearCallingIdentity();
6906 try {
6907 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6908 mLockdownEnabled = false;
6909 setLockdownTracker(null);
6910 } finally {
6911 Binder.restoreCallingIdentity(ident);
6912 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006913 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006914
Hugo Benichi69744342017-11-27 10:57:16 +09006915 // Turn VPN off
6916 VpnConfig vpnConfig = getVpnConfig(userId);
6917 if (vpnConfig != null) {
6918 if (vpnConfig.legacy) {
6919 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6920 } else {
6921 // Prevent this app (packagename = vpnConfig.user) from initiating
6922 // VPN connections in the future without user intervention.
6923 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006924
Hugo Benichi69744342017-11-27 10:57:16 +09006925 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6926 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006927 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006928 }
6929 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006930
6931 Settings.Global.putString(mContext.getContentResolver(),
6932 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006933 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006934
Ricky Wai44dcbde2018-01-23 04:09:45 +00006935 @Override
6936 public byte[] getNetworkWatchlistConfigHash() {
6937 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6938 if (nwm == null) {
6939 loge("Unable to get NetworkWatchlistManager");
6940 return null;
6941 }
6942 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6943 return nwm.getWatchlistConfigHash();
6944 }
6945
Paul Jensencf4c2c62015-07-01 14:16:32 -04006946 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006947 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6948 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006949 }
6950
6951 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006952 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6953 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6954 }
6955
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006956 @VisibleForTesting
6957 public boolean hasService(String name) {
6958 return ServiceManager.checkService(name) != null;
6959 }
6960
Hugo Benichi64901e52017-10-19 14:42:40 +09006961 @VisibleForTesting
6962 protected IpConnectivityMetrics.Logger metricsLogger() {
6963 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6964 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006965 }
6966
6967 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006968 int[] transports = nai.networkCapabilities.getTransportTypes();
6969 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006970 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006971
6972 private static boolean toBool(int encodedBoolean) {
6973 return encodedBoolean != 0; // Only 0 means false.
6974 }
6975
6976 private static int encodeBool(boolean b) {
6977 return b ? 1 : 0;
6978 }
mswest46386886f2018-03-12 10:34:34 -07006979
6980 @Override
6981 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6982 FileDescriptor err, String[] args, ShellCallback callback,
6983 ResultReceiver resultReceiver) {
6984 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6985 }
6986
6987 private class ShellCmd extends ShellCommand {
6988
6989 @Override
6990 public int onCommand(String cmd) {
6991 if (cmd == null) {
6992 return handleDefaultCommands(cmd);
6993 }
6994 final PrintWriter pw = getOutPrintWriter();
6995 try {
6996 switch (cmd) {
6997 case "airplane-mode":
6998 final String action = getNextArg();
6999 if ("enable".equals(action)) {
7000 setAirplaneMode(true);
7001 return 0;
7002 } else if ("disable".equals(action)) {
7003 setAirplaneMode(false);
7004 return 0;
7005 } else if (action == null) {
7006 final ContentResolver cr = mContext.getContentResolver();
7007 final int enabled = Settings.Global.getInt(cr,
7008 Settings.Global.AIRPLANE_MODE_ON);
7009 pw.println(enabled == 0 ? "disabled" : "enabled");
7010 return 0;
7011 } else {
7012 onHelp();
7013 return -1;
7014 }
7015 default:
7016 return handleDefaultCommands(cmd);
7017 }
7018 } catch (Exception e) {
7019 pw.println(e);
7020 }
7021 return -1;
7022 }
7023
7024 @Override
7025 public void onHelp() {
7026 PrintWriter pw = getOutPrintWriter();
7027 pw.println("Connectivity service commands:");
7028 pw.println(" help");
7029 pw.println(" Print this help text.");
7030 pw.println(" airplane-mode [enable|disable]");
7031 pw.println(" Turn airplane mode on or off.");
7032 pw.println(" airplane-mode");
7033 pw.println(" Get airplane mode.");
7034 }
7035 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007036
Pavel Grafovcb3b8952018-12-14 13:51:07 +00007037 @GuardedBy("mVpns")
7038 private Vpn getVpnIfOwner() {
7039 final int uid = Binder.getCallingUid();
7040 final int user = UserHandle.getUserId(uid);
7041
7042 final Vpn vpn = mVpns.get(user);
7043 if (vpn == null) {
7044 return null;
7045 } else {
7046 final VpnInfo info = vpn.getVpnInfo();
7047 return (info == null || info.ownerUid != uid) ? null : vpn;
7048 }
7049 }
7050
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007051 /**
7052 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
7053 * for testing.
7054 */
7055 private Vpn enforceActiveVpnOrNetworkStackPermission() {
7056 if (checkNetworkStackPermission()) {
7057 return null;
7058 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007059 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00007060 Vpn vpn = getVpnIfOwner();
7061 if (vpn != null) {
7062 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007063 }
7064 }
7065 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
7066 + "permission");
7067 }
7068
7069 /**
7070 * @param connectionInfo the connection to resolve.
7071 * @return {@code uid} if the connection is found and the app has permission to observe it
7072 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
7073 * connection is not found.
7074 */
7075 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
7076 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
7077 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
7078 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
7079 }
7080
7081 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
7082 connectionInfo.local, connectionInfo.remote);
7083
7084 /* Filter out Uids not associated with the VPN. */
7085 if (vpn != null && !vpn.appliesToUid(uid)) {
7086 return INVALID_UID;
7087 }
7088
7089 return uid;
7090 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00007091
7092 @Override
7093 public boolean isCallerCurrentAlwaysOnVpnApp() {
7094 synchronized (mVpns) {
7095 Vpn vpn = getVpnIfOwner();
7096 return vpn != null && vpn.getAlwaysOn();
7097 }
7098 }
7099
7100 @Override
7101 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
7102 synchronized (mVpns) {
7103 Vpn vpn = getVpnIfOwner();
7104 return vpn != null && vpn.getLockdown();
7105 }
7106 }
Benedict Wong99a48412018-11-09 14:45:34 -08007107
7108 /**
7109 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
7110 *
7111 * <p>The TestNetworkService must be run in the system server due to TUN creation.
7112 */
7113 @Override
7114 public IBinder startOrGetTestNetworkService() {
7115 synchronized (mTNSLock) {
7116 TestNetworkService.enforceTestNetworkPermissions(mContext);
7117
7118 if (mTNS == null) {
7119 mTNS = new TestNetworkService(mContext, mNMS);
7120 }
7121
7122 return mTNS;
7123 }
7124 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07007125}