blob: ee8bb0524dfdeb8fcd814131c1182c73f1750c2c [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
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700280 private final PermissionMonitor mPermissionMonitor;
281
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700282 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700283
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900284 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700285 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900286 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700287
Hugo Benichi69744342017-11-27 10:57:16 +0900288 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
289 // a direct call to LockdownVpnTracker.isEnabled().
290 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700291 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900292 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700293 private LockdownVpnTracker mLockdownTracker;
294
junyulai05986c62018-08-07 19:50:45 +0800295 /**
296 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
297 * handler thread, they don't need a lock.
298 */
299 private SparseIntArray mUidRules = new SparseIntArray();
300 /** Flag indicating if background data is restricted. */
301 private boolean mRestrictBackground;
302
Erik Klineda4bfa82015-04-30 12:58:40 +0900303 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700304 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700305 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306
Luke Huang4e25ec62018-09-27 16:58:23 +0800307 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800308 @VisibleForTesting
Luke Huang65914772019-03-16 00:31:46 +0800309 protected IDnsResolver mDnsResolver;
310 @VisibleForTesting
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800311 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800312 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700313 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900314 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700315
Benedict Wong99a48412018-11-09 14:45:34 -0800316 /**
317 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
318 * instances.
319 */
320 @GuardedBy("mTNSLock")
321 private TestNetworkService mTNS;
322
323 private final Object mTNSLock = new Object();
324
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700325 private String mCurrentTcpBufferSizes;
326
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900327 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900328 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
329 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900330
Paul Jensenb10e37f2014-11-25 12:33:08 -0500331 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400332 // Tear down networks that have no chance (e.g. even if validated) of becoming
333 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500334 // all networks have been rematched against all NetworkRequests.
335 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400336 // Don't reap networks. This should be passed when some networks have not yet been
337 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500338 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900339 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500340
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900341 private enum UnneededFor {
342 LINGER, // Determine whether this network is unneeded and should be lingered.
343 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
344 }
345
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700346 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700347 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700348 * from one net to another. Clear happens when we get a new
349 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
350 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700351 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700352 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700353
Robert Greenwalt434203a2010-10-11 16:00:27 -0700354 /**
355 * used internally to reload global proxy settings
356 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700357 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700358
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700359 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400360 * PAC manager has received new port.
361 */
362 private static final int EVENT_PROXY_HAS_CHANGED = 16;
363
Robert Greenwalte049c232014-04-11 15:53:27 -0700364 /**
365 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700366 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700367 */
368 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
369
Robert Greenwalt7b816022014-04-18 15:25:25 -0700370 /**
371 * used internally when registering NetworkAgents
372 * obj = Messenger
373 */
374 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
375
Robert Greenwalt9258c642014-03-26 16:47:06 -0700376 /**
377 * used to add a network request
378 * includes a NetworkRequestInfo
379 */
380 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
381
382 /**
383 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900384 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700385 * cancel it.
386 * includes a NetworkRequestInfo
387 */
388 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
389
390 /**
391 * used to add a network listener - no request
392 * includes a NetworkRequestInfo
393 */
394 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
395
396 /**
397 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400398 * arg1 = UID of caller
399 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700400 */
401 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
402
Robert Greenwalta67be032014-05-16 15:49:14 -0700403 /**
404 * used internally when registering NetworkFactories
405 * obj = Messenger
406 */
407 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
408
Robert Greenwalt27711812014-06-25 16:45:57 -0700409 /**
410 * used internally to expire a wakelock when transitioning
411 * from one net to another. Expire happens when we fail to find
412 * a new network (typically after 1 minute) -
413 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
414 * a replacement network.
415 */
416 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
417
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700418 /**
419 * Used internally to indicate the system is ready.
420 */
421 private static final int EVENT_SYSTEM_READY = 25;
422
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800423 /**
424 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400425 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800426 */
427 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
428
429 /**
430 * used to remove a pending intent and its associated network request.
431 * arg1 = UID of caller
432 * obj = PendingIntent
433 */
434 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
435
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900436 /**
437 * used to specify whether a network should be used even if unvalidated.
438 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
439 * arg2 = whether to remember this choice in the future (1 or 0)
440 * obj = network
441 */
442 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
443
444 /**
445 * used to ask the user to confirm a connection to an unvalidated network.
446 * obj = network
447 */
448 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700449
Erik Klineda4bfa82015-04-30 12:58:40 +0900450 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700451 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900452 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700453 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900454
Paul Jensen694f2b82015-06-17 14:15:39 -0400455 /**
456 * used to add a network listener with a pending intent
457 * obj = NetworkRequestInfo
458 */
459 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
460
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900461 /**
462 * used to specify whether a network should not be penalized when it becomes unvalidated.
463 */
464 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
465
466 /**
467 * used to trigger revalidation of a network.
468 */
469 private static final int EVENT_REVALIDATE_NETWORK = 36;
470
Erik Klinea24d4592018-01-11 21:07:29 +0900471 // Handle changes in Private DNS settings.
472 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
473
dalyk7301aa42018-03-05 12:42:22 -0500474 // Handle private DNS validation status updates.
475 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
476
junyulai05986c62018-08-07 19:50:45 +0800477 /**
478 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
479 */
480 private static final int EVENT_UID_RULES_CHANGED = 39;
481
482 /**
483 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
484 */
485 private static final int EVENT_DATA_SAVER_CHANGED = 40;
486
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900487 /**
488 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
489 * been tested.
490 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
491 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
492 * arg2 = NetID.
493 */
494 public static final int EVENT_NETWORK_TESTED = 41;
495
496 /**
497 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
498 * config was resolved.
499 * obj = PrivateDnsConfig
500 * arg2 = netid
501 */
502 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
503
504 /**
505 * Request ConnectivityService display provisioning notification.
506 * arg1 = Whether to make the notification visible.
507 * arg2 = NetID.
508 * obj = Intent to be launched when notification selected by user, null if !arg1.
509 */
510 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
511
512 /**
lucaslind2e045e02019-01-24 15:55:30 +0800513 * This event can handle dismissing notification by given network id.
514 */
515 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
516
517 /**
lucasline252a742019-03-12 13:08:03 +0800518 * Used to specify whether a network should be used even if connectivity is partial.
519 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
520 * false)
521 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
522 * obj = network
523 */
524 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
525
526 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900527 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
528 * should be shown.
529 */
530 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
531
532 /**
533 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
534 * should be hidden.
535 */
536 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
537
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900538 private static String eventName(int what) {
539 return sMagicDecoderRing.get(what, Integer.toString(what));
540 }
541
Luke Huang65914772019-03-16 00:31:46 +0800542 private static IDnsResolver getDnsResolver() {
543 return IDnsResolver.Stub
544 .asInterface(ServiceManager.getService("dnsresolver"));
545 }
546
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900547 /** Handler thread used for both of the handlers below. */
548 @VisibleForTesting
549 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700550 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700551 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700552 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700553 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900554 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700555
Mike Lockwood0f79b542009-08-14 14:18:49 -0400556 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800557 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400558
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700559 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700560 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800561 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700562
Chalard Jean52c2aa72018-06-07 16:44:04 +0900563 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
564 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000565 @VisibleForTesting
566 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400567
Erik Klineda4bfa82015-04-30 12:58:40 +0900568 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700569
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400570 private UserManager mUserManager;
571
Chalard Jean4133a122018-06-04 13:33:12 +0900572 private NetworkConfig[] mNetConfigs;
573 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700574
Robert Greenwalt50393202011-06-21 17:26:14 -0700575 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900576 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700577
Chalard Jean4133a122018-06-04 13:33:12 +0900578 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400579
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900580 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900581 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900582 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900583
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700584 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800585 private static final int MIN_NET_ID = 100; // some reserved marks
586 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700587 private int mNextNetId = MIN_NET_ID;
588
Robert Greenwalt34524f02014-05-18 16:22:10 -0700589 // sequence number of NetworkRequests
590 private int mNextNetworkRequestId = 1;
591
Erik Kline7523eb32015-07-09 18:24:03 +0900592 // NetworkRequest activity String log entries.
593 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
594 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
595
Hugo Benichic2ae2872016-07-11 11:05:12 +0900596 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900597 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900598 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
599
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900600 private static final int MAX_WAKELOCK_LOGS = 20;
601 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900602 private int mTotalWakelockAcquisitions = 0;
603 private int mTotalWakelockReleases = 0;
604 private long mTotalWakelockDurationMs = 0;
605 private long mMaxWakelockDurationMs = 0;
606 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900607
Hugo Benichif9fdf872016-07-28 17:53:06 +0900608 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900609
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700610 @GuardedBy("mBandwidthRequests")
611 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
612
Erik Kline065ab6e2016-10-02 18:02:14 +0900613 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900614 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900615
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900616 @VisibleForTesting
617 final MultipathPolicyTracker mMultipathPolicyTracker;
618
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 /**
620 * Implements support for the legacy "one network per network type" model.
621 *
622 * We used to have a static array of NetworkStateTrackers, one for each
623 * network type, but that doesn't work any more now that we can have,
624 * for example, more that one wifi network. This class stores all the
625 * NetworkAgentInfo objects that support a given type, but the legacy
626 * API will only see the first one.
627 *
628 * It serves two main purposes:
629 *
630 * 1. Provide information about "the network for a given type" (since this
631 * API only supports one).
632 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
633 * the first network for a given type changes, or if the default network
634 * changes.
635 */
Chalard Jeanff46a252019-04-10 23:07:55 +0900636 @VisibleForTesting
637 static class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900638
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900639 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900640 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700642 /**
643 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
644 * Each list holds references to all NetworkAgentInfos that are used to
645 * satisfy requests for that network type.
646 *
647 * This array is built out at startup such that an unsupported network
648 * doesn't get an ArrayList instance, making this a tristate:
649 * unsupported, supported but not active and active.
650 *
651 * The actual lists are populated when we scan the network types that
652 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900653 *
654 * Threading model:
655 * - addSupportedType() is only called in the constructor
656 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
657 * They are therefore not thread-safe with respect to each other.
658 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
659 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
660 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700661 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jeanff46a252019-04-10 23:07:55 +0900663 @NonNull
664 private final ConnectivityService mService;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700665
Chalard Jeanff46a252019-04-10 23:07:55 +0900666 LegacyTypeTracker(@NonNull ConnectivityService service) {
667 mService = service;
668 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700669 }
670
671 public void addSupportedType(int type) {
672 if (mTypeLists[type] != null) {
673 throw new IllegalStateException(
674 "legacy list for type " + type + "already initialized");
675 }
Chalard Jean4133a122018-06-04 13:33:12 +0900676 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700677 }
678
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 public boolean isTypeSupported(int type) {
680 return isNetworkTypeValid(type) && mTypeLists[type] != null;
681 }
682
683 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900684 synchronized (mTypeLists) {
685 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
686 return mTypeLists[type].get(0);
687 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700688 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900689 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691
Robert Greenwalt8d482522015-06-24 13:23:42 -0700692 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900693 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900694 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700695 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900696 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900697 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900698 }
699 }
700
701 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700702 public void add(int type, NetworkAgentInfo nai) {
703 if (!isTypeSupported(type)) {
704 return; // Invalid network type.
705 }
706 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
707
708 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
709 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700710 return;
711 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900712 synchronized (mTypeLists) {
713 list.add(nai);
714 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900715
716 // 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 +0900717 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900718 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700719 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
Chalard Jeanff46a252019-04-10 23:07:55 +0900720 mService.sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700721 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700722 }
723
Lorenzo Colittia793a672014-07-31 23:20:17 +0900724 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900725 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900726 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
727 if (list == null || list.isEmpty()) {
728 return;
729 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900730 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900731
Hugo Benichi78caa2582016-06-21 09:48:07 +0900732 synchronized (mTypeLists) {
733 if (!list.remove(nai)) {
734 return;
735 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900736 }
737
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900738 if (wasFirstNetwork || wasDefault) {
Chalard Jean98c59fa2019-04-11 14:09:07 +0900739 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
740 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900741 }
742
743 if (!list.isEmpty() && wasFirstNetwork) {
744 if (DBG) log("Other network available for type " + type +
745 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900746 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean98c59fa2019-04-11 14:09:07 +0900747 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
748 mService.isDefaultNetwork(replacement));
749 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900750 }
751 }
752
753 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900754 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
755 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700756 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900757 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700758 }
759 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700760
Robert Greenwalt8d482522015-06-24 13:23:42 -0700761 // send out another legacy broadcast - currently only used for suspend/unsuspend
762 // toggle
763 public void update(NetworkAgentInfo nai) {
Chalard Jeanff46a252019-04-10 23:07:55 +0900764 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700765 final DetailedState state = nai.networkInfo.getDetailedState();
766 for (int type = 0; type < mTypeLists.length; type++) {
767 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700768 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900769 final boolean isFirst = contains && (nai == list.get(0));
770 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700771 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jeanff46a252019-04-10 23:07:55 +0900772 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700773 }
774 }
775 }
776
Lorenzo Colittia793a672014-07-31 23:20:17 +0900777 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900778 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900779 String state = (nai.networkInfo != null) ?
780 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
781 "???/???";
782 return name + " " + state;
783 }
784
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700785 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900786 pw.println("mLegacyTypeTracker:");
787 pw.increaseIndent();
788 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700789 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900790 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700791 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900792 pw.println();
793 pw.println("Current state:");
794 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900795 synchronized (mTypeLists) {
796 for (int type = 0; type < mTypeLists.length; type++) {
797 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
798 for (NetworkAgentInfo nai : mTypeLists[type]) {
799 pw.println(type + " " + naiToString(nai));
800 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900801 }
802 }
803 pw.decreaseIndent();
804 pw.decreaseIndent();
805 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700806 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700807 }
Chalard Jeanff46a252019-04-10 23:07:55 +0900808 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700809
Vishnu Nair5c010902017-10-26 10:08:50 -0700810 /**
811 * Helper class which parses out priority arguments and dumps sections according to their
812 * priority. If priority arguments are omitted, function calls the legacy dump command.
813 */
814 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
815 @Override
816 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
817 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
818 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
819 }
820
821 @Override
822 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
823 doDump(fd, pw, args, asProto);
824 }
825
826 @Override
827 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
828 doDump(fd, pw, args, asProto);
829 }
830 };
831
Jeff Sharkey899223b2012-08-04 15:24:58 -0700832 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700833 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Luke Huang65914772019-03-16 00:31:46 +0800834 this(context, netManager, statsService, policyManager,
835 getDnsResolver(), new IpConnectivityLog());
Hugo Benichif9fdf872016-07-28 17:53:06 +0900836 }
837
838 @VisibleForTesting
839 protected ConnectivityService(Context context, INetworkManagementService netManager,
840 INetworkStatsService statsService, INetworkPolicyManager policyManager,
Luke Huang65914772019-03-16 00:31:46 +0800841 IDnsResolver dnsresolver, IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800842 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800843
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900844 mSystemProperties = getSystemProperties();
845
Hugo Benichif9fdf872016-07-28 17:53:06 +0900846 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900847 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900848 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900849 mNetworkRequests.put(mDefaultRequest, defaultNRI);
850 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900851
Chalard Jeandda156a2018-01-10 21:19:32 +0900852 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900853 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700854
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700855 // The default WiFi request is a background request so that apps using WiFi are
856 // migrated to a better network (typically ethernet) when one comes up, instead
857 // of staying on WiFi forever.
858 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
859 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
860
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900861 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900862 mHandlerThread.start();
863 mHandler = new InternalHandler(mHandlerThread.getLooper());
864 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700865
Jeremy Joslin79294842014-12-03 17:15:28 -0800866 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
867 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
868
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900869 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900870
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700871 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800872 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800873 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700874 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900875 mPolicyManagerInternal = checkNotNull(
876 LocalServices.getService(NetworkPolicyManagerInternal.class),
877 "missing NetworkPolicyManagerInternal");
Luke Huang65914772019-03-16 00:31:46 +0800878 mDnsResolver = checkNotNull(dnsresolver, "missing IDnsResolver");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000879 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900880
Luke Huang674660f2018-09-27 19:33:11 +0800881 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700882 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700883 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700884
junyulai05986c62018-08-07 19:50:45 +0800885 // To ensure uid rules are synchronized with Network Policy, register for
886 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
887 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700888 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900889 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700890 } catch (RemoteException e) {
891 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700892 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700893 }
894
895 final PowerManager powerManager = (PowerManager) context.getSystemService(
896 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700897 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
898 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
899 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800900 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700901
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700902 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700903
Wink Saville51f456f2013-04-23 14:26:51 -0700904 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900905 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700906 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700907 String[] naStrings = context.getResources().getStringArray(
908 com.android.internal.R.array.networkAttributes);
909 for (String naString : naStrings) {
910 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700911 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700912 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700913 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800914 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700915 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700916 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700917 }
Wink Saville51f456f2013-04-23 14:26:51 -0700918 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
919 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
920 n.type);
921 continue;
922 }
Wink Saville975c8482011-04-07 14:23:45 -0700923 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800924 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700925 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700926 continue;
927 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700928 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700929
Wink Saville975c8482011-04-07 14:23:45 -0700930 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700931 mNetworksDefined++;
932 } catch(Exception e) {
933 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700934 }
935 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700936
937 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
938 if (mNetConfigs[TYPE_VPN] == null) {
939 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
940 // don't need to add TYPE_VPN to mNetConfigs.
941 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
942 mNetworksDefined++; // used only in the log() statement below.
943 }
944
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900945 // Do the same for Ethernet, since it's often not specified in the configs, although many
946 // devices can use it via USB host adapters.
947 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
948 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
949 mNetworksDefined++;
950 }
951
Wink Saville5e56bc52013-07-29 15:00:57 -0700952 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700953
Robert Greenwalt50393202011-06-21 17:26:14 -0700954 mProtectedNetworks = new ArrayList<Integer>();
955 int[] protectedNetworks = context.getResources().getIntArray(
956 com.android.internal.R.array.config_protectedNetworks);
957 for (int p : protectedNetworks) {
958 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
959 mProtectedNetworks.add(p);
960 } else {
961 if (DBG) loge("Ignoring protectedNetwork " + p);
962 }
963 }
964
Erik Kline47222fc2017-04-30 19:36:15 +0900965 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800966
Chenbo Feng436fe582019-02-25 22:55:58 -0800967 mPermissionMonitor = new PermissionMonitor(mContext, mNMS, mNetd);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700968
Varun Anand4fa80e82019-02-06 10:13:38 -0800969 // Set up the listener for user state for creating user VPNs.
970 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700971 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100972 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700973 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700974 intentFilter.addAction(Intent.ACTION_USER_ADDED);
975 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000976 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700977 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800978 mIntentReceiver,
979 UserHandle.ALL,
980 intentFilter,
981 null /* broadcastPermission */,
982 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000983 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
984 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900985
junyulai2454b692018-11-01 17:16:31 +0800986 // Listen to package add and removal events for all users.
987 intentFilter = new IntentFilter();
988 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800989 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800990 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
991 intentFilter.addDataScheme("package");
992 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800993 mIntentReceiver,
994 UserHandle.ALL,
995 intentFilter,
996 null /* broadcastPermission */,
997 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800998
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700999 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001000 mNMS.registerObserver(mTethering);
1001 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001002 } catch (RemoteException e) {
1003 loge("Error registering observer :" + e);
1004 }
1005
Erik Klineda4bfa82015-04-30 12:58:40 +09001006 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1007 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -08001008
Chalard Jean4133a122018-06-04 13:33:12 +09001009 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
1010 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -04001011
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04001012 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001013
junyulai0c666972019-03-04 22:45:36 +08001014 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +09001015 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
1016 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +09001017
1018 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1019 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1020 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1021 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1022 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1023 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1024 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001025
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001026 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001027 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001028 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001029
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001030 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1031
Luke Huang65914772019-03-16 00:31:46 +08001032 mDnsManager = new DnsManager(mContext, mDnsResolver, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001033 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001035
Mike Yuf9729752018-08-17 15:22:05 +08001036 @VisibleForTesting
1037 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001038 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001039 final TetheringDependencies deps = new TetheringDependencies() {
1040 @Override
1041 public boolean isTetheringSupported() {
1042 return ConnectivityService.this.isTetheringSupported();
1043 }
Erik Kline72302902018-06-14 17:36:40 +09001044 @Override
1045 public NetworkRequest getDefaultNetworkRequest() {
1046 return mDefaultRequest;
1047 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001048 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001049 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001050 IoThread.get().getLooper(), new MockableSystemProperties(),
1051 deps);
1052 }
1053
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001054 @VisibleForTesting
1055 protected ProxyTracker makeProxyTracker() {
1056 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1057 }
1058
Chalard Jean26400492018-04-18 20:18:38 +09001059 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1060 final NetworkCapabilities netCap = new NetworkCapabilities();
1061 netCap.addCapability(NET_CAPABILITY_INTERNET);
1062 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1063 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1064 netCap.setSingleUid(uid);
1065 return netCap;
1066 }
1067
Chalard Jeandda156a2018-01-10 21:19:32 +09001068 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001069 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001070 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001071 netCap.addCapability(NET_CAPABILITY_INTERNET);
1072 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001073 if (transportType > -1) {
1074 netCap.addTransportType(transportType);
1075 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001076 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001077 }
1078
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001079 // Used only for testing.
1080 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001081 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001082 // changing ContentResolver to make registerContentObserver non-final).
1083 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1084 // by subclassing SettingsObserver.
1085 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001086 void updateAlwaysOnNetworks() {
1087 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001088 }
1089
Erik Kline736353a2018-03-21 07:18:33 -07001090 // See FakeSettingsProvider comment above.
1091 @VisibleForTesting
1092 void updatePrivateDnsSettings() {
1093 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1094 }
1095
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001096 private void handleAlwaysOnNetworkRequest(
1097 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001098 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001099 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1100 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001101 if (enable == isEnabled) {
1102 return; // Nothing to do.
1103 }
1104
1105 if (enable) {
1106 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001107 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001108 } else {
Etan Cohenae574a82019-01-08 12:09:18 -08001109 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1110 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001111 }
1112 }
1113
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001114 private void handleConfigureAlwaysOnNetworks() {
1115 handleAlwaysOnNetworkRequest(
1116 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1117 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1118 false);
1119 }
1120
Erik Klineda4bfa82015-04-30 12:58:40 +09001121 private void registerSettingsCallbacks() {
1122 // Watch for global HTTP proxy changes.
1123 mSettingsObserver.observe(
1124 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1125 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1126
1127 // Watch for whether or not to keep mobile data always on.
1128 mSettingsObserver.observe(
1129 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001130 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1131
1132 // Watch for whether or not to keep wifi always on.
1133 mSettingsObserver.observe(
1134 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1135 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001136 }
1137
Erik Klinea24d4592018-01-11 21:07:29 +09001138 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001139 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1140 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001141 }
1142 }
1143
Robert Greenwalt34524f02014-05-18 16:22:10 -07001144 private synchronized int nextNetworkRequestId() {
1145 return mNextNetworkRequestId++;
1146 }
1147
Paul Jensen67b0b072015-06-10 11:22:17 -04001148 @VisibleForTesting
1149 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001150 synchronized (mNetworkForNetId) {
1151 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1152 int netId = mNextNetId;
1153 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1154 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001155 if (!mNetIdInUse.get(netId)) {
1156 mNetIdInUse.put(netId, true);
1157 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001158 }
1159 }
1160 }
1161 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001162 }
1163
Chalard Jeanc0982912018-06-07 16:11:34 +09001164 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001166 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1167 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001169 state = nai.getNetworkState();
1170 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 final NetworkInfo info = new NetworkInfo(networkType, 0,
1173 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1175 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001176 final NetworkCapabilities capabilities = new NetworkCapabilities();
1177 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1178 !info.isRoaming());
1179 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001181 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001182 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 return state;
1184 } else {
1185 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001187 }
1188
junyulai4a192e22018-06-13 15:00:37 +08001189 @VisibleForTesting
1190 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 if (network == null) {
1192 return null;
1193 }
Erik Kline736353a2018-03-21 07:18:33 -07001194 return getNetworkAgentInfoForNetId(network.netId);
1195 }
1196
1197 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001198 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001199 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001201 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001203 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001204 synchronized (mVpns) {
1205 if (!mLockdownEnabled) {
1206 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001207 Vpn vpn = mVpns.get(user);
1208 if (vpn != null && vpn.appliesToUid(uid)) {
1209 return vpn.getUnderlyingNetworks();
1210 }
1211 }
1212 }
1213 return null;
1214 }
1215
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001217 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001218
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001219 final Network[] networks = getVpnUnderlyingNetworks(uid);
1220 if (networks != null) {
1221 // getUnderlyingNetworks() returns:
1222 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1223 // empty array => the VPN explicitly said "no default network".
1224 // non-empty array => the VPN specified one or more default networks; we use the
1225 // first one.
1226 if (networks.length > 0) {
1227 nai = getNetworkAgentInfoForNetwork(networks[0]);
1228 } else {
1229 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001230 }
1231 }
1232
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001234 return nai.getNetworkState();
1235 } else {
1236 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001237 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001238 }
1239
1240 /**
1241 * Check if UID should be blocked from using the network with the given LinkProperties.
1242 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001243 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1244 boolean ignoreBlocked) {
1245 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001246 if (ignoreBlocked) {
1247 return false;
1248 }
Robin Lee17e61832016-05-09 13:46:28 +01001249 synchronized (mVpns) {
1250 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001251 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001252 return true;
1253 }
1254 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001255 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001256 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001257 }
1258
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001259 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001260 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1261 return;
1262 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001263 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001264 synchronized (mBlockedAppUids) {
1265 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001266 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001267 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001268 blocked = false;
1269 } else {
1270 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001271 }
1272 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001273 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1274 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1275 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001276 }
1277
junyulai05986c62018-08-07 19:50:45 +08001278 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1279 boolean blocked) {
1280 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1281 return;
1282 }
1283 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1284 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1285 nri.mUid, nri.request.requestId, net.netId));
1286 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1287 }
1288
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001289 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001290 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1291 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001292 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001293 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001294 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001295 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1296
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001297 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001298 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001299 }
Hugo Benichi69744342017-11-27 10:57:16 +09001300 synchronized (mVpns) {
1301 if (mLockdownTracker != null) {
1302 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1303 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001304 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001305 }
1306
1307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 * Return NetworkInfo for the active (i.e., connected) network interface.
1309 * It is assumed that at most one network is active at a time. If more
1310 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001311 * @return the info for the active network, or {@code null} if none is
1312 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001316 enforceAccessPermission();
1317 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001318 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001319 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001320 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1321 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
1323
Paul Jensen31a94f42015-02-13 14:18:39 -05001324 @Override
1325 public Network getActiveNetwork() {
1326 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001327 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001328 }
1329
1330 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001331 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001332 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001333 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001334 }
1335
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001336 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001337 final int user = UserHandle.getUserId(uid);
1338 int vpnNetId = NETID_UNSET;
1339 synchronized (mVpns) {
1340 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001341 // TODO : now that capabilities contain the UID, the appliesToUid test should
1342 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001343 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1344 }
1345 NetworkAgentInfo nai;
1346 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001347 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001348 if (nai != null) {
1349 final NetworkCapabilities requiredCaps =
1350 createDefaultNetworkCapabilitiesForUid(uid);
1351 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1352 return nai.network;
1353 }
1354 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001355 }
1356 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001357 if (nai != null
1358 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1359 nai = null;
1360 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001361 return nai != null ? nai.network : null;
1362 }
1363
Lorenzo Colitti18660282016-07-04 12:55:44 +09001364 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001365 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1366 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 final int uid = Binder.getCallingUid();
1368 NetworkState state = getUnfilteredActiveNetworkState(uid);
1369 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001370 }
1371
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001373 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001374 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001375 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001376 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001377 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 }
1379
1380 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 public NetworkInfo getNetworkInfo(int networkType) {
1382 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001383 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001384 if (getVpnUnderlyingNetworks(uid) != null) {
1385 // A VPN is active, so we may need to return one of its underlying networks. This
1386 // information is not available in LegacyTypeTracker, so we have to get it from
1387 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001388 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001389 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001390 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001391 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001392 }
1393 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001394 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001395 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001398 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001399 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001400 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001401 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001402 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001403 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001404 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001405 return state.networkInfo;
1406 } else {
1407 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001408 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001409 }
1410
1411 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 public NetworkInfo[] getAllNetworkInfo() {
1413 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001414 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001415 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1416 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001417 NetworkInfo info = getNetworkInfo(networkType);
1418 if (info != null) {
1419 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001422 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001425 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001426 public Network getNetworkForType(int networkType) {
1427 enforceAccessPermission();
1428 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001429 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001430 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001431 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001432 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001433 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001434 }
1435
1436 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001437 public Network[] getAllNetworks() {
1438 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001439 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001440 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001441 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001442 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001443 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001444 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001445 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001446 }
1447
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001448 @Override
1449 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1450 // The basic principle is: if an app's traffic could possibly go over a
1451 // network, without the app doing anything multinetwork-specific,
1452 // (hence, by "default"), then include that network's capabilities in
1453 // the array.
1454 //
1455 // In the normal case, app traffic only goes over the system's default
1456 // network connection, so that's the only network returned.
1457 //
1458 // With a VPN in force, some app traffic may go into the VPN, and thus
1459 // over whatever underlying networks the VPN specifies, while other app
1460 // traffic may go over the system default network (e.g.: a split-tunnel
1461 // VPN, or an app disallowed by the VPN), so the set of networks
1462 // returned includes the VPN's underlying networks and the system
1463 // default.
1464 enforceAccessPermission();
1465
Chalard Jean4133a122018-06-04 13:33:12 +09001466 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001467
1468 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001469 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001470 if (nc != null) {
1471 result.put(nai.network, nc);
1472 }
1473
Hugo Benichi69744342017-11-27 10:57:16 +09001474 synchronized (mVpns) {
1475 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001476 Vpn vpn = mVpns.get(userId);
1477 if (vpn != null) {
1478 Network[] networks = vpn.getUnderlyingNetworks();
1479 if (networks != null) {
1480 for (Network network : networks) {
1481 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001482 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001483 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001484 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001485 }
1486 }
1487 }
1488 }
1489 }
1490 }
1491
1492 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1493 out = result.values().toArray(out);
1494 return out;
1495 }
1496
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001497 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001498 public boolean isNetworkSupported(int networkType) {
1499 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001500 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001501 }
1502
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001503 /**
1504 * Return LinkProperties for the active (i.e., connected) default
1505 * network interface. It is assumed that at most one default network
1506 * is active at a time. If more than one is active, it is indeterminate
1507 * which will be returned.
1508 * @return the ip properties for the active network, or {@code null} if
1509 * none is active
1510 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001511 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001512 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001513 enforceAccessPermission();
1514 final int uid = Binder.getCallingUid();
1515 NetworkState state = getUnfilteredActiveNetworkState(uid);
1516 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001517 }
1518
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001519 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001520 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001521 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001522 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1523 if (nai != null) {
1524 synchronized (nai) {
1525 return new LinkProperties(nai.linkProperties);
1526 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001527 }
1528 return null;
1529 }
1530
Robert Greenwalt12e67352014-05-13 21:41:06 -07001531 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001532 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001533 public LinkProperties getLinkProperties(Network network) {
1534 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001535 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1536 }
1537
1538 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1539 if (nai == null) {
1540 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001541 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001542 synchronized (nai) {
1543 return new LinkProperties(nai.linkProperties);
1544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001545 }
1546
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001547 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001548 if (nai != null) {
1549 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001550 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001551 return networkCapabilitiesRestrictedForCallerPermissions(
1552 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001553 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001554 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001555 }
1556 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001557 return null;
1558 }
1559
1560 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001561 public NetworkCapabilities getNetworkCapabilities(Network network) {
1562 enforceAccessPermission();
1563 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1564 }
1565
Chalard Jeanb03a6222018-04-11 21:09:10 +09001566 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001567 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001568 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001569 if (!checkSettingsPermission(callerPid, callerUid)) {
1570 newNc.setUids(null);
1571 newNc.setSSID(null);
1572 }
Etan Cohen836ad572018-12-30 17:59:59 -08001573 if (newNc.getNetworkSpecifier() != null) {
1574 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1575 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001576 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001577 }
1578
Chalard Jeanb552c462018-02-21 18:43:54 +09001579 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1580 if (!checkSettingsPermission()) {
1581 nc.setSingleUid(Binder.getCallingUid());
1582 }
1583 }
1584
Chalard Jean26aa91a2018-03-20 19:13:57 +09001585 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1586 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1587 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1588 }
1589 }
1590
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001591 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001592 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001593 // Require internal since we're handing out IMSI details
1594 enforceConnectivityInternalPermission();
1595
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001596 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001597 for (Network network : getAllNetworks()) {
1598 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1599 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001600 // TODO (b/73321673) : NetworkState contains a copy of the
1601 // NetworkCapabilities, which may contain UIDs of apps to which the
1602 // network applies. Should the UIDs be cleared so as not to leak or
1603 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001604 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001605 }
1606 }
1607 return result.toArray(new NetworkState[result.size()]);
1608 }
1609
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001610 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001611 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001612 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001613 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1614 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1615 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001616 }
1617
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001618 @Override
1619 public boolean isActiveNetworkMetered() {
1620 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001621
Varun Anandc51b06d2019-02-25 17:22:02 -08001622 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001623 if (caps != null) {
1624 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1625 } else {
1626 // Always return the most conservative value
1627 return true;
1628 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001629 }
1630
Jeff Sharkey216c1812012-08-05 14:29:23 -07001631 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1632 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001633 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001634 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001635 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001636 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001637 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001638
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001639 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001640 * Ensures that the system cannot call a particular method.
1641 */
1642 private boolean disallowedBecauseSystemCaller() {
1643 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale41992c2019-04-08 12:36:02 -07001644 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
1645 // for devices launched with Q and above. However, existing devices upgrading to Q and
1646 // above must continued to be supported for few more releases.
1647 if (isSystem(Binder.getCallingUid()) && SystemProperties.getInt(
1648 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001649 log("This method exists only for app backwards compatibility"
1650 + " and must not be called by system services.");
1651 return true;
1652 }
1653 return false;
1654 }
1655
1656 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 * Ensure that a network route exists to deliver traffic to the specified
1658 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001659 * @param networkType the type of the network over which traffic to the
1660 * specified host is to be routed
1661 * @param hostAddress the IP address of the host to which the route is
1662 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 * @return {@code true} on success, {@code false} on failure
1664 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001665 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001666 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001667 if (disallowedBecauseSystemCaller()) {
1668 return false;
1669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001671 if (mProtectedNetworks.contains(networkType)) {
1672 enforceConnectivityInternalPermission();
1673 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001674
Chad Brubakerc0234532014-02-14 13:24:29 -08001675 InetAddress addr;
1676 try {
1677 addr = InetAddress.getByAddress(hostAddress);
1678 } catch (UnknownHostException e) {
1679 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1680 return false;
1681 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001684 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 return false;
1686 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001687
1688 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1689 if (nai == null) {
1690 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1691 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1692 } else {
1693 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1694 }
1695 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001696 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001697
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001698 DetailedState netState;
1699 synchronized (nai) {
1700 netState = nai.networkInfo.getDetailedState();
1701 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001702
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001703 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001704 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001705 log("requestRouteToHostAddress on down network "
1706 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001707 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001708 }
1709 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001711
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001712 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001713 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001714 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001715 LinkProperties lp;
1716 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001717 synchronized (nai) {
1718 lp = nai.linkProperties;
1719 netId = nai.network.netId;
1720 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001721 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001722 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1723 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001724 } finally {
1725 Binder.restoreCallingIdentity(token);
1726 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001727 }
1728
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001729 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001730 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001731 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001732 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001733 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001734 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001735 if (bestRoute.getGateway().equals(addr)) {
1736 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001737 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001738 } else {
1739 // if we will connect to this through another route, add a direct route
1740 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001741 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001742 }
1743 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001744 if (DBG) log("Adding legacy route " + bestRoute +
1745 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001746 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001747 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001748 } catch (Exception e) {
1749 // never crash - catch them all
1750 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001751 return false;
1752 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001753 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755
dalyk7301aa42018-03-05 12:42:22 -05001756 @VisibleForTesting
1757 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1758 @Override
1759 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1760 String hostname, boolean validated) {
1761 try {
1762 mHandler.sendMessage(mHandler.obtainMessage(
1763 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1764 new PrivateDnsValidationUpdate(netId,
1765 InetAddress.parseNumericAddress(ipAddress),
1766 hostname, validated)));
1767 } catch (IllegalArgumentException e) {
1768 loge("Error parsing ip address in validation event");
1769 }
1770 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001771
1772 @Override
1773 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1774 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1775 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1776 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1777 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1778 // event callback for certain nai. e.g. cellular. Register here to pass to
1779 // NetworkMonitor instead.
1780 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1781 // registerNetworkAgent to have NetworkMonitor created with system process as design
1782 // expectation. Also, NetdEventListenerService only allow one callback from each
1783 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1784 // NetworkMonitor registrants.
1785 if (nai != null && nai.satisfies(mDefaultRequest)) {
Chalard Jean971d9c92019-04-08 20:28:44 +09001786 Binder.withCleanCallingIdentity(() ->
1787 nai.networkMonitor().notifyDnsResponse(returnCode));
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001788 }
1789 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001790
1791 @Override
1792 public void onNat64PrefixEvent(int netId, boolean added,
1793 String prefixString, int prefixLength) {
1794 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1795 }
dalyk7301aa42018-03-05 12:42:22 -05001796 };
1797
1798 @VisibleForTesting
1799 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001800 final IIpConnectivityMetrics ipConnectivityMetrics =
1801 IIpConnectivityMetrics.Stub.asInterface(
1802 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1803 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001804 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001805 return;
dalyk7301aa42018-03-05 12:42:22 -05001806 }
1807
1808 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001809 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001810 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1811 mNetdEventCallback);
1812 } catch (Exception e) {
1813 loge("Error registering netd callback: " + e);
1814 }
1815 }
1816
Jeff Sharkey75d31892018-01-18 22:01:59 +09001817 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001818 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001819 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001821 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001822 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001823 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001824 // caller is NPMS, since we only register with them
1825 if (LOGD_BLOCKED_NETWORKINFO) {
1826 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1827 }
1828 mHandler.sendMessage(mHandler.obtainMessage(
1829 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1830
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001831 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001832 if (restrictBackground) {
1833 log("onRestrictBackgroundChanged(true): disabling tethering");
1834 mTethering.untetherAll();
1835 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001836 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001837 };
1838
junyulai05986c62018-08-07 19:50:45 +08001839 void handleUidRulesChanged(int uid, int newRules) {
1840 // skip update when we've already applied rules
1841 final int oldRules = mUidRules.get(uid, RULE_NONE);
1842 if (oldRules == newRules) return;
1843
1844 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1845
1846 if (newRules == RULE_NONE) {
1847 mUidRules.delete(uid);
1848 } else {
1849 mUidRules.put(uid, newRules);
1850 }
1851 }
1852
1853 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1854 if (mRestrictBackground == restrictBackground) return;
1855
1856 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1857 final boolean curMetered = nai.networkCapabilities.isMetered();
1858 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1859 restrictBackground);
1860 }
1861
1862 mRestrictBackground = restrictBackground;
1863 }
1864
1865 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1866 boolean isBackgroundRestricted) {
1867 synchronized (mVpns) {
1868 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1869 // Because the return value of this function depends on the list of UIDs the
1870 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1871 // list all state depending on the return value of this function has to be recomputed.
1872 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1873 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001874 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001875 return true;
1876 }
1877 }
1878
1879 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1880 isNetworkMetered, isBackgroundRestricted);
1881 }
1882
Robin Lee3b3dd942015-05-12 18:14:58 +01001883 /**
1884 * Require that the caller is either in the same user or has appropriate permission to interact
1885 * across users.
1886 *
1887 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1888 */
1889 private void enforceCrossUserPermission(int userId) {
1890 if (userId == UserHandle.getCallingUserId()) {
1891 // Not a cross-user call.
1892 return;
1893 }
1894 mContext.enforceCallingOrSelfPermission(
1895 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1896 "ConnectivityService");
1897 }
1898
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001899 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001900 for (String permission : permissions) {
1901 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001902 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001903 }
1904 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001905 return false;
1906 }
1907
paulhu3d67f532019-03-22 16:35:06 +08001908 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
1909 for (String permission : permissions) {
1910 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
1911 return true;
1912 }
1913 }
1914 return false;
1915 }
1916
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001917 private void enforceAnyPermissionOf(String... permissions) {
1918 if (!checkAnyPermissionOf(permissions)) {
1919 throw new SecurityException("Requires one of the following permissions: "
1920 + String.join(", ", permissions) + ".");
1921 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001922 }
1923
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001924 private void enforceInternetPermission() {
1925 mContext.enforceCallingOrSelfPermission(
1926 android.Manifest.permission.INTERNET,
1927 "ConnectivityService");
1928 }
1929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001931 mContext.enforceCallingOrSelfPermission(
1932 android.Manifest.permission.ACCESS_NETWORK_STATE,
1933 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
1935
1936 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001937 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
1939
Charles He36738632017-05-15 17:07:18 +01001940 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001941 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001942 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001943 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001944 }
1945
Chalard Jeanb552c462018-02-21 18:43:54 +09001946 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001947 return checkAnyPermissionOf(
1948 android.Manifest.permission.NETWORK_SETTINGS,
1949 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001950 }
1951
1952 private boolean checkSettingsPermission(int pid, int uid) {
1953 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001954 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1955 || PERMISSION_GRANTED == mContext.checkPermission(
1956 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001957 }
1958
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001959 private void enforceTetherAccessPermission() {
1960 mContext.enforceCallingOrSelfPermission(
1961 android.Manifest.permission.ACCESS_NETWORK_STATE,
1962 "ConnectivityService");
1963 }
1964
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001965 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001966 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001967 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001968 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001969 }
1970
Pavel Grafova462bcb2019-01-25 08:50:06 +00001971 private void enforceControlAlwaysOnVpnPermission() {
1972 mContext.enforceCallingOrSelfPermission(
1973 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1974 "ConnectivityService");
1975 }
1976
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001977 private void enforceNetworkStackSettingsOrSetup() {
1978 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001979 android.Manifest.permission.NETWORK_SETTINGS,
1980 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001981 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001982 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001983 }
1984
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001985 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001986 return checkAnyPermissionOf(
1987 android.Manifest.permission.NETWORK_STACK,
1988 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001989 }
1990
paulhu3d67f532019-03-22 16:35:06 +08001991 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
1992 return checkAnyPermissionOf(pid, uid,
1993 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
1994 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
1995 }
1996
Hugo Benichi514da602016-07-19 15:59:27 +09001997 private void enforceConnectivityRestrictedNetworksPermission() {
1998 try {
1999 mContext.enforceCallingOrSelfPermission(
2000 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2001 "ConnectivityService");
2002 return;
2003 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2004 enforceConnectivityInternalPermission();
2005 }
2006
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002007 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09002008 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002009 }
2010
Lorenzo Colitti18660282016-07-04 12:55:44 +09002011 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002012 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002013 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07002014 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002015 }
2016
2017 private void sendInetConditionBroadcast(NetworkInfo info) {
2018 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2019 }
2020
Wink Saville628b0852011-08-04 15:01:58 -07002021 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09002022 synchronized (mVpns) {
2023 if (mLockdownTracker != null) {
2024 info = new NetworkInfo(info);
2025 mLockdownTracker.augmentNetworkInfo(info);
2026 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002027 }
2028
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002029 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002030 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002031 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 if (info.isFailover()) {
2033 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2034 info.setFailover(false);
2035 }
2036 if (info.getReason() != null) {
2037 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2038 }
2039 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002040 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2041 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002043 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002044 return intent;
2045 }
2046
2047 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2048 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2049 }
2050
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002051 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002052 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2053 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2054 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002055 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002056 final long ident = Binder.clearCallingIdentity();
2057 try {
2058 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2059 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2060 } finally {
2061 Binder.restoreCallingIdentity(ident);
2062 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002063 }
2064
Mike Lockwood0f79b542009-08-14 14:18:49 -04002065 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002066 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002067 if (!mSystemReady
2068 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002069 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002070 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002071 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002072 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002073 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002074 }
2075
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002076 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002077 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002078 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002079 final NetworkInfo ni = intent.getParcelableExtra(
2080 ConnectivityManager.EXTRA_NETWORK_INFO);
2081 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2082 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2083 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002084 } else {
2085 BroadcastOptions opts = BroadcastOptions.makeBasic();
2086 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2087 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002088 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002089 final IBatteryStats bs = BatteryStatsService.getService();
2090 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002091 bs.noteConnectivityChanged(intent.getIntExtra(
2092 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002093 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002094 } catch (RemoteException e) {
2095 }
Chad Brubakerac925012018-03-08 10:37:09 -08002096 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002097 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002098 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002099 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002100 } finally {
2101 Binder.restoreCallingIdentity(ident);
2102 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002103 }
2104 }
2105
2106 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002107 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002108 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002109 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002110
Hugo Benichi20035e02017-04-26 14:53:28 +09002111 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002112 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002113 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002114 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002115 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002116 }
2117 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002118
Robin Lee244ce8e2016-01-05 18:03:46 +00002119 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2120 // for user to unlock device too.
2121 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002122
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002123 // Create network requests for always-on networks.
2124 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002125
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002126 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002127
2128 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 }
2130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002133 *
2134 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002135 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002136 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2138 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002139
2140 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002142
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 if (networkAgent.networkCapabilities.hasTransport(
2144 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002145 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2146 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002147 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002148 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 } else if (networkAgent.networkCapabilities.hasTransport(
2150 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002151 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2152 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002153 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002155 } else {
2156 // do not track any other networks
2157 timeout = 0;
2158 }
2159
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002161 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002162 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002163 } catch (Exception e) {
2164 // You shall not crash!
2165 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002166 }
2167 }
2168 }
2169
2170 /**
2171 * Remove data activity tracking when network disconnects.
2172 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2174 final String iface = networkAgent.linkProperties.getInterfaceName();
2175 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002176
Robert Greenwalt7b816022014-04-18 15:25:25 -07002177 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2178 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002179 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002180 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002181 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002182 } catch (Exception e) {
2183 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002184 }
2185 }
2186 }
2187
2188 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002189 * Update data activity tracking when network state is updated.
2190 */
2191 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2192 NetworkAgentInfo oldNetwork) {
2193 if (newNetwork != null) {
2194 setupDataActivityTracking(newNetwork);
2195 }
2196 if (oldNetwork != null) {
2197 removeDataActivityTracking(oldNetwork);
2198 }
2199 }
2200 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002201 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002202 * and set it on it's iface.
2203 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002204 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2205 final String iface = newLp.getInterfaceName();
2206 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002207 if (oldLp == null && mtu == 0) {
2208 // Silently ignore unset MTU value.
2209 return;
2210 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002211 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2212 if (VDBG) log("identical MTU - not setting");
2213 return;
2214 }
paulhud9736de2019-03-08 16:35:20 +08002215 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002216 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002217 return;
2218 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002219
w1997615afd812014-08-05 15:18:11 -07002220 // Cannot set MTU without interface name
2221 if (TextUtils.isEmpty(iface)) {
2222 loge("Setting MTU size with null iface.");
2223 return;
2224 }
2225
Robert Greenwalt7b816022014-04-18 15:25:25 -07002226 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002227 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002228 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002229 } catch (Exception e) {
2230 Slog.e(TAG, "exception in setMtu()" + e);
2231 }
2232 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002233
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002234 @VisibleForTesting
2235 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002236 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2237
2238 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002239 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002240 protected MockableSystemProperties getSystemProperties() {
2241 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002242 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002243
lucaslin041a1af2018-11-28 19:27:52 +08002244 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002245 String[] values = null;
2246 if (tcpBufferSizes != null) {
2247 values = tcpBufferSizes.split(",");
2248 }
2249
2250 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002251 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002252 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2253 values = tcpBufferSizes.split(",");
2254 }
2255
2256 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2257
2258 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002259 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002260
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002261 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2262 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2263 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002264 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002265 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002266 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002267 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002268
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002269 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002270 Settings.Global.TCP_DEFAULT_INIT_RWND,
2271 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002272 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2273 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002274 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002275 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002276 }
2277
Robert Greenwalt562cc542014-05-15 18:07:26 -07002278 @Override
2279 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002280 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002281 NETWORK_RESTORE_DELAY_PROP_NAME);
2282 if(restoreDefaultNetworkDelayStr != null &&
2283 restoreDefaultNetworkDelayStr.length() != 0) {
2284 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002285 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002286 } catch (NumberFormatException e) {
2287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002289 // if the system property isn't set, use the value for the apn type
2290 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2291
2292 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2293 (mNetConfigs[networkType] != null)) {
2294 ret = mNetConfigs[networkType].restoreTime;
2295 }
2296 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 }
2298
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002299 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2300 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2301 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002302 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002303 // Start gathering diagnostic information.
2304 netDiags.add(new NetworkDiagnostics(
2305 nai.network,
2306 new LinkProperties(nai.linkProperties), // Must be a copy.
2307 DIAG_TIME_MS));
2308 }
2309
2310 for (NetworkDiagnostics netDiag : netDiags) {
2311 pw.println();
2312 netDiag.waitForMeasurements();
2313 netDiag.dump(pw);
2314 }
2315 }
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002318 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002319 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2320 }
2321
2322 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002323 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002324 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002325 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002326
Erik Kline3f8306b2018-05-01 16:51:44 +09002327 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002328 dumpNetworkDiagnostics(pw);
2329 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002330 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002331 mTethering.dump(fd, pw, args);
2332 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002333 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2334 dumpNetworks(pw);
2335 return;
2336 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2337 dumpNetworkRequests(pw);
2338 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002339 }
Erik Kline379747a2015-06-05 17:47:34 +09002340
Lorenzo Colittie3805462015-06-03 11:18:24 +09002341 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002342 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002343 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002344 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002345 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002346 pw.println();
2347
Paul Jensen85cf78e2015-06-25 13:25:07 -04002348 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002349 pw.print("Active default network: ");
2350 if (defaultNai == null) {
2351 pw.println("none");
2352 } else {
2353 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002355 pw.println();
2356
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002357 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002358 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002359 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002360 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002361 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002362
junyulai05986c62018-08-07 19:50:45 +08002363 pw.print("Restrict background: ");
2364 pw.println(mRestrictBackground);
2365 pw.println();
2366
2367 pw.println("Status for known UIDs:");
2368 pw.increaseIndent();
2369 final int size = mUidRules.size();
2370 for (int i = 0; i < size; i++) {
2371 // Don't crash if the array is modified while dumping in bugreports.
2372 try {
2373 final int uid = mUidRules.keyAt(i);
2374 final int uidRules = mUidRules.get(uid, RULE_NONE);
2375 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2376 } catch (ArrayIndexOutOfBoundsException e) {
2377 pw.println(" ArrayIndexOutOfBoundsException");
2378 } catch (ConcurrentModificationException e) {
2379 pw.println(" ConcurrentModificationException");
2380 }
2381 }
2382 pw.println();
2383 pw.decreaseIndent();
2384
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002385 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002386 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002387 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002388 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002389 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002390
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002391 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002392
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002393 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002394 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002395
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002396 pw.println();
2397 mKeepaliveTracker.dump(pw);
2398
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002399 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002400 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002401
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002402 pw.println();
2403 mMultipathPolicyTracker.dump(pw);
2404
Erik Kline3f8306b2018-05-01 16:51:44 +09002405 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002406 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002407 pw.println("mNetworkRequestInfoLogs (most recent first):");
2408 pw.increaseIndent();
2409 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2410 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002411
2412 pw.println();
2413 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2414 pw.increaseIndent();
2415 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2416 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002417
2418 pw.println();
2419 pw.println("NetTransition WakeLock activity (most recent first):");
2420 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002421 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2422 pw.println("total releases: " + mTotalWakelockReleases);
2423 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2424 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2425 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2426 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2427 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2428 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002429 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002430
2431 pw.println();
2432 pw.println("bandwidth update requests (by uid):");
2433 pw.increaseIndent();
2434 synchronized (mBandwidthRequests) {
2435 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2436 pw.println("[" + mBandwidthRequests.keyAt(i)
2437 + "]: " + mBandwidthRequests.valueAt(i));
2438 }
2439 }
2440 pw.decreaseIndent();
2441
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002442 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002443 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002444
2445 pw.println();
2446 pw.println("NetworkStackClient logs:");
2447 pw.increaseIndent();
2448 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450
Hugo Benichi14683812018-09-03 08:32:56 +09002451 private void dumpNetworks(IndentingPrintWriter pw) {
2452 for (NetworkAgentInfo nai : networksSortedById()) {
2453 pw.println(nai.toString());
2454 pw.increaseIndent();
2455 pw.println(String.format(
2456 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2457 nai.numForegroundNetworkRequests(),
2458 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2459 nai.numBackgroundNetworkRequests(),
2460 nai.numNetworkRequests()));
2461 pw.increaseIndent();
2462 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2463 pw.println(nai.requestAt(i).toString());
2464 }
2465 pw.decreaseIndent();
2466 pw.println("Lingered:");
2467 pw.increaseIndent();
2468 nai.dumpLingerTimers(pw);
2469 pw.decreaseIndent();
2470 pw.decreaseIndent();
2471 }
2472 }
2473
2474 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2475 for (NetworkRequestInfo nri : requestsSortedById()) {
2476 pw.println(nri.toString());
2477 }
2478 }
2479
Hugo Benichia2a917c2018-09-03 08:19:02 +09002480 /**
2481 * Return an array of all current NetworkAgentInfos sorted by network id.
2482 */
2483 private NetworkAgentInfo[] networksSortedById() {
2484 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2485 networks = mNetworkAgentInfos.values().toArray(networks);
2486 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2487 return networks;
2488 }
2489
2490 /**
2491 * Return an array of all current NetworkRequest sorted by request id.
2492 */
2493 private NetworkRequestInfo[] requestsSortedById() {
2494 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2495 requests = mNetworkRequests.values().toArray(requests);
2496 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2497 return requests;
2498 }
2499
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002500 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002501 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002502 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002503 if (officialNai != null && officialNai.equals(nai)) return true;
2504 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002505 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002506 " - " + nai);
2507 }
2508 return false;
2509 }
2510
Robert Greenwalt42acef32009-08-12 16:08:25 -07002511 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002512 private class NetworkStateTrackerHandler extends Handler {
2513 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002514 super(looper);
2515 }
2516
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002517 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002519 default:
2520 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002521 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002522 handleAsyncChannelHalfConnect(msg);
2523 break;
2524 }
2525 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2526 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2527 if (nai != null) nai.asyncChannel.disconnect();
2528 break;
2529 }
2530 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2531 handleAsyncChannelDisconnected(msg);
2532 break;
2533 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002534 }
2535 return true;
2536 }
2537
2538 private void maybeHandleNetworkAgentMessage(Message msg) {
2539 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2540 if (nai == null) {
2541 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002542 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002543 }
2544 return;
2545 }
2546
2547 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002548 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002549 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002550 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002551 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002552 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002553 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002554 break;
2555 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002556 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002557 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002558 break;
2559 }
2560 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002561 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002562 updateNetworkInfo(nai, info);
2563 break;
2564 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002565 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002566 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002567 break;
2568 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002569 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002570 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2571 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002572 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002573 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002574 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002575 // Mark the network as temporarily accepting partial connectivity so that it
2576 // will be validated (and possibly become default) even if it only provides
2577 // partial internet access. Note that if user connects to partial connectivity
2578 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2579 // out of wifi coverage) and if the same wifi is available again, the device
2580 // will auto connect to this wifi even though the wifi has "no internet".
2581 // TODO: Evaluate using a separate setting in IpMemoryStore.
2582 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002583 break;
2584 }
junyulaie4135282019-01-03 18:50:15 +08002585 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2586 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002587 break;
2588 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002589 }
2590 }
2591
2592 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2593 switch (msg.what) {
2594 default:
2595 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002596 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002597 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002598 if (nai == null) break;
2599
lucasline252a742019-03-12 13:08:03 +08002600 final boolean partialConnectivity =
2601 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002602 || (nai.networkMisc.acceptPartialConnectivity
2603 && nai.partialConnectivity);
2604 // Once a network is determined to have partial connectivity, it cannot
lucaslin975b7d32019-03-21 11:59:22 +08002605 // go back to full connectivity without a disconnect. This is because
2606 // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
2607 // but not both.
2608 // TODO: Provide multi-testResult to improve the communication between
2609 // ConnectivityService and NetworkMonitor, so that ConnectivityService could
2610 // know the real status of network.
lucaslin43338992019-03-20 18:21:59 +08002611 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002612 (partialConnectivity && !nai.partialConnectivity);
2613
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002614 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002615 final boolean wasValidated = nai.lastValidated;
2616 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002617 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2618 && valid) {
2619 nai.captivePortalLoginNotified = true;
2620 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2621 }
Erik Klinea24d4592018-01-11 21:07:29 +09002622
Erik Klinea24d4592018-01-11 21:07:29 +09002623 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2624
Erik Klinea24d4592018-01-11 21:07:29 +09002625 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002626 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2627 ? " with redirect to " + redirectUrl
2628 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002629 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2630 }
Erik Klinea24d4592018-01-11 21:07:29 +09002631 if (valid != nai.lastValidated) {
2632 if (wasDefault) {
2633 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2634 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002635 }
Erik Klinea24d4592018-01-11 21:07:29 +09002636 final int oldScore = nai.getCurrentScore();
2637 nai.lastValidated = valid;
2638 nai.everValidated |= valid;
2639 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2640 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2641 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002642 if (valid) {
2643 handleFreshlyValidatedNetwork(nai);
2644 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2645 // valid.
2646 mNotifier.clearNotification(nai.network.netId,
2647 NotificationType.NO_INTERNET);
2648 mNotifier.clearNotification(nai.network.netId,
2649 NotificationType.LOST_INTERNET);
2650 }
lucaslin43338992019-03-20 18:21:59 +08002651 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002652 nai.partialConnectivity = partialConnectivity;
2653 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002654 }
2655 updateInetCondition(nai);
2656 // Let the NetworkAgent know the state of its network
2657 Bundle redirectUrlBundle = new Bundle();
2658 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2659 nai.asyncChannel.sendMessage(
2660 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2661 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2662 0, redirectUrlBundle);
2663 if (wasValidated && !nai.lastValidated) {
2664 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002665 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002666 break;
2667 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002668 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002669 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002670 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002671 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002672 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002673 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002674 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002675 nai.lastCaptivePortalDetected = visible;
2676 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002677 if (visible) {
2678 nai.captivePortalLoginNotified = false;
2679 }
Calvin Onbe96da12016-10-11 15:10:46 -07002680 if (nai.lastCaptivePortalDetected &&
2681 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2682 if (DBG) log("Avoiding captive portal network: " + nai.name());
2683 nai.asyncChannel.sendMessage(
2684 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2685 teardownUnneededNetwork(nai);
2686 break;
2687 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002688 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002689 }
2690 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002691 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002692 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002693 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2694 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002695 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002696 if (nai == null) {
2697 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2698 break;
2699 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002700 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002701 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002702 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002703 }
Paul Jensen869868be2014-05-15 10:33:05 -04002704 }
Paul Jensen869868be2014-05-15 10:33:05 -04002705 break;
2706 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002707 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002708 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002709 if (nai == null) break;
2710
Erik Kline736353a2018-03-21 07:18:33 -07002711 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002712 break;
2713 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002714 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002715 return true;
2716 }
2717
Calvin Onbe96da12016-10-11 15:10:46 -07002718 private int getCaptivePortalMode() {
2719 return Settings.Global.getInt(mContext.getContentResolver(),
2720 Settings.Global.CAPTIVE_PORTAL_MODE,
2721 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2722 }
2723
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002724 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2725 switch (msg.what) {
2726 default:
2727 return false;
2728 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2729 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2730 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2731 handleLingerComplete(nai);
2732 }
2733 break;
2734 }
2735 }
2736 return true;
2737 }
2738
Etan Cohenae574a82019-01-08 12:09:18 -08002739 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2740 switch (msg.what) {
2741 default:
2742 return false;
2743 case NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2744 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2745 /* callOnUnavailable */ true);
2746 break;
2747 }
2748 }
2749 return true;
2750 }
2751
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002752 @Override
2753 public void handleMessage(Message msg) {
Etan Cohenae574a82019-01-08 12:09:18 -08002754 if (!maybeHandleAsyncChannelMessage(msg)
2755 && !maybeHandleNetworkMonitorMessage(msg)
2756 && !maybeHandleNetworkAgentInfoMessage(msg)
2757 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002758 maybeHandleNetworkAgentMessage(msg);
2759 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002760 }
2761 }
2762
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002763 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2764 private final NetworkAgentInfo mNai;
2765
2766 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2767 mNai = nai;
2768 }
2769
2770 @Override
2771 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2772 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2773 new Pair<>(mNai, networkMonitor)));
2774 }
2775
2776 @Override
2777 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2778 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2779 testResult, mNai.network.netId, redirectUrl));
2780 }
2781
2782 @Override
2783 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2784 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2785 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2786 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2787 }
2788
2789 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002790 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002791 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002792 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002793
2794 final PendingIntent pendingIntent;
2795 // Only the system server can register notifications with package "android"
2796 final long token = Binder.clearCallingIdentity();
2797 try {
2798 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2799 } finally {
2800 Binder.restoreCallingIdentity(token);
2801 }
2802 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2803 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2804 mNai.network.netId,
2805 pendingIntent));
2806 }
2807
2808 @Override
2809 public void hideProvisioningNotification() {
2810 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2811 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2812 mNai.network.netId));
2813 }
Lorenzo Colittie8660ef2019-04-23 01:55:01 -07002814
2815 @Override
2816 public int getInterfaceVersion() {
2817 return this.VERSION;
2818 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002819 }
2820
Erik Kline736353a2018-03-21 07:18:33 -07002821 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002822 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002823 }
2824
Erik Klinec6d00222018-06-26 18:53:43 +09002825 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2826 if (nai == null) return;
2827 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2828 // in order to restart a validation pass from within netd.
2829 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2830 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2831 updateDnses(nai.linkProperties, null, nai.network.netId);
2832 }
2833 }
2834
Erik Klinea24d4592018-01-11 21:07:29 +09002835 private void handlePrivateDnsSettingsChanged() {
2836 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2837
2838 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002839 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002840 if (networkRequiresValidation(nai)) {
2841 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2842 }
Erik Klinea24d4592018-01-11 21:07:29 +09002843 }
2844 }
2845
Erik Kline736353a2018-03-21 07:18:33 -07002846 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2847 // Private DNS only ever applies to networks that might provide
2848 // Internet access and therefore also require validation.
2849 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002850
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002851 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002852 // schedule DNS resolutions. If a DNS resolution is required the
2853 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002854 try {
2855 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2856 } catch (RemoteException e) {
2857 e.rethrowFromSystemServer();
2858 }
Erik Kline736353a2018-03-21 07:18:33 -07002859
2860 // With Private DNS bypass support, we can proceed to update the
2861 // Private DNS config immediately, even if we're in strict mode
2862 // and have not yet resolved the provider name into a set of IPs.
2863 updatePrivateDns(nai, cfg);
2864 }
2865
2866 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2867 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002868 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002869 }
2870
dalyk7301aa42018-03-05 12:42:22 -05002871 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2872 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2873 if (nai == null) {
2874 return;
2875 }
2876 mDnsManager.updatePrivateDnsValidation(update);
2877 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2878 }
2879
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002880 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2881 int prefixLength) {
2882 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2883 if (nai == null) return;
2884
2885 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2886 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2887
2888 IpPrefix prefix = null;
2889 if (added) {
2890 try {
2891 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2892 prefixLength);
2893 } catch (IllegalArgumentException e) {
2894 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2895 return;
2896 }
2897 }
2898
2899 nai.clatd.setNat64Prefix(prefix);
2900 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2901 }
2902
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002903 private void updateLingerState(NetworkAgentInfo nai, long now) {
2904 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2905 // 2. If the network was lingering and there are now requests, unlinger it.
2906 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2907 // one lingered request, start lingering.
2908 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002909 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002910 if (DBG) log("Unlingering " + nai.name());
2911 nai.unlinger();
2912 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002913 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002914 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002915 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002916 nai.linger();
2917 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2918 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2919 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002920 }
2921
Robert Greenwalt7b816022014-04-18 15:25:25 -07002922 private void handleAsyncChannelHalfConnect(Message msg) {
2923 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002924 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002925 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2926 if (VDBG) log("NetworkFactory connected");
Etan Cohenae574a82019-01-08 12:09:18 -08002927 // Finish setting up the full connection
2928 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2929 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002930 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002931 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002932 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002933 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002934 final int score;
2935 final int serial;
2936 if (nai != null) {
2937 score = nai.getCurrentScore();
2938 serial = nai.factorySerialNumber;
2939 } else {
2940 score = 0;
2941 serial = NetworkFactory.SerialNumber.NONE;
2942 }
2943 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2944 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002945 }
2946 } else {
2947 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002948 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002949 }
2950 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2951 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2952 if (VDBG) log("NetworkAgent connected");
2953 // A network agent has requested a connection. Establish the connection.
2954 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2955 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2956 } else {
2957 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002958 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002959 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002960 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002961 synchronized (mNetworkForNetId) {
2962 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002963 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002964 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002965 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002966 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002967 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002968 }
2969 }
2970 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002971
Chalard Jean392971c2018-05-11 20:19:20 +09002972 // This is a no-op if it's called with a message designating a network that has
2973 // already been destroyed, because its reference will not be found in the relevant
2974 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002975 private void handleAsyncChannelDisconnected(Message msg) {
2976 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2977 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002978 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002979 } else {
2980 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2981 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002982 }
2983 }
2984
Chalard Jean392971c2018-05-11 20:19:20 +09002985 // Destroys a network, remove references to it from the internal state managed by
2986 // ConnectivityService, free its interfaces and clean up.
2987 // Must be called on the Handler thread.
2988 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2989 if (DBG) {
2990 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2991 }
lucaslinf80b83b2019-02-12 15:30:13 +08002992 // Clear all notifications of this network.
2993 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002994 // A network agent has disconnected.
2995 // TODO - if we move the logic to the network agent (have them disconnect
2996 // because they lost all their requests or because their score isn't good)
2997 // then they would disconnect organically, report their new state and then
2998 // disconnect the channel.
2999 if (nai.networkInfo.isConnected()) {
3000 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3001 null, null);
3002 }
3003 final boolean wasDefault = isDefaultNetwork(nai);
3004 if (wasDefault) {
3005 mDefaultInetConditionPublished = 0;
3006 // Log default network disconnection before required book-keeping.
3007 // Let rematchAllNetworksAndRequests() below record a new default network event
3008 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
3009 // whose timestamps tell how long it takes to recover a default network.
3010 long now = SystemClock.elapsedRealtime();
3011 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
3012 }
3013 notifyIfacesChangedForNetworkStats();
3014 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3015 // by other networks that are already connected. Perhaps that can be done by
3016 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3017 // of rematchAllNetworksAndRequests
3018 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulaie4135282019-01-03 18:50:15 +08003019 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09003020 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3021 // Disable wakeup packet monitoring for each interface.
3022 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3023 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003024 try {
3025 nai.networkMonitor().notifyNetworkDisconnected();
3026 } catch (RemoteException e) {
3027 e.rethrowFromSystemServer();
3028 }
Chalard Jean392971c2018-05-11 20:19:20 +09003029 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09003030 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09003031 synchronized (mNetworkForNetId) {
3032 // Remove the NetworkAgent, but don't mark the netId as
3033 // available until we've told netd to delete it below.
3034 mNetworkForNetId.remove(nai.network.netId);
3035 }
3036 // Remove all previously satisfied requests.
3037 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3038 NetworkRequest request = nai.requestAt(i);
3039 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3040 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3041 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09003042 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003043 }
3044 }
3045 nai.clearLingerState();
3046 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003047 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003048 notifyLockdownVpn(nai);
3049 ensureNetworkTransitionWakelock(nai.name());
3050 }
3051 mLegacyTypeTracker.remove(nai, wasDefault);
3052 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3053 updateAllVpnsCapabilities();
3054 }
3055 rematchAllNetworksAndRequests(null, 0);
3056 mLingerMonitor.noteDisconnect(nai);
3057 if (nai.created) {
3058 // Tell netd to clean up the configuration for this network
3059 // (routing rules, DNS, etc).
3060 // This may be slow as it requires a lot of netd shelling out to ip and
3061 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3062 // after we've rematched networks with requests which should make a potential
3063 // fallback network the default or requested a new network from the
3064 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3065 // long time.
3066 try {
Luke Huang65914772019-03-16 00:31:46 +08003067 mNetd.networkDestroy(nai.network.netId);
3068 } catch (RemoteException | ServiceSpecificException e) {
3069 loge("Exception destroying network: " + e);
Chalard Jean392971c2018-05-11 20:19:20 +09003070 }
3071 mDnsManager.removeNetwork(nai.network);
3072 }
3073 synchronized (mNetworkForNetId) {
3074 mNetIdInUse.delete(nai.network.netId);
3075 }
3076 }
3077
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003078 // If this method proves to be too slow then we can maintain a separate
3079 // pendingIntent => NetworkRequestInfo map.
3080 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3081 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3082 Intent intent = pendingIntent.getIntent();
3083 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3084 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3085 if (existingPendingIntent != null &&
3086 existingPendingIntent.getIntent().filterEquals(intent)) {
3087 return entry.getValue();
3088 }
3089 }
3090 return null;
3091 }
3092
3093 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3094 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3095
3096 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3097 if (existingRequest != null) { // remove the existing request.
3098 if (DBG) log("Replacing " + existingRequest.request + " with "
3099 + nri.request + " because their intents matched.");
Etan Cohenae574a82019-01-08 12:09:18 -08003100 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3101 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003102 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003103 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003104 }
3105
Erik Klineda4bfa82015-04-30 12:58:40 +09003106 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003107 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003108 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003109 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003110 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003111 if (nri.request.networkCapabilities.hasSignalStrength() &&
3112 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3113 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003114 }
3115 }
3116 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003117 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003118 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09003119 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003120 }
3121 }
3122
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003123 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3124 int callingUid) {
3125 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3126 if (nri != null) {
Etan Cohenae574a82019-01-08 12:09:18 -08003127 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003128 }
3129 }
3130
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003131 // Determines whether the network is the best (or could become the best, if it validated), for
3132 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3133 // on the value of reason:
3134 //
3135 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3136 // then it should be torn down.
3137 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3138 // then it should be lingered.
3139 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3140 final int numRequests;
3141 switch (reason) {
3142 case TEARDOWN:
3143 numRequests = nai.numRequestNetworkRequests();
3144 break;
3145 case LINGER:
3146 numRequests = nai.numForegroundNetworkRequests();
3147 break;
3148 default:
3149 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3150 return true;
3151 }
3152
3153 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003154 return false;
3155 }
Paul Jensene0988542015-06-25 15:30:08 -04003156 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003157 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3158 // Background requests don't affect lingering.
3159 continue;
3160 }
3161
Paul Jensene0988542015-06-25 15:30:08 -04003162 // If this Network is already the highest scoring Network for a request, or if
3163 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003164 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003165 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003166 // Note that this catches two important cases:
3167 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3168 // is currently satisfying the request. This is desirable when
3169 // cellular ends up validating but WiFi does not.
3170 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003171 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003172 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003173 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003174 nai.getCurrentScoreAsValidated())) {
3175 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003176 }
3177 }
Paul Jensene0988542015-06-25 15:30:08 -04003178 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003179 }
3180
Erik Klineacdd6392016-07-07 16:50:58 +09003181 private NetworkRequestInfo getNriForAppRequest(
3182 NetworkRequest request, int callingUid, String requestedOperation) {
3183 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3184
Robert Greenwalt9258c642014-03-26 16:47:06 -07003185 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003186 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003187 log(String.format("UID %d attempted to %s for unowned request %s",
3188 callingUid, requestedOperation, nri));
3189 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003190 }
Erik Klineacdd6392016-07-07 16:50:58 +09003191 }
3192
3193 return nri;
3194 }
3195
Erik Kline57faba92015-11-25 12:49:38 +09003196 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003197 if (mNetworkRequests.get(nri.request) == null) {
3198 return;
Erik Kline57faba92015-11-25 12:49:38 +09003199 }
Hugo Benichicd952782017-09-20 11:20:14 +09003200 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003201 return;
3202 }
3203 if (VDBG || (DBG && nri.request.isRequest())) {
3204 log("releasing " + nri.request + " (timeout)");
3205 }
3206 handleRemoveNetworkRequest(nri);
3207 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003208 }
3209
Etan Cohenae574a82019-01-08 12:09:18 -08003210 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3211 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003212 final NetworkRequestInfo nri =
3213 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3214 if (nri == null) {
3215 return;
Erik Kline57faba92015-11-25 12:49:38 +09003216 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003217 if (VDBG || (DBG && nri.request.isRequest())) {
3218 log("releasing " + nri.request + " (release request)");
3219 }
3220 handleRemoveNetworkRequest(nri);
Etan Cohenae574a82019-01-08 12:09:18 -08003221 if (callOnUnavailable) {
3222 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3223 }
Erik Kline57faba92015-11-25 12:49:38 +09003224 }
Erik Klineacdd6392016-07-07 16:50:58 +09003225
Hugo Benichidba33db2017-03-23 22:40:44 +09003226 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003227 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003228 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003229
Erik Klineacdd6392016-07-07 16:50:58 +09003230 synchronized (mUidToNetworkRequestCount) {
3231 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3232 if (requests < 1) {
3233 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3234 nri.mUid);
3235 } else if (requests == 1) {
3236 mUidToNetworkRequestCount.removeAt(
3237 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3238 } else {
3239 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3240 }
3241 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003242
Erik Klineacdd6392016-07-07 16:50:58 +09003243 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3244 if (nri.request.isRequest()) {
3245 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003246 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003247 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003248 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003249 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003250 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003251 log(" Removing from current network " + nai.name() +
3252 ", leaving " + nai.numNetworkRequests() + " requests.");
3253 }
3254 // If there are still lingered requests on this network, don't tear it down,
3255 // but resume lingering instead.
3256 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003257 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003258 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3259 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003260 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003261 wasKept = true;
3262 }
Hugo Benichicd952782017-09-20 11:20:14 +09003263 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003264 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3265 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003266 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003267 }
Erik Klineacdd6392016-07-07 16:50:58 +09003268 }
3269
Erik Klineacdd6392016-07-07 16:50:58 +09003270 // Maintain the illusion. When this request arrived, we might have pretended
3271 // that a network connected to serve it, even though the network was already
3272 // connected. Now that this request has gone away, we might have to pretend
3273 // that the network disconnected. LegacyTypeTracker will generate that
3274 // phantom disconnect for this type.
3275 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3276 boolean doRemove = true;
3277 if (wasKept) {
3278 // check if any of the remaining requests for this network are for the
3279 // same legacy type - if so, don't remove the nai
3280 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3281 NetworkRequest otherRequest = nai.requestAt(i);
3282 if (otherRequest.legacyType == nri.request.legacyType &&
3283 otherRequest.isRequest()) {
3284 if (DBG) log(" still have other legacy request - leaving");
3285 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003286 }
3287 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003288 }
3289
Erik Klineacdd6392016-07-07 16:50:58 +09003290 if (doRemove) {
3291 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003292 }
3293 }
Erik Klineacdd6392016-07-07 16:50:58 +09003294
3295 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3296 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3297 nri.request);
3298 }
3299 } else {
3300 // listens don't have a singular affectedNetwork. Check all networks to see
3301 // if this listen request applies and remove it.
3302 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3303 nai.removeRequest(nri.request.requestId);
3304 if (nri.request.networkCapabilities.hasSignalStrength() &&
3305 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3306 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3307 }
3308 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003309 }
3310 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003311
Lorenzo Colitti18660282016-07-04 12:55:44 +09003312 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003313 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003314 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003315 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003316 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003317 }
3318
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003319 @Override
lucasline252a742019-03-12 13:08:03 +08003320 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3321 enforceNetworkStackSettingsOrSetup();
3322 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3323 encodeBool(accept), encodeBool(always), network));
3324 }
3325
3326 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003327 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003328 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003329 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3330 }
3331
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003332 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3333 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3334 " accept=" + accept + " always=" + always);
3335
3336 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3337 if (nai == null) {
3338 // Nothing to do.
3339 return;
3340 }
3341
3342 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003343 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003344 return;
3345 }
3346
3347 if (!nai.networkMisc.explicitlySelected) {
3348 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3349 }
3350
3351 if (accept != nai.networkMisc.acceptUnvalidated) {
3352 int oldScore = nai.getCurrentScore();
3353 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003354 // If network becomes partial connectivity and user already accepted to use this
3355 // network, we should respect the user's option and don't need to popup the
3356 // PARTIAL_CONNECTIVITY notification to user again.
3357 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003358 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003359 sendUpdatedScoreToFactories(nai);
3360 }
3361
3362 if (always) {
3363 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003364 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003365 }
3366
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003367 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003368 // Tell the NetworkAgent to not automatically reconnect to the network.
3369 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003370 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003371 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003372 }
3373
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003374 }
3375
lucasline252a742019-03-12 13:08:03 +08003376 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3377 boolean always) {
3378 if (DBG) {
3379 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3380 + " always=" + always);
3381 }
3382
3383 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3384 if (nai == null) {
3385 // Nothing to do.
3386 return;
3387 }
3388
3389 if (nai.lastValidated) {
3390 // The network validated while the dialog box was up. Take no action.
3391 return;
3392 }
3393
3394 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3395 nai.networkMisc.acceptPartialConnectivity = accept;
3396 }
3397
3398 // TODO: Use the current design or save the user choice into IpMemoryStore.
3399 if (always) {
3400 nai.asyncChannel.sendMessage(
3401 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3402 }
3403
3404 if (!accept) {
3405 // Tell the NetworkAgent to not automatically reconnect to the network.
3406 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3407 // Tear down the network.
3408 teardownUnneededNetwork(nai);
3409 } else {
lucaslin43338992019-03-20 18:21:59 +08003410 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3411 // result in a partial connectivity result which will be processed by
3412 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003413 try {
lucaslin43338992019-03-20 18:21:59 +08003414 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003415 } catch (RemoteException e) {
3416 e.rethrowFromSystemServer();
3417 }
3418 }
3419 }
3420
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003421 private void handleSetAvoidUnvalidated(Network network) {
3422 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3423 if (nai == null || nai.lastValidated) {
3424 // Nothing to do. The network either disconnected or revalidated.
3425 return;
3426 }
3427 if (!nai.avoidUnvalidated) {
3428 int oldScore = nai.getCurrentScore();
3429 nai.avoidUnvalidated = true;
3430 rematchAllNetworksAndRequests(nai, oldScore);
3431 sendUpdatedScoreToFactories(nai);
3432 }
3433 }
3434
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003435 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003436 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003437 mHandler.sendMessageDelayed(
3438 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3439 PROMPT_UNVALIDATED_DELAY_MS);
3440 }
3441
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003442 @Override
3443 public void startCaptivePortalApp(Network network) {
3444 enforceConnectivityInternalPermission();
3445 mHandler.post(() -> {
3446 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3447 if (nai == null) return;
3448 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003449 try {
3450 nai.networkMonitor().launchCaptivePortalApp();
3451 } catch (RemoteException e) {
3452 e.rethrowFromSystemServer();
3453 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003454 });
3455 }
3456
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003457 /**
3458 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3459 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003460 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003461 * @param appExtras Bundle to use as intent extras for the captive portal application.
3462 * Must be treated as opaque to avoid preventing the captive portal app to
3463 * update its arguments.
3464 */
3465 @Override
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003466 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003467 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3468
3469 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3470 appIntent.putExtras(appExtras);
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003471 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3472 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003473 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3474
3475 Binder.withCleanCallingIdentity(() ->
3476 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3477 }
3478
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003479 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3480 private final Network mNetwork;
3481
3482 private CaptivePortalImpl(Network network) {
3483 mNetwork = network;
3484 }
3485
3486 @Override
3487 public void appResponse(final int response) throws RemoteException {
3488 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3489 enforceSettingsPermission();
3490 }
3491
3492 // getNetworkAgentInfoForNetwork is thread-safe
3493 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3494 if (nai == null) return;
3495
3496 // nai.networkMonitor() is thread-safe
3497 final INetworkMonitor nm = nai.networkMonitor();
3498 if (nm == null) return;
3499
3500 final long token = Binder.clearCallingIdentity();
3501 try {
3502 nm.notifyCaptivePortalAppFinished(response);
3503 } finally {
3504 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3505 Binder.restoreCallingIdentity(token);
3506 }
3507 }
3508
3509 @Override
3510 public void logEvent(int eventId, String packageName) {
3511 enforceSettingsPermission();
3512
3513 new MetricsLogger().action(eventId, packageName);
3514 }
3515 }
3516
Hugo Benichic8e9e122016-09-14 23:23:08 +00003517 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003518 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003519 }
3520
Remi NGUYEN VAN24ec3ff2019-03-22 17:16:52 +09003521 /**
3522 * Return whether the device should maintain continuous, working connectivity by switching away
3523 * from WiFi networks having no connectivity.
3524 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3525 */
3526 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003527 if (!checkNetworkStackPermission()) {
3528 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3529 }
3530 return avoidBadWifi();
3531 }
3532
3533
Erik Kline065ab6e2016-10-02 18:02:14 +09003534 private void rematchForAvoidBadWifiUpdate() {
3535 rematchAllNetworksAndRequests(null, 0);
3536 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3537 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3538 sendUpdatedScoreToFactories(nai);
3539 }
3540 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003541 }
3542
Erik Kline065ab6e2016-10-02 18:02:14 +09003543 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003544 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003545 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003546 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003547 if (!configRestrict) {
3548 pw.println("Bad Wi-Fi avoidance: unrestricted");
3549 return;
3550 }
3551
3552 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3553 pw.increaseIndent();
3554 pw.println("Config restrict: " + configRestrict);
3555
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003556 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003557 String description;
3558 // Can't use a switch statement because strings are legal case labels, but null is not.
3559 if ("0".equals(value)) {
3560 description = "get stuck";
3561 } else if (value == null) {
3562 description = "prompt";
3563 } else if ("1".equals(value)) {
3564 description = "avoid";
3565 } else {
3566 description = value + " (?)";
3567 }
3568 pw.println("User setting: " + description);
3569 pw.println("Network overrides:");
3570 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003571 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003572 if (nai.avoidUnvalidated) {
3573 pw.println(nai.name());
3574 }
3575 }
3576 pw.decreaseIndent();
3577 pw.decreaseIndent();
3578 }
3579
lucaslind2e045e02019-01-24 15:55:30 +08003580 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003581 final String action;
3582 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003583 case LOGGED_IN:
3584 action = Settings.ACTION_WIFI_SETTINGS;
3585 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3586 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3587 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3588 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003589 case NO_INTERNET:
3590 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3591 break;
3592 case LOST_INTERNET:
3593 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3594 break;
lucasline252a742019-03-12 13:08:03 +08003595 case PARTIAL_CONNECTIVITY:
3596 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3597 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003598 default:
3599 Slog.wtf(TAG, "Unknown notification type " + type);
3600 return;
3601 }
3602
3603 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003604 if (type != NotificationType.LOGGED_IN) {
3605 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3606 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3607 intent.setClassName("com.android.settings",
3608 "com.android.settings.wifi.WifiNoInternetDialog");
3609 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003610
3611 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3612 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3613 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3614 }
3615
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003616 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003617 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003618 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3619
lucasline252a742019-03-12 13:08:03 +08003620 // Only prompt if the network is unvalidated or network has partial internet connectivity
3621 // and was explicitly selected by the user, and if we haven't already been told to switch
3622 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3623 // because we're already prompting the user to sign in.
3624 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3625 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003626 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3627 // we should reevaluate how to handle acceptPartialConnectivity when network just
3628 // connected.
lucasline252a742019-03-12 13:08:03 +08003629 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003630 return;
3631 }
lucasline252a742019-03-12 13:08:03 +08003632 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3633 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3634 // popup the notification immediately when the network is partial connectivity.
3635 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003636 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003637 } else {
3638 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3639 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003640 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003641
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003642 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3643 NetworkCapabilities nc = nai.networkCapabilities;
3644 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003645
lucasline252a742019-03-12 13:08:03 +08003646 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3647 return;
3648 }
3649
3650 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003651 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003652 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003653 }
3654
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003655 @Override
3656 public int getMultipathPreference(Network network) {
3657 enforceAccessPermission();
3658
3659 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003660 if (nai != null && nai.networkCapabilities
3661 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003662 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3663 }
3664
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003665 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3666 if (networkPreference != null) {
3667 return networkPreference;
3668 }
3669
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003670 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3671 }
3672
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003673 @Override
3674 public NetworkRequest getDefaultRequest() {
3675 return mDefaultRequest;
3676 }
3677
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003678 private class InternalHandler extends Handler {
3679 public InternalHandler(Looper looper) {
3680 super(looper);
3681 }
3682
3683 @Override
3684 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003685 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003686 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003687 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003688 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003689 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003690 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003691 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003692 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003693 break;
3694 }
Jason Monkdecd2952013-10-10 14:02:51 -04003695 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003696 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003697 break;
3698 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003699 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003700 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3701 break;
3702 }
3703 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3704 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003705 break;
3706 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003707 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003708 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3709 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3710 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003711 break;
3712 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003713 case EVENT_REGISTER_NETWORK_REQUEST:
3714 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003715 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003716 break;
3717 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003718 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3719 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003720 handleRegisterNetworkRequestWithIntent(msg);
3721 break;
3722 }
Erik Kline57faba92015-11-25 12:49:38 +09003723 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3724 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3725 handleTimedOutNetworkRequest(nri);
3726 break;
3727 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003728 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3729 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3730 break;
3731 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003732 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenae574a82019-01-08 12:09:18 -08003733 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3734 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003735 break;
3736 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003737 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003738 Network network = (Network) msg.obj;
3739 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003740 break;
3741 }
lucasline252a742019-03-12 13:08:03 +08003742 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3743 Network network = (Network) msg.obj;
3744 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3745 toBool(msg.arg2));
3746 break;
3747 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003748 case EVENT_SET_AVOID_UNVALIDATED: {
3749 handleSetAvoidUnvalidated((Network) msg.obj);
3750 break;
3751 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003752 case EVENT_PROMPT_UNVALIDATED: {
3753 handlePromptUnvalidated((Network) msg.obj);
3754 break;
3755 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003756 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3757 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003758 break;
3759 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003760 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003761 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003762 mKeepaliveTracker.handleStartKeepalive(msg);
3763 break;
3764 }
3765 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003766 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003767 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3768 int slot = msg.arg1;
3769 int reason = msg.arg2;
3770 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3771 break;
3772 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003773 case EVENT_SYSTEM_READY: {
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003774 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003775 break;
3776 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003777 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003778 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003779 break;
3780 }
Erik Klinea24d4592018-01-11 21:07:29 +09003781 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3782 handlePrivateDnsSettingsChanged();
3783 break;
dalyk7301aa42018-03-05 12:42:22 -05003784 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3785 handlePrivateDnsValidationUpdate(
3786 (PrivateDnsValidationUpdate) msg.obj);
3787 break;
junyulai05986c62018-08-07 19:50:45 +08003788 case EVENT_UID_RULES_CHANGED:
3789 handleUidRulesChanged(msg.arg1, msg.arg2);
3790 break;
3791 case EVENT_DATA_SAVER_CHANGED:
3792 handleRestrictBackgroundChanged(toBool(msg.arg1));
3793 break;
lucaslind2e045e02019-01-24 15:55:30 +08003794 case EVENT_TIMEOUT_NOTIFICATION:
3795 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3796 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 }
3798 }
3799 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003800
3801 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003802 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003803 public int tether(String iface, String callerPkg) {
3804 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003805 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003806 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003807 } else {
3808 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3809 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003810 }
3811
3812 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003813 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003814 public int untether(String iface, String callerPkg) {
3815 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003816
3817 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003818 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003819 } else {
3820 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3821 }
3822 }
3823
3824 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003825 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003826 public int getLastTetherError(String iface) {
3827 enforceTetherAccessPermission();
3828
3829 if (isTetheringSupported()) {
3830 return mTethering.getLastTetherError(iface);
3831 } else {
3832 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3833 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003834 }
3835
3836 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003837 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003838 public String[] getTetherableUsbRegexs() {
3839 enforceTetherAccessPermission();
3840 if (isTetheringSupported()) {
3841 return mTethering.getTetherableUsbRegexs();
3842 } else {
3843 return new String[0];
3844 }
3845 }
3846
Lorenzo Colitti18660282016-07-04 12:55:44 +09003847 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003848 public String[] getTetherableWifiRegexs() {
3849 enforceTetherAccessPermission();
3850 if (isTetheringSupported()) {
3851 return mTethering.getTetherableWifiRegexs();
3852 } else {
3853 return new String[0];
3854 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003855 }
3856
Lorenzo Colitti18660282016-07-04 12:55:44 +09003857 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003858 public String[] getTetherableBluetoothRegexs() {
3859 enforceTetherAccessPermission();
3860 if (isTetheringSupported()) {
3861 return mTethering.getTetherableBluetoothRegexs();
3862 } else {
3863 return new String[0];
3864 }
3865 }
3866
Lorenzo Colitti18660282016-07-04 12:55:44 +09003867 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003868 public int setUsbTethering(boolean enable, String callerPkg) {
3869 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003870 if (isTetheringSupported()) {
3871 return mTethering.setUsbTethering(enable);
3872 } else {
3873 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3874 }
3875 }
3876
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003877 // TODO - move iface listing, queries, etc to new module
3878 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003879 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003880 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003881 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003882 return mTethering.getTetherableIfaces();
3883 }
3884
Lorenzo Colitti18660282016-07-04 12:55:44 +09003885 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003886 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003887 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003888 return mTethering.getTetheredIfaces();
3889 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003890
Lorenzo Colitti18660282016-07-04 12:55:44 +09003891 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003892 public String[] getTetheringErroredIfaces() {
3893 enforceTetherAccessPermission();
3894 return mTethering.getErroredIfaces();
3895 }
3896
Lorenzo Colitti18660282016-07-04 12:55:44 +09003897 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003898 public String[] getTetheredDhcpRanges() {
3899 enforceConnectivityInternalPermission();
3900 return mTethering.getTetheredDhcpRanges();
3901 }
3902
Udam Saini0e94c362017-06-07 12:06:28 -07003903 @Override
3904 public boolean isTetheringSupported(String callerPkg) {
3905 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3906 return isTetheringSupported();
3907 }
3908
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003909 // if ro.tether.denied = true we default to no tethering
3910 // gservices could set the secure setting to 1 though to enable it on a build where it
3911 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003912 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003913 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3914 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3915 Settings.Global.TETHER_SUPPORTED, defaultVal));
3916 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003917 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003918
3919 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3920 boolean adminUser = false;
3921 final long token = Binder.clearCallingIdentity();
3922 try {
3923 adminUser = mUserManager.isAdminUser();
3924 } finally {
3925 Binder.restoreCallingIdentity(token);
3926 }
3927
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003928 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003929 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003930
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003931 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003932 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3933 String callerPkg) {
3934 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003935 if (!isTetheringSupported()) {
3936 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3937 return;
3938 }
3939 mTethering.startTethering(type, receiver, showProvisioningUi);
3940 }
3941
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003942 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003943 public void stopTethering(int type, String callerPkg) {
3944 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003945 mTethering.stopTethering(type);
3946 }
3947
markchienf2731272019-01-16 17:44:13 +08003948 /**
3949 * Get the latest value of the tethering entitlement check.
3950 *
3951 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3952 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3953 * if it's really needed.
3954 */
3955 @Override
markchien9554abf2019-03-06 16:25:00 +08003956 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003957 boolean showEntitlementUi, String callerPkg) {
3958 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003959 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003960 }
3961
markchien6ea34542019-02-27 14:56:11 +08003962 /** Register tethering event callback. */
3963 @Override
3964 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3965 String callerPkg) {
3966 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3967 mTethering.registerTetheringEventCallback(callback);
3968 }
3969
3970 /** Unregister tethering event callback. */
3971 @Override
3972 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3973 String callerPkg) {
3974 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3975 mTethering.unregisterTetheringEventCallback(callback);
3976 }
3977
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003978 // Called when we lose the default network and have no replacement yet.
3979 // This will automatically be cleared after X seconds or a new default network
3980 // becomes CONNECTED, whichever happens first. The timer is started by the
3981 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003982 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003983 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003984 if (mNetTransitionWakeLock.isHeld()) {
3985 return;
3986 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003987 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003988 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3989 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003990 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003991 mWakelockLogs.log("ACQUIRE for " + forWhom);
3992 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3993 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003994 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003995
Hugo Benichi4c31b342017-03-30 23:18:10 +09003996 // Called when we gain a new default network to release the network transition wakelock in a
3997 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3998 // message is cancelled.
3999 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004000 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09004001 if (!mNetTransitionWakeLock.isHeld()) {
4002 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004003 }
4004 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004005 // Cancel self timeout on wakelock hold.
4006 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4007 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4008 mHandler.sendMessageDelayed(msg, 1000);
4009 }
4010
4011 // Called when either message of ensureNetworkTransitionWakelock or
4012 // scheduleReleaseNetworkTransitionWakelock is processed.
4013 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4014 String event = eventName(eventId);
4015 synchronized (this) {
4016 if (!mNetTransitionWakeLock.isHeld()) {
4017 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4018 Slog.w(TAG, "expected Net Transition WakeLock to be held");
4019 return;
4020 }
4021 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09004022 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4023 mTotalWakelockDurationMs += lockDuration;
4024 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4025 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004026 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004027 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004028 }
4029
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004030 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004031 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004032 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004033 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004034 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004035 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004036 }
4037
Lorenzo Colitti18660282016-07-04 12:55:44 +09004038 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004039 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004040 enforceAccessPermission();
4041 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004042 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004043 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004044 mHandler.sendMessage(
4045 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4046 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004047
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004048 private void handleReportNetworkConnectivity(
4049 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004050 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004051 if (network == null) {
4052 nai = getDefaultNetwork();
4053 } else {
4054 nai = getNetworkAgentInfoForNetwork(network);
4055 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004056 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4057 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4058 return;
4059 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004060 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004061 if (hasConnectivity == nai.lastValidated) {
4062 return;
4063 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004064 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004065 int netid = nai.network.netId;
4066 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004067 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004068 // Validating a network that has not yet connected could result in a call to
4069 // rematchNetworkAndRequests() which is not meant to work on such networks.
4070 if (!nai.everConnected) {
4071 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004072 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004073 LinkProperties lp = getLinkProperties(nai);
4074 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4075 return;
4076 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004077 try {
4078 nai.networkMonitor().forceReevaluation(uid);
4079 } catch (RemoteException e) {
4080 e.rethrowFromSystemServer();
4081 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 }
4083
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004084 /**
4085 * Returns information about the proxy a certain network is using. If given a null network, it
4086 * it will return the proxy for the bound network for the caller app or the default proxy if
4087 * none.
4088 *
4089 * @param network the network we want to get the proxy information for.
4090 * @return Proxy information if a network has a proxy configured, or otherwise null.
4091 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004092 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004093 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004094 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004095 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004096 if (network == null) {
4097 // Get the network associated with the calling UID.
4098 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4099 true);
4100 if (activeNetwork == null) {
4101 return null;
4102 }
4103 return getLinkPropertiesProxyInfo(activeNetwork);
4104 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4105 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4106 // caller may not have.
4107 return getLinkPropertiesProxyInfo(network);
4108 }
4109 // No proxy info available if the calling UID does not have network access.
4110 return null;
4111 }
4112
4113 @VisibleForTesting
4114 protected boolean queryUserAccess(int uid, int netId) {
4115 return NetworkUtils.queryUserAccess(uid, netId);
4116 }
4117
4118 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004119 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4120 if (nai == null) return null;
4121 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004122 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4123 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004124 }
4125 }
4126
Chalard Jean3c443fc2018-06-07 18:37:59 +09004127 @Override
4128 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004129 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004130 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004131 }
4132
Chalard Jean5afbc832018-06-07 18:02:37 +09004133 @Override
4134 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004135 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004136 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004137 }
4138
Jason Monk207900c2014-04-25 15:00:09 -04004139 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004140 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004141 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004142 proxy = null;
4143 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004144 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004145 }
4146
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004147 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4148 // when any network changes proxy.
4149 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4150 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004151 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004152 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4153 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4154
Chalard Jean4949dd72018-06-07 17:41:29 +09004155 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004156 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004157 }
4158 }
4159
Robert Greenwalt434203a2010-10-11 16:00:27 -07004160 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004161 final private HashMap<Uri, Integer> mUriEventMap;
4162 final private Context mContext;
4163 final private Handler mHandler;
4164
4165 SettingsObserver(Context context, Handler handler) {
4166 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004167 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004168 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004169 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004170 }
4171
Erik Klineda4bfa82015-04-30 12:58:40 +09004172 void observe(Uri uri, int what) {
4173 mUriEventMap.put(uri, what);
4174 final ContentResolver resolver = mContext.getContentResolver();
4175 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004176 }
4177
4178 @Override
4179 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004180 Slog.wtf(TAG, "Should never be reached.");
4181 }
4182
4183 @Override
4184 public void onChange(boolean selfChange, Uri uri) {
4185 final Integer what = mUriEventMap.get(uri);
4186 if (what != null) {
4187 mHandler.obtainMessage(what.intValue()).sendToTarget();
4188 } else {
4189 loge("No matching event to send for URI=" + uri);
4190 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004191 }
4192 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004193
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004194 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004195 Slog.d(TAG, s);
4196 }
4197
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004198 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004199 Slog.e(TAG, s);
4200 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004201
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004202 private static void loge(String s, Throwable t) {
4203 Slog.e(TAG, s, t);
4204 }
4205
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004206 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004207 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004208 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4209 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4210 *
4211 * @param oldPackage Package name of the application which currently controls VPN, which will
4212 * be replaced. If there is no such application, this should should either be
4213 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4214 * @param newPackage Package name of the application which should gain control of VPN, or
4215 * {@code null} to disable.
4216 * @param userId User for whom to prepare the new VPN.
4217 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004218 * @hide
4219 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004220 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004221 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4222 int userId) {
4223 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004224
Hugo Benichi20035e02017-04-26 14:53:28 +09004225 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004226 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004227 Vpn vpn = mVpns.get(userId);
4228 if (vpn != null) {
4229 return vpn.prepare(oldPackage, newPackage);
4230 } else {
4231 return false;
4232 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004233 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004234 }
4235
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004236 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004237 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4238 * This method is used by system-privileged apps.
4239 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4240 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4241 *
4242 * @param packageName The package for which authorization state should change.
4243 * @param userId User for whom {@code packageName} is installed.
4244 * @param authorized {@code true} if this app should be able to start a VPN connection without
4245 * explicit user approval, {@code false} if not.
4246 *
Jeff Davidson05542602014-08-11 14:07:27 -07004247 * @hide
4248 */
4249 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004250 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4251 enforceCrossUserPermission(userId);
4252
Hugo Benichi20035e02017-04-26 14:53:28 +09004253 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004254 Vpn vpn = mVpns.get(userId);
4255 if (vpn != null) {
4256 vpn.setPackageAuthorization(packageName, authorized);
4257 }
Jeff Davidson05542602014-08-11 14:07:27 -07004258 }
4259 }
4260
4261 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004262 * Configure a TUN interface and return its file descriptor. Parameters
4263 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004264 * and not available in ConnectivityManager. Permissions are checked in
4265 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004266 * @hide
4267 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004268 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004269 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004270 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004271 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004272 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004273 return mVpns.get(user).establish(config);
4274 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004275 }
4276
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004277 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004278 * Start legacy VPN, controlling native daemons as needed. Creates a
4279 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004280 */
4281 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004282 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004283 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004284 final LinkProperties egress = getActiveLinkProperties();
4285 if (egress == null) {
4286 throw new IllegalStateException("Missing active network connection");
4287 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004288 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004289 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004290 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4291 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004292 }
4293
4294 /**
4295 * Return the information of the ongoing legacy VPN. This method is used
4296 * by VpnSettings and not available in ConnectivityManager. Permissions
4297 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004298 */
4299 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004300 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4301 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004302
Hugo Benichi20035e02017-04-26 14:53:28 +09004303 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004304 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004305 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004306 }
4307
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004308 /**
Varun Anand02c50ef2019-02-07 14:13:13 -08004309 * Return the information of all ongoing VPNs.
4310 *
4311 * <p>This method is used to update NetworkStatsService.
4312 *
4313 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004314 */
Varun Anand02c50ef2019-02-07 14:13:13 -08004315 private VpnInfo[] getAllVpnInfo() {
4316 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004317 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004318 if (mLockdownEnabled) {
4319 return new VpnInfo[0];
4320 }
4321
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004322 List<VpnInfo> infoList = new ArrayList<>();
4323 for (int i = 0; i < mVpns.size(); i++) {
4324 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4325 if (info != null) {
4326 infoList.add(info);
4327 }
4328 }
4329 return infoList.toArray(new VpnInfo[infoList.size()]);
4330 }
4331 }
4332
4333 /**
4334 * @return VPN information for accounting, or null if we can't retrieve all required
4335 * information, e.g primary underlying iface.
4336 */
4337 @Nullable
4338 private VpnInfo createVpnInfo(Vpn vpn) {
4339 VpnInfo info = vpn.getVpnInfo();
4340 if (info == null) {
4341 return null;
4342 }
4343 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4344 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4345 // the underlyingNetworks list.
4346 if (underlyingNetworks == null) {
4347 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4348 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4349 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4350 }
4351 } else if (underlyingNetworks.length > 0) {
4352 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4353 if (linkProperties != null) {
4354 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4355 }
4356 }
4357 return info.primaryUnderlyingIface == null ? null : info;
4358 }
4359
4360 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004361 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4362 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004363 * Permissions are checked in Vpn class.
4364 * @hide
4365 */
4366 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004367 public VpnConfig getVpnConfig(int userId) {
4368 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004369 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004370 Vpn vpn = mVpns.get(userId);
4371 if (vpn != null) {
4372 return vpn.getVpnConfig();
4373 } else {
4374 return null;
4375 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004376 }
4377 }
4378
Chalard Jean6b65ec72018-05-18 22:02:56 +09004379 /**
4380 * Ask all VPN objects to recompute and update their capabilities.
4381 *
4382 * When underlying networks change, VPNs may have to update capabilities to reflect things
4383 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4384 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4385 * handler thread through their agent, this is asynchronous. When the capabilities objects
4386 * are computed they will be up-to-date as they are computed synchronously from here and
4387 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004388 */
4389 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004390 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004391 synchronized (mVpns) {
4392 for (int i = 0; i < mVpns.size(); i++) {
4393 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004394 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4395 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004396 }
4397 }
4398 }
4399
Varun Anand4fa80e82019-02-06 10:13:38 -08004400 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4401 ensureRunningOnConnectivityServiceThread();
4402 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4403 if (vpnNai == null || nc == null) {
4404 return;
4405 }
4406 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4407 }
4408
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004409 @Override
4410 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004411 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4412 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4413 return false;
4414 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004415
Hugo Benichi69744342017-11-27 10:57:16 +09004416 synchronized (mVpns) {
4417 // Tear down existing lockdown if profile was removed
4418 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4419 if (mLockdownEnabled) {
4420 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4421 if (profileTag == null) {
4422 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4423 return false;
4424 }
4425 String profileName = new String(profileTag);
4426 final VpnProfile profile = VpnProfile.decode(
4427 profileName, mKeyStore.get(Credentials.VPN + profileName));
4428 if (profile == null) {
4429 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4430 setLockdownTracker(null);
4431 return true;
4432 }
4433 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004434 Vpn vpn = mVpns.get(user);
4435 if (vpn == null) {
4436 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4437 return false;
4438 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004439 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004440 } else {
4441 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004442 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004443 }
4444
4445 return true;
4446 }
4447
4448 /**
4449 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4450 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4451 */
Hugo Benichi69744342017-11-27 10:57:16 +09004452 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004453 private void setLockdownTracker(LockdownVpnTracker tracker) {
4454 // Shutdown any existing tracker
4455 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004456 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4457 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004458 mLockdownTracker = null;
4459 if (existing != null) {
4460 existing.shutdown();
4461 }
4462
Robin Leec3736bc2017-03-10 16:19:54 +00004463 if (tracker != null) {
4464 mLockdownTracker = tracker;
4465 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004466 }
4467 }
4468
Hugo Benichi69744342017-11-27 10:57:16 +09004469 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004470 private void throwIfLockdownEnabled() {
4471 if (mLockdownEnabled) {
4472 throw new IllegalStateException("Unavailable in lockdown mode");
4473 }
4474 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004475
Robin Lee244ce8e2016-01-05 18:03:46 +00004476 /**
Robin Lee17e61832016-05-09 13:46:28 +01004477 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4478 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004479 *
Robin Lee17e61832016-05-09 13:46:28 +01004480 * @return {@code true} if the service was started, the service was already connected, or there
4481 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004482 */
Robin Lee17e61832016-05-09 13:46:28 +01004483 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004484 synchronized (mVpns) {
4485 Vpn vpn = mVpns.get(userId);
4486 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004487 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004488 // exists already.
4489 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4490 return false;
4491 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004492
Robin Lee812800c2016-05-13 15:38:08 +01004493 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004494 }
4495 }
4496
4497 @Override
Charles He36738632017-05-15 17:07:18 +01004498 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4499 enforceSettingsPermission();
4500 enforceCrossUserPermission(userId);
4501
4502 synchronized (mVpns) {
4503 Vpn vpn = mVpns.get(userId);
4504 if (vpn == null) {
4505 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4506 return false;
4507 }
4508 return vpn.isAlwaysOnPackageSupported(packageName);
4509 }
4510 }
4511
4512 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004513 public boolean setAlwaysOnVpnPackage(
4514 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4515 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004516 enforceCrossUserPermission(userId);
4517
Robin Lee244ce8e2016-01-05 18:03:46 +00004518 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004519 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4520 if (LockdownVpnTracker.isEnabled()) {
4521 return false;
4522 }
4523
Robin Lee244ce8e2016-01-05 18:03:46 +00004524 Vpn vpn = mVpns.get(userId);
4525 if (vpn == null) {
4526 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4527 return false;
4528 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004529 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004530 return false;
4531 }
Robin Lee17e61832016-05-09 13:46:28 +01004532 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004533 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004534 return false;
4535 }
4536 }
4537 return true;
4538 }
4539
4540 @Override
4541 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004542 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004543 enforceCrossUserPermission(userId);
4544
4545 synchronized (mVpns) {
4546 Vpn vpn = mVpns.get(userId);
4547 if (vpn == null) {
4548 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4549 return null;
4550 }
4551 return vpn.getAlwaysOnPackage();
4552 }
4553 }
4554
Wink Savilleab9321d2013-06-29 21:10:57 -07004555 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004556 public boolean isVpnLockdownEnabled(int userId) {
4557 enforceControlAlwaysOnVpnPermission();
4558 enforceCrossUserPermission(userId);
4559
4560 synchronized (mVpns) {
4561 Vpn vpn = mVpns.get(userId);
4562 if (vpn == null) {
4563 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4564 return false;
4565 }
4566 return vpn.getLockdown();
4567 }
4568 }
4569
4570 @Override
4571 public List<String> getVpnLockdownWhitelist(int userId) {
4572 enforceControlAlwaysOnVpnPermission();
4573 enforceCrossUserPermission(userId);
4574
4575 synchronized (mVpns) {
4576 Vpn vpn = mVpns.get(userId);
4577 if (vpn == null) {
4578 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4579 return null;
4580 }
4581 return vpn.getLockdownWhitelist();
4582 }
4583 }
4584
4585 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004586 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004587 // TODO: Remove? Any reason to trigger a provisioning check?
4588 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004589 }
4590
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004591 /** Location to an updatable file listing carrier provisioning urls.
4592 * An example:
4593 *
4594 * <?xml version="1.0" encoding="utf-8"?>
4595 * <provisioningUrls>
4596 * <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 -07004597 * </provisioningUrls>
4598 */
4599 private static final String PROVISIONING_URL_PATH =
4600 "/data/misc/radio/provisioning_urls.xml";
4601 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004602
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004603 /** XML tag for root element. */
4604 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4605 /** XML tag for individual url */
4606 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004607 /** XML attribute for mcc */
4608 private static final String ATTR_MCC = "mcc";
4609 /** XML attribute for mnc */
4610 private static final String ATTR_MNC = "mnc";
4611
Paul Jensen434dde82015-06-11 09:43:30 -04004612 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004613 FileReader fileReader = null;
4614 XmlPullParser parser = null;
4615 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004616
4617 try {
4618 fileReader = new FileReader(mProvisioningUrlFile);
4619 parser = Xml.newPullParser();
4620 parser.setInput(fileReader);
4621 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4622
4623 while (true) {
4624 XmlUtils.nextElement(parser);
4625
4626 String element = parser.getName();
4627 if (element == null) break;
4628
Paul Jensen434dde82015-06-11 09:43:30 -04004629 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004630 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4631 try {
4632 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4633 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4634 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4635 parser.next();
4636 if (parser.getEventType() == XmlPullParser.TEXT) {
4637 return parser.getText();
4638 }
4639 }
4640 }
4641 } catch (NumberFormatException e) {
4642 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4643 }
4644 }
4645 }
4646 return null;
4647 } catch (FileNotFoundException e) {
4648 loge("Carrier Provisioning Urls file not found");
4649 } catch (XmlPullParserException e) {
4650 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4651 } catch (IOException e) {
4652 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4653 } finally {
4654 if (fileReader != null) {
4655 try {
4656 fileReader.close();
4657 } catch (IOException e) {}
4658 }
4659 }
4660 return null;
4661 }
4662
Wink Saville42d4f082013-07-20 20:31:59 -07004663 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004664 public String getMobileProvisioningUrl() {
4665 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004666 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004667 if (TextUtils.isEmpty(url)) {
4668 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004669 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004670 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004671 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004672 }
Wink Saville8cf35602013-07-10 23:00:07 -07004673 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004674 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004675 String phoneNumber = mTelephonyManager.getLine1Number();
4676 if (TextUtils.isEmpty(phoneNumber)) {
4677 phoneNumber = "0000000000";
4678 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004679 url = String.format(url,
4680 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4681 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004682 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004683 }
4684
Wink Savilleab9321d2013-06-29 21:10:57 -07004685 return url;
4686 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004687
Wink Saville948282b2013-08-29 08:55:16 -07004688 @Override
4689 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004690 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004691 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004692 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4693 return;
4694 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004695 final long ident = Binder.clearCallingIdentity();
4696 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004697 // Concatenate the range of types onto the range of NetIDs.
4698 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4699 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004700 } finally {
4701 Binder.restoreCallingIdentity(ident);
4702 }
Wink Saville948282b2013-08-29 08:55:16 -07004703 }
Wink Saville7788c612013-08-29 14:57:08 -07004704
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004705 @Override
4706 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004707 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004708 final long ident = Binder.clearCallingIdentity();
4709 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004710 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004711 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004712 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4713 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004714 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004715 } finally {
4716 Binder.restoreCallingIdentity(ident);
4717 }
4718 }
4719
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004720 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004721 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004722 Vpn userVpn = mVpns.get(userId);
4723 if (userVpn != null) {
4724 loge("Starting user already has a VPN");
4725 return;
4726 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004727 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004728 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004729 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4730 updateLockdownVpn();
4731 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004732 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004733 }
4734
4735 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004736 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004737 Vpn userVpn = mVpns.get(userId);
4738 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004739 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004740 return;
4741 }
Robin Lee17e61832016-05-09 13:46:28 +01004742 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004743 mVpns.delete(userId);
4744 }
4745 }
4746
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004747 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004748 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004749 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004750 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004751 final int vpnsSize = mVpns.size();
4752 for (int i = 0; i < vpnsSize; i++) {
4753 Vpn vpn = mVpns.valueAt(i);
4754 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004755 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4756 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004757 }
4758 }
4759 }
4760
4761 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004762 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004763 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004764 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004765 final int vpnsSize = mVpns.size();
4766 for (int i = 0; i < vpnsSize; i++) {
4767 Vpn vpn = mVpns.valueAt(i);
4768 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004769 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4770 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004771 }
4772 }
4773 }
4774
junyulai2454b692018-11-01 17:16:31 +08004775 private void onPackageAdded(String packageName, int uid) {
4776 if (TextUtils.isEmpty(packageName) || uid < 0) {
4777 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4778 return;
4779 }
4780 mPermissionMonitor.onPackageAdded(packageName, uid);
4781 }
4782
junyulaiefb04d32018-11-12 22:39:30 +08004783 private void onPackageReplaced(String packageName, int uid) {
4784 if (TextUtils.isEmpty(packageName) || uid < 0) {
4785 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4786 return;
4787 }
4788 final int userId = UserHandle.getUserId(uid);
4789 synchronized (mVpns) {
4790 final Vpn vpn = mVpns.get(userId);
4791 if (vpn == null) {
4792 return;
4793 }
4794 // Legacy always-on VPN won't be affected since the package name is not set.
4795 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4796 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4797 + userId);
4798 vpn.startAlwaysOnVpn();
4799 }
4800 }
4801 }
4802
4803 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004804 if (TextUtils.isEmpty(packageName) || uid < 0) {
4805 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4806 return;
4807 }
4808 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004809
4810 final int userId = UserHandle.getUserId(uid);
4811 synchronized (mVpns) {
4812 final Vpn vpn = mVpns.get(userId);
4813 if (vpn == null) {
4814 return;
4815 }
4816 // Legacy always-on VPN won't be affected since the package name is not set.
4817 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4818 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4819 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004820 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004821 }
4822 }
junyulai2454b692018-11-01 17:16:31 +08004823 }
4824
Robin Lee89e7a692016-02-29 14:38:17 +00004825 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004826 synchronized (mVpns) {
4827 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4828 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4829 updateLockdownVpn();
4830 } else {
4831 startAlwaysOnVpn(userId);
4832 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004833 }
4834 }
4835
junyulai2454b692018-11-01 17:16:31 +08004836 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004837 @Override
4838 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004839 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004840 final String action = intent.getAction();
4841 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004842 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4843 final Uri packageData = intent.getData();
4844 final String packageName =
4845 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004846 if (userId == UserHandle.USER_NULL) return;
4847
Robin Lee323f29d2016-05-04 16:38:06 +01004848 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004849 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004850 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004851 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004852 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4853 onUserAdded(userId);
4854 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4855 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004856 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4857 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004858 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4859 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004860 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4861 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004862 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004863 final boolean isReplacing = intent.getBooleanExtra(
4864 Intent.EXTRA_REPLACING, false);
4865 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004866 }
4867 }
4868 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004869
Robin Lee95204e02017-01-27 11:59:22 +00004870 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4871 @Override
4872 public void onReceive(Context context, Intent intent) {
4873 // Try creating lockdown tracker, since user present usually means
4874 // unlocked keystore.
4875 updateLockdownVpn();
4876 mContext.unregisterReceiver(this);
4877 }
4878 };
4879
Chalard Jean4133a122018-06-04 13:33:12 +09004880 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4881 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004882
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004883 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4884 // Map from UID to number of NetworkRequests that UID has filed.
4885 @GuardedBy("mUidToNetworkRequestCount")
4886 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4887
Robert Greenwalta67be032014-05-16 15:49:14 -07004888 private static class NetworkFactoryInfo {
4889 public final String name;
4890 public final Messenger messenger;
4891 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004892 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004893
Chalard Jean08577fc2018-05-02 21:14:54 +09004894 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4895 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004896 this.name = name;
4897 this.messenger = messenger;
4898 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004899 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004900 }
4901 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004902
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004903 private void ensureNetworkRequestHasType(NetworkRequest request) {
4904 if (request.type == NetworkRequest.Type.NONE) {
4905 throw new IllegalArgumentException(
4906 "All NetworkRequests in ConnectivityService must have a type");
4907 }
4908 }
4909
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004910 /**
4911 * Tracks info about the requester.
4912 * Also used to notice when the calling process dies so we can self-expire
4913 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004914 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004915 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004916 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004917 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004918 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004919 final int mPid;
4920 final int mUid;
4921 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004922
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004923 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004924 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004925 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004926 mPendingIntent = pi;
4927 messenger = null;
4928 mBinder = null;
4929 mPid = getCallingPid();
4930 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004931 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004932 }
4933
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004934 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004935 super();
4936 messenger = m;
4937 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004938 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004939 mBinder = binder;
4940 mPid = getCallingPid();
4941 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004942 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004943 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004944
4945 try {
4946 mBinder.linkToDeath(this, 0);
4947 } catch (RemoteException e) {
4948 binderDied();
4949 }
4950 }
4951
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004952 private void enforceRequestCountLimit() {
4953 synchronized (mUidToNetworkRequestCount) {
4954 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4955 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004956 throw new ServiceSpecificException(
4957 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004958 }
4959 mUidToNetworkRequestCount.put(mUid, networkRequests);
4960 }
4961 }
4962
Robert Greenwalt9258c642014-03-26 16:47:06 -07004963 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004964 if (mBinder != null) {
4965 mBinder.unlinkToDeath(this, 0);
4966 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004967 }
4968
4969 public void binderDied() {
4970 log("ConnectivityService NetworkRequestInfo binderDied(" +
4971 request + ", " + mBinder + ")");
4972 releaseNetworkRequest(request);
4973 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004974
4975 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004976 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004977 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004978 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004979 }
4980
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004981 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4982 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4983 if (badCapability != null) {
4984 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004985 }
4986 }
4987
paulhu3d67f532019-03-22 16:35:06 +08004988 // This checks that the passed capabilities either do not request a specific SSID/SignalStrength
4989 // , or the calling app has permission to do so.
Chalard Jeanb03a6222018-04-11 21:09:10 +09004990 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4991 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004992 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004993 throw new SecurityException("Insufficient permissions to request a specific SSID");
4994 }
paulhu3d67f532019-03-22 16:35:06 +08004995
4996 if (nc.hasSignalStrength()
4997 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
4998 throw new SecurityException(
4999 "Insufficient permissions to request a specific signal strength");
5000 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09005001 }
5002
Erik Kline9d598e12015-07-13 16:37:51 +09005003 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09005004 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005005 synchronized (nai) {
5006 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5007 if (nri.request.networkCapabilities.hasSignalStrength() &&
5008 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
5009 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
5010 }
5011 }
5012 }
Chalard Jean4133a122018-06-04 13:33:12 +09005013 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005014 }
5015
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005016 private void updateSignalStrengthThresholds(
5017 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5018 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09005019 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005020 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
5021
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005022 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005023 String detail;
5024 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5025 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5026 } else {
5027 detail = reason;
5028 }
5029 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5030 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
5031 }
5032
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005033 nai.asyncChannel.sendMessage(
5034 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005035 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005036 }
5037
Etan Cohen859748f2017-04-03 17:42:34 -07005038 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5039 if (nc == null) {
5040 return;
5041 }
5042 NetworkSpecifier ns = nc.getNetworkSpecifier();
5043 if (ns == null) {
5044 return;
5045 }
5046 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5047 ns.assertValidFromUid(Binder.getCallingUid());
5048 }
5049
Robert Greenwalt9258c642014-03-26 16:47:06 -07005050 @Override
5051 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005052 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005053 final NetworkRequest.Type type = (networkCapabilities == null)
5054 ? NetworkRequest.Type.TRACK_DEFAULT
5055 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005056 // If the requested networkCapabilities is null, take them instead from
5057 // the default network request. This allows callers to keep track of
5058 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005059 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005060 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005061 enforceAccessPermission();
5062 } else {
5063 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5064 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005065 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5066 // of the app when the request is filed, but we never change the request if the app
5067 // changes network state. http://b/29964605
5068 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005069 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005070 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005071 ensureSufficientPermissionsForRequest(networkCapabilities,
5072 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005073 // Set the UID range for this request to the single UID of the requester, or to an empty
5074 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005075 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5076 // are no visible methods to set the UIDs, an app could use reflection to try and get
5077 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005078 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005079
Etan Cohenba07c8c2017-02-05 10:42:27 -08005080 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005081 throw new IllegalArgumentException("Bad timeout specified");
5082 }
Etan Cohen859748f2017-04-03 17:42:34 -07005083 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005084
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005085 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005086 nextNetworkRequestId(), type);
5087 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005088 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005089
5090 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005091 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005092 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005093 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005094 }
5095 return networkRequest;
5096 }
5097
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005098 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005099 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005100 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005101 } else {
5102 enforceChangePermission();
5103 }
5104 }
5105
fenglub15e72b2015-03-20 11:29:56 -07005106 @Override
fengludb571472015-04-21 17:12:05 -07005107 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005108 enforceAccessPermission();
5109 NetworkAgentInfo nai = null;
5110 if (network == null) {
5111 return false;
5112 }
5113 synchronized (mNetworkForNetId) {
5114 nai = mNetworkForNetId.get(network.netId);
5115 }
5116 if (nai != null) {
5117 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005118 synchronized (mBandwidthRequests) {
5119 final int uid = Binder.getCallingUid();
5120 Integer uidReqs = mBandwidthRequests.get(uid);
5121 if (uidReqs == null) {
5122 uidReqs = new Integer(0);
5123 }
5124 mBandwidthRequests.put(uid, ++uidReqs);
5125 }
fenglub15e72b2015-03-20 11:29:56 -07005126 return true;
5127 }
5128 return false;
5129 }
5130
Felipe Lemeee27cab2016-06-20 16:36:29 -07005131 private boolean isSystem(int uid) {
5132 return uid < Process.FIRST_APPLICATION_UID;
5133 }
fenglub15e72b2015-03-20 11:29:56 -07005134
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005135 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005136 final int uid = Binder.getCallingUid();
5137 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005138 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005139 return;
5140 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005141 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5142 // Policy already enforced.
5143 return;
5144 }
5145 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5146 // If UID is restricted, don't allow them to bring up metered APNs.
5147 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005148 }
5149 }
5150
Robert Greenwalt9258c642014-03-26 16:47:06 -07005151 @Override
5152 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5153 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005154 checkNotNull(operation, "PendingIntent cannot be null.");
5155 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5156 enforceNetworkRequestPermissions(networkCapabilities);
5157 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005158 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005159 ensureSufficientPermissionsForRequest(networkCapabilities,
5160 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005161 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005162 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005163
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005164 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005165 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5166 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005167 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005168 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5169 nri));
5170 return networkRequest;
5171 }
5172
Jeremy Joslin79294842014-12-03 17:15:28 -08005173 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5174 mHandler.sendMessageDelayed(
5175 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5176 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5177 }
5178
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005179 @Override
5180 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005181 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005182 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5183 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005184 }
5185
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005186 // In order to implement the compatibility measure for pre-M apps that call
5187 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5188 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5189 // This ensures it has permission to do so.
5190 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5191 if (nc == null) {
5192 return false;
5193 }
5194 int[] transportTypes = nc.getTransportTypes();
5195 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5196 return false;
5197 }
5198 try {
5199 mContext.enforceCallingOrSelfPermission(
5200 android.Manifest.permission.ACCESS_WIFI_STATE,
5201 "ConnectivityService");
5202 } catch (SecurityException e) {
5203 return false;
5204 }
5205 return true;
5206 }
5207
Robert Greenwalt9258c642014-03-26 16:47:06 -07005208 @Override
5209 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5210 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005211 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5212 enforceAccessPermission();
5213 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005214
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005215 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005216 ensureSufficientPermissionsForRequest(networkCapabilities,
5217 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005218 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005219 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5220 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5221 // onLost and onAvailable callbacks when networks move in and out of the background.
5222 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5223 // can't request networks.
5224 restrictBackgroundRequestForCaller(nc);
5225 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005226
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005227 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005228 NetworkRequest.Type.LISTEN);
5229 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005230 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005231
5232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5233 return networkRequest;
5234 }
5235
5236 @Override
5237 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5238 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005239 checkNotNull(operation, "PendingIntent cannot be null.");
5240 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5241 enforceAccessPermission();
5242 }
Etan Cohen859748f2017-04-03 17:42:34 -07005243 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005244 ensureSufficientPermissionsForRequest(networkCapabilities,
5245 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005246
Chalard Jeandda156a2018-01-10 21:19:32 +09005247 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005248 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005249
5250 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005251 NetworkRequest.Type.LISTEN);
5252 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005253 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005254
5255 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005256 }
5257
Erik Klineacdd6392016-07-07 16:50:58 +09005258 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005259 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005260 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005261 mHandler.sendMessage(mHandler.obtainMessage(
5262 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005263 }
5264
5265 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09005266 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005267 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09005268 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5269 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005270 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09005271 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005272 }
5273
Robert Greenwalta67be032014-05-16 15:49:14 -07005274 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005275 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005276 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5277 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5278 }
5279
5280 @Override
5281 public void unregisterNetworkFactory(Messenger messenger) {
5282 enforceConnectivityInternalPermission();
5283 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5284 }
5285
5286 private void handleUnregisterNetworkFactory(Messenger messenger) {
5287 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5288 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005289 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005290 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005291 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005292 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005293 }
5294
Robert Greenwalt7b816022014-04-18 15:25:25 -07005295 /**
5296 * NetworkAgentInfo supporting a request by requestId.
5297 * These have already been vetted (their Capabilities satisfy the request)
5298 * and the are the highest scored network available.
5299 * the are keyed off the Requests requestId.
5300 */
Hugo Benichicd952782017-09-20 11:20:14 +09005301 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5302 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005303 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005304
Paul Jensen31a94f42015-02-13 14:18:39 -05005305 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5306 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005307 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005308 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5309 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5310 // there may not be a strict 1:1 correlation between the two.
5311 @GuardedBy("mNetworkForNetId")
5312 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005313
Robert Greenwalt7b816022014-04-18 15:25:25 -07005314 // NetworkAgentInfo keyed off its connecting messenger
5315 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005316 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005317 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005318
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005319 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005320 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005321
Paul Jensen2c311d62014-11-17 12:34:51 -05005322 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005323 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005324
Erik Klineda4bfa82015-04-30 12:58:40 +09005325 // Request used to optionally keep mobile data active even when higher
5326 // priority networks like Wi-Fi are active.
5327 private final NetworkRequest mDefaultMobileDataRequest;
5328
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005329 // Request used to optionally keep wifi data active even when higher
5330 // priority networks like ethernet are active.
5331 private final NetworkRequest mDefaultWifiRequest;
5332
Hugo Benichicd952782017-09-20 11:20:14 +09005333 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5334 synchronized (mNetworkForRequestId) {
5335 return mNetworkForRequestId.get(requestId);
5336 }
5337 }
5338
5339 private void clearNetworkForRequest(int requestId) {
5340 synchronized (mNetworkForRequestId) {
5341 mNetworkForRequestId.remove(requestId);
5342 }
5343 }
5344
5345 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5346 synchronized (mNetworkForRequestId) {
5347 mNetworkForRequestId.put(requestId, nai);
5348 }
5349 }
5350
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005351 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005352 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005353 }
5354
Varun Anand4fa80e82019-02-06 10:13:38 -08005355 @Nullable
5356 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5357 return nai != null ? nai.network : null;
5358 }
5359
5360 private void ensureRunningOnConnectivityServiceThread() {
5361 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5362 throw new IllegalStateException(
5363 "Not running on ConnectivityService thread: "
5364 + Thread.currentThread().getName());
5365 }
5366 }
5367
Chalard Jeanff46a252019-04-10 23:07:55 +09005368 @VisibleForTesting
5369 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005370 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005371 }
5372
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005373 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5374 return nri.request.requestId == mDefaultRequest.requestId;
5375 }
5376
Chalard Jean08577fc2018-05-02 21:14:54 +09005377 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5378 // changes that would conflict throughout the automerger graph. Having this method temporarily
5379 // helps with the process of going through with all these dependent changes across the entire
5380 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005381 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005382 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005383 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005384 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5385 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5386 }
5387
5388 /**
5389 * Register a new agent with ConnectivityService to handle a network.
5390 *
5391 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5392 * @param networkInfo the initial info associated with this network. It can be updated later :
5393 * see {@link #updateNetworkInfo}.
5394 * @param linkProperties the initial link properties of this network. They can be updated
5395 * later : see {@link #updateLinkProperties}.
5396 * @param networkCapabilities the initial capabilites of this network. They can be updated
5397 * later : see {@link #updateNetworkCapabilities}.
5398 * @param currentScore the initial score of the network. See
5399 * {@link NetworkAgentInfo#getCurrentScore}.
5400 * @param networkMisc metadata about the network. This is never updated.
5401 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5402 */
5403 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5404 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5405 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005406 enforceConnectivityInternalPermission();
5407
Rubin Xu1bb5c082017-09-05 18:40:49 +01005408 LinkProperties lp = new LinkProperties(linkProperties);
5409 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005410 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5411 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005412 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005413 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005414 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Luke Huang65914772019-03-16 00:31:46 +08005415 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mDnsResolver,
5416 mNMS, factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005417 // Make sure the network capabilities reflect what the agent info says.
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005418 nai.setNetworkCapabilities(mixInCapabilities(nai, nc));
Chalard Jeand771aa02018-04-26 16:16:10 +09005419 final String extraInfo = networkInfo.getExtraInfo();
5420 final String name = TextUtils.isEmpty(extraInfo)
5421 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005422 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005423 final long token = Binder.clearCallingIdentity();
5424 try {
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005425 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005426 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005427 } finally {
5428 Binder.restoreCallingIdentity(token);
5429 }
5430 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5431 // If the network disconnects or sends any other event before that, messages are deferred by
5432 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5433 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005434 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005435 }
5436
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005437 @VisibleForTesting
5438 protected NetworkStackClient getNetworkStack() {
5439 return NetworkStackClient.getInstance();
5440 }
5441
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005442 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5443 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005444 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005445 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005446 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005447 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005448 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005449
5450 try {
5451 networkMonitor.start();
5452 } catch (RemoteException e) {
5453 e.rethrowFromSystemServer();
5454 }
Erik Klinee5dac902018-03-04 21:01:01 +09005455 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5456 NetworkInfo networkInfo = nai.networkInfo;
5457 nai.networkInfo = null;
5458 updateNetworkInfo(nai, networkInfo);
5459 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005460 }
5461
lucaslin25a4ec32018-11-28 12:51:55 +08005462 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5463 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005464 int netId = networkAgent.network.netId;
5465
Lorenzo Colittidf595632019-01-08 14:43:37 +09005466 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5467 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5468 // are accurate.
5469 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005470
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005471 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005472 updateMtu(newLp, oldLp);
5473 // TODO - figure out what to do for clat
5474// for (LinkProperties lp : newLp.getStackedLinks()) {
5475// updateMtu(lp, null);
5476// }
lucaslin041a1af2018-11-28 19:27:52 +08005477 if (isDefaultNetwork(networkAgent)) {
5478 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5479 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005480
Erik Kline94887872016-04-05 13:30:49 +09005481 updateRoutes(newLp, oldLp, netId);
5482 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005483 // Make sure LinkProperties represents the latest private DNS status.
5484 // This does not need to be done before updateDnses because the
5485 // LinkProperties are not the source of the private DNS configuration.
5486 // updateDnses will fetch the private DNS configuration from DnsManager.
5487 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005488
Paul Jensene0bef712014-12-10 15:12:18 -05005489 if (isDefaultNetwork(networkAgent)) {
5490 handleApplyDefaultProxy(newLp.getHttpProxy());
5491 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005492 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005493 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005494 // TODO - move this check to cover the whole function
5495 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005496 synchronized (networkAgent) {
5497 networkAgent.linkProperties = newLp;
5498 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005499 // Start or stop DNS64 detection and 464xlat according to network state.
5500 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005501 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005502 try {
5503 networkAgent.networkMonitor().notifyLinkPropertiesChanged(newLp);
5504 } catch (RemoteException e) {
5505 e.rethrowFromSystemServer();
5506 }
lucaslin25a4ec32018-11-28 12:51:55 +08005507 if (networkAgent.everConnected) {
5508 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5509 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005510 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005511
5512 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005513 }
5514
Joel Scherpelz668370b2017-06-08 15:35:21 +09005515 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005516 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005517 // marks on unsupported interfaces is harmless.
5518 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5519 return;
5520 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005521
Joel Scherpelz668370b2017-06-08 15:35:21 +09005522 int mark = mContext.getResources().getInteger(
5523 com.android.internal.R.integer.config_networkWakeupPacketMark);
5524 int mask = mContext.getResources().getInteger(
5525 com.android.internal.R.integer.config_networkWakeupPacketMask);
5526
5527 // Mask/mark of zero will not detect anything interesting.
5528 // Don't install rules unless both values are nonzero.
5529 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005530 return;
5531 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005532
5533 final String prefix = "iface:" + iface;
5534 try {
5535 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005536 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005537 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005538 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005539 }
5540 } catch (Exception e) {
5541 loge("Exception modifying wakeup packet monitoring: " + e);
5542 }
5543
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005544 }
5545
5546 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5547 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005548 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005549 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5550 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005551 for (String iface : interfaceDiff.added) {
5552 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005553 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005554 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005555 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005556 } catch (Exception e) {
5557 loge("Exception adding interface: " + e);
5558 }
5559 }
5560 for (String iface : interfaceDiff.removed) {
5561 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005562 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005563 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005564 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005565 } catch (Exception e) {
5566 loge("Exception removing interface: " + e);
5567 }
5568 }
5569 }
5570
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005571 /**
5572 * Have netd update routes from oldLp to newLp.
5573 * @return true if routes changed between oldLp and newLp
5574 */
5575 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005576 // Compare the route diff to determine which routes should be added and removed.
5577 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5578 oldLp != null ? oldLp.getAllRoutes() : null,
5579 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005580
5581 // add routes before removing old in case it helps with continuous connectivity
5582
Chalard Jean4d660112018-06-04 16:52:49 +09005583 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005584 for (RouteInfo route : routeDiff.added) {
5585 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005586 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005587 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005588 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005589 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005590 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5591 loge("Exception in addRoute for non-gateway: " + e);
5592 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005593 }
5594 }
5595 for (RouteInfo route : routeDiff.added) {
5596 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005597 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005598 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005599 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005600 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005601 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5602 loge("Exception in addRoute for gateway: " + e);
5603 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005604 }
5605 }
5606
5607 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005608 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005609 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005610 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005611 } catch (Exception e) {
5612 loge("Exception in removeRoute: " + e);
5613 }
5614 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005615 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005616 }
Erik Kline41368502015-06-17 13:19:54 +09005617
Erik Kline94887872016-04-05 13:30:49 +09005618 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5619 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5620 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005621 }
Erik Kline94887872016-04-05 13:30:49 +09005622
Erik Kline1742fe12017-12-13 19:40:49 +09005623 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5624 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5625
Erik Klinea24d4592018-01-11 21:07:29 +09005626 if (DBG) {
5627 final Collection<InetAddress> dnses = newLp.getDnsServers();
5628 log("Setting DNS servers for network " + netId + " to " + dnses);
5629 }
Erik Kline94887872016-04-05 13:30:49 +09005630 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005631 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005632 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005633 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005634 }
Erik Kline4edba012017-04-07 15:29:29 +09005635 }
5636
Luke Huang8a462ec2018-08-24 20:33:16 +08005637 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005638 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005639 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005640 }
5641 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005642 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005643 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005644 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005645 }
5646
Paul Jensen3d194ea2015-06-16 14:27:36 -04005647 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005648 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5649 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5650 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005651 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005652 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005653 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005654 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5655 // causing a connect/teardown loop.
5656 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5657 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005658 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005659 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005660 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5661 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005662 // does not cause any request (that is not a listen) currently matching that agent to
5663 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005664 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005665 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005666 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005667 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005668 }
5669
Paul Jensen3d194ea2015-06-16 14:27:36 -04005670 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005671 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005672 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005673 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005674 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005675 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005676 }
Paul Jensene0988542015-06-25 15:30:08 -04005677 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005678 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005679 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005680 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005681 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005682 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005683 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005684 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005685 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005686 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005687 if (nai.isSuspended()) {
5688 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5689 } else {
5690 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5691 }
lucasline252a742019-03-12 13:08:03 +08005692 if (nai.partialConnectivity) {
5693 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5694 } else {
5695 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5696 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005697
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005698 return newNc;
5699 }
5700
5701 /**
5702 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5703 *
5704 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5705 * capabilities we manage and store in {@code nai}, such as validated status and captive
5706 * portal status)
5707 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5708 * potentially triggers rematches.
5709 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5710 * change.)
5711 *
5712 * @param oldScore score of the network before any of the changes that prompted us
5713 * to call this function.
5714 * @param nai the network having its capabilities updated.
5715 * @param nc the new network capabilities.
5716 */
5717 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5718 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5719
5720 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005721
Luke Huang8a462ec2018-08-24 20:33:16 +08005722 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5723 final int newPermission = getNetworkPermission(newNc);
5724 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005725 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005726 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005727 } catch (RemoteException e) {
5728 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005729 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005730 }
5731
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005732 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005733 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005734 prevNc = nai.networkCapabilities;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005735 nai.setNetworkCapabilities(newNc);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005736 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005737
Chalard Jeanf213ca12018-01-16 18:43:05 +09005738 updateUids(nai, prevNc, newNc);
5739
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005740 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005741 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5742 // the change we're processing can't affect any requests, it can only affect the listens
5743 // on this network. We might have been called by rematchNetworkAndRequests when a
5744 // network changed foreground state.
5745 processListenRequests(nai, true);
5746 } else {
5747 // If the requestable capabilities have changed or the score changed, we can't have been
5748 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005749 rematchAllNetworksAndRequests(nai, oldScore);
5750 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005751 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005752
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005753 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005754 final boolean oldMetered = prevNc.isMetered();
5755 final boolean newMetered = newNc.isMetered();
5756 final boolean meteredChanged = oldMetered != newMetered;
5757
5758 if (meteredChanged) {
5759 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5760 mRestrictBackground);
5761 }
5762
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005763 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005764 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005765
5766 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005767 if (meteredChanged || roamingChanged) {
5768 notifyIfacesChangedForNetworkStats();
5769 }
5770 }
5771
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005772 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005773 // Tell VPNs about updated capabilities, since they may need to
5774 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005775 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005776 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005777 }
5778
Chalard Jeanf213ca12018-01-16 18:43:05 +09005779 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5780 NetworkCapabilities newNc) {
5781 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5782 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5783 if (null == prevRanges) prevRanges = new ArraySet<>();
5784 if (null == newRanges) newRanges = new ArraySet<>();
5785 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5786
5787 prevRanges.removeAll(newRanges);
5788 newRanges.removeAll(prevRangesCopy);
5789
5790 try {
5791 if (!newRanges.isEmpty()) {
5792 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5793 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005794 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005795 }
5796 if (!prevRanges.isEmpty()) {
5797 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5798 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005799 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005800 }
5801 } catch (Exception e) {
5802 // Never crash!
5803 loge("Exception in updateUids: " + e);
5804 }
5805 }
5806
Hugo Benichief502882017-09-01 01:23:32 +00005807 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005808 ensureRunningOnConnectivityServiceThread();
5809
Erik Kline736353a2018-03-21 07:18:33 -07005810 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005811 // Ignore updates for disconnected networks
5812 return;
5813 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005814 // newLp is already a defensive copy.
5815 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005816 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005817 log("Update of LinkProperties for " + nai.name() +
5818 "; created=" + nai.created +
5819 "; everConnected=" + nai.everConnected);
5820 }
lucaslin25a4ec32018-11-28 12:51:55 +08005821 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005822 }
5823
Paul Jensenc8b9a742014-09-30 15:37:41 -04005824 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005825 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5826 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005827 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005828 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005829 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005830 }
5831 }
5832
Chalard Jean08577fc2018-05-02 21:14:54 +09005833 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5834 int score = 0;
5835 int serial = 0;
5836 if (nai != null) {
5837 score = nai.getCurrentScore();
5838 serial = nai.factorySerialNumber;
5839 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005840 if (VDBG || DDBG){
5841 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5842 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005843 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005844 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5845 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005846 }
5847 }
5848
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005849 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5850 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005851 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005852 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005853 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5854 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005855 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005856 sendIntent(nri.mPendingIntent, intent);
5857 }
5858 // else not handled
5859 }
5860
5861 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5862 mPendingIntentWakeLock.acquire();
5863 try {
5864 if (DBG) log("Sending " + pendingIntent);
5865 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5866 } catch (PendingIntent.CanceledException e) {
5867 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5868 mPendingIntentWakeLock.release();
5869 releasePendingNetworkRequest(pendingIntent);
5870 }
5871 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5872 }
5873
5874 @Override
5875 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5876 String resultData, Bundle resultExtras) {
5877 if (DBG) log("Finished sending " + pendingIntent);
5878 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005879 // Release with a delay so the receiving client has an opportunity to put in its
5880 // own request.
5881 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005882 }
5883
Chalard Jeanf19db372018-01-26 19:24:40 +09005884 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005885 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005886 if (nri.messenger == null) {
5887 return; // Default request has no msgr
5888 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005889 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005890 // TODO: check if defensive copies of data is needed.
5891 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005892 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005893 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5894 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005895 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005896 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005897 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005898 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5899 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005900 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005901 // For this notification, arg1 contains the blocked status.
5902 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005903 break;
5904 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005905 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005906 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005907 break;
5908 }
5909 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005910 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005911 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005912 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005913 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005914 break;
5915 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005916 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005917 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005918 break;
5919 }
junyulai05986c62018-08-07 19:50:45 +08005920 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005921 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005922 msg.arg1 = arg1;
5923 break;
5924 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005925 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005926 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005927 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005928 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005929 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005930 String notification = ConnectivityManager.getCallbackName(notificationType);
5931 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005932 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005933 nri.messenger.send(msg);
5934 } catch (RemoteException e) {
5935 // may occur naturally in the race of binder death.
5936 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5937 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005938 }
5939
Hugo Benichidba33db2017-03-23 22:40:44 +09005940 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5941 bundle.putParcelable(t.getClass().getSimpleName(), t);
5942 }
5943
Paul Jensenc8b9a742014-09-30 15:37:41 -04005944 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005945 if (nai.numRequestNetworkRequests() != 0) {
5946 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5947 NetworkRequest nr = nai.requestAt(i);
5948 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005949 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005950 loge("Dead network still had at least " + nr);
5951 break;
5952 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005953 }
5954 nai.asyncChannel.disconnect();
5955 }
5956
Robert Greenwalt7b816022014-04-18 15:25:25 -07005957 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5958 if (oldNetwork == null) {
5959 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5960 return;
5961 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005962 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005963
5964 // If we get here it means that the last linger timeout for this network expired. So there
5965 // must be no other active linger timers, and we must stop lingering.
5966 oldNetwork.clearLingerState();
5967
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005968 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005969 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005970 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005971 } else {
5972 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005973 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5974 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005975 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005976 }
5977
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005978 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005979 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005980
Paul Jensen27b02b72014-07-14 12:03:33 -04005981 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005982 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005983 } catch (Exception e) {
5984 loge("Exception setting default network :" + e);
5985 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005986
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005987 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005988 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005989 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005990 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005991 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005992 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5993 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005994 }
5995
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005996 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005997 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5998 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5999 NetworkRequest nr = nri.request;
6000 if (!nr.isListen()) continue;
6001 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
6002 nai.removeRequest(nri.request.requestId);
6003 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
6004 }
6005 }
6006
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006007 if (capabilitiesChanged) {
6008 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
6009 }
6010
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006011 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6012 NetworkRequest nr = nri.request;
6013 if (!nr.isListen()) continue;
6014 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6015 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006016 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006017 }
6018 }
6019 }
6020
Paul Jensen2161a8e2014-09-11 11:00:39 -04006021 // Handles a network appearing or improving its score.
6022 //
6023 // - Evaluates all current NetworkRequests that can be
6024 // satisfied by newNetwork, and reassigns to newNetwork
6025 // any such requests for which newNetwork is the best.
6026 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006027 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006028 // needed. A network is needed if it is the best network for
6029 // one or more NetworkRequests, or if it is a VPN.
6030 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006031 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006032 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006033 //
6034 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6035 // networks that have no chance (i.e. even if validated)
6036 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006037 //
6038 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6039 // it does not remove NetworkRequests that other Networks could better satisfy.
6040 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6041 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6042 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006043 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006044 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006045 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6046 // performed to tear down unvalidated networks that have no chance (i.e. even if
6047 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006048 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006049 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006050 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006051 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006052 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006053 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006054
6055 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6056 final int score = newNetwork.getCurrentScore();
6057
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006058 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006059
Paul Jensen2161a8e2014-09-11 11:00:39 -04006060 // Find and migrate to this Network any NetworkRequests for
6061 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006062 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6063 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006064 NetworkCapabilities nc = newNetwork.networkCapabilities;
6065 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006066 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006067 // Process requests in the first pass and listens in the second pass. This allows us to
6068 // change a network's capabilities depending on which requests it has. This is only
6069 // correct if the change in capabilities doesn't affect whether the network satisfies
6070 // requests or not, and doesn't affect the network's score.
6071 if (nri.request.isListen()) continue;
6072
Hugo Benichicd952782017-09-20 11:20:14 +09006073 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006074 final boolean satisfies = newNetwork.satisfies(nri.request);
6075 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006076 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006077 log("Network " + newNetwork.name() + " was already satisfying" +
6078 " request " + nri.request.requestId + ". No change.");
6079 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006080 keep = true;
6081 continue;
6082 }
6083
6084 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006085 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006086 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006087 // next check if it's better than any current network we're using for
6088 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006089 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006090 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006091 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006092 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006093 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006094 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006095 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006096 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006097 if (VDBG || DDBG){
6098 log(" accepting network in place of " + currentNetwork.name());
6099 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006100 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006101 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006102 affectedNetworks.add(currentNetwork);
6103 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006104 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006105 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006106 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006107 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006108 if (!newNetwork.addRequest(nri.request)) {
6109 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6110 }
6111 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006112 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006113 // Tell NetworkFactories about the new score, so they can stop
6114 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006115 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006116 // network. Think about if there is a way to reduce this. Push
6117 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09006118 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006119 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006120 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006121 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006122 if (currentNetwork != null) {
6123 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006125 }
6126 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006127 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006128 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6129 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006130 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006131 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6132 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6133 // This means this code doesn't have to handle the case where "currentNetwork" no
6134 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6135 if (DBG) {
6136 log("Network " + newNetwork.name() + " stopped satisfying" +
6137 " request " + nri.request.requestId);
6138 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006139 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006140 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006141 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09006142 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006143 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006144 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6145 newNetwork.name() +
6146 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006147 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006148 // TODO: Technically, sending CALLBACK_LOST here is
6149 // incorrect if there is a replacement network currently
6150 // connected that can satisfy nri, which is a request
6151 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006152 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6153 // so this code is only incorrect for a network that loses
6154 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006155 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006156 }
6157 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006158 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006159 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006160 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006161 makeDefault(newNetwork);
6162 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006163 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006164 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006165 // Have a new default network, release the transition wakelock in
6166 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006167 }
6168
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006169 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6170 Slog.wtf(TAG, String.format(
6171 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006172 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006173 }
6174 if (newNetwork.getCurrentScore() != score) {
6175 Slog.wtf(TAG, String.format(
6176 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006177 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006178 }
6179
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006180 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006181 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6182 // If the network went from background to foreground or vice versa, we need to update
6183 // its foreground state. It is safe to do this after rematching the requests because
6184 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6185 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006186 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006187 } else {
6188 processListenRequests(newNetwork, false);
6189 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006190
Paul Jensencf4c2c62015-07-01 14:16:32 -04006191 // do this after the default net is switched, but
6192 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006193 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006194
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006195 // Linger any networks that are no longer needed. This should be done after sending the
6196 // available callback for newNetwork.
6197 for (NetworkAgentInfo nai : affectedNetworks) {
6198 updateLingerState(nai, now);
6199 }
6200 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6201 // does not need to be done in any particular order.
6202 updateLingerState(newNetwork, now);
6203
Paul Jensencf4c2c62015-07-01 14:16:32 -04006204 if (isNewDefault) {
6205 // Maintain the illusion: since the legacy API only
6206 // understands one network at a time, we must pretend
6207 // that the current default network disconnected before
6208 // the new one connected.
6209 if (oldDefaultNetwork != null) {
6210 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6211 oldDefaultNetwork, true);
6212 }
6213 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6214 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6215 notifyLockdownVpn(newNetwork);
6216 }
6217
Robert Greenwalt7b816022014-04-18 15:25:25 -07006218 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006219 // Notify battery stats service about this network, both the normal
6220 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006221 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006222 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006223 final IBatteryStats bs = BatteryStatsService.getService();
6224 final int type = newNetwork.networkInfo.getType();
6225
6226 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6227 bs.noteNetworkInterfaceType(baseIface, type);
6228 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6229 final String stackedIface = stacked.getInterfaceName();
6230 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006231 }
6232 } catch (RemoteException ignored) {
6233 }
6234
Robert Greenwalt152ed372014-12-17 17:19:53 -08006235 // This has to happen after the notifyNetworkCallbacks as that tickles each
6236 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006237 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006238 // and will generally do a dns request so they can ensureRouteToHost and if
6239 // they do that before the callbacks happen they'll use the default network.
6240 //
6241 // TODO: Is there still a race here? We send the broadcast
6242 // after sending the callback, but if the app can receive the
6243 // broadcast before the callback, it might still break.
6244 //
6245 // This *does* introduce a race where if the user uses the new api
6246 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6247 // they may get old info. Reverse this after the old startUsing api is removed.
6248 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006249 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6250 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006251 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006252 // legacy type tracker filters out repeat adds
6253 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6254 }
6255 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006256
6257 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6258 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6259 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6260 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6261 if (newNetwork.isVPN()) {
6262 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6263 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006264 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006265 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6266 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006267 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006268 if (nai.getLingerExpiry() > 0) {
6269 // This network has active linger timers and no requests, but is not
6270 // lingering. Linger it.
6271 //
6272 // One way (the only way?) this can happen if this network is unvalidated
6273 // and became unneeded due to another network improving its score to the
6274 // point where this network will no longer be able to satisfy any requests
6275 // even if it validates.
6276 updateLingerState(nai, now);
6277 } else {
6278 if (DBG) log("Reaping " + nai.name());
6279 teardownUnneededNetwork(nai);
6280 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006281 }
6282 }
6283 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006284 }
6285
Paul Jensen1c7ba022015-06-16 14:27:36 -04006286 /**
6287 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6288 * being disconnected.
6289 * @param changed If only one Network's score or capabilities have been modified since the last
6290 * time this function was called, pass this Network in this argument, otherwise pass
6291 * null.
6292 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6293 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6294 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6295 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6296 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006297 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006298 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006299 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6300 // to avoid the slowness. It is not simply enough to process just "changed", for
6301 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006302 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006303
6304 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6305 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6306 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006307 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006308 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006309 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006310 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006311 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6312 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6313 // Rematch higher scoring networks first to prevent requests first matching a lower
6314 // scoring network and then a higher scoring network, which could produce multiple
6315 // callbacks and inadvertently unlinger networks.
6316 Arrays.sort(nais);
6317 for (NetworkAgentInfo nai : nais) {
6318 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006319 // Only reap the last time through the loop. Reaping before all rematching
6320 // is complete could incorrectly teardown a network that hasn't yet been
6321 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006322 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006323 : ReapUnvalidatedNetworks.REAP,
6324 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006325 }
6326 }
6327 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006328
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006329 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006330 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006331 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006332 // For now only update icons for default connection.
6333 // TODO: Update WiFi and cellular icons separately. b/17237507
6334 if (!isDefaultNetwork(nai)) return;
6335
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006336 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006337 // Don't repeat publish.
6338 if (newInetCondition == mDefaultInetConditionPublished) return;
6339
6340 mDefaultInetConditionPublished = newInetCondition;
6341 sendInetConditionBroadcast(nai.networkInfo);
6342 }
6343
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006344 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006345 synchronized (mVpns) {
6346 if (mLockdownTracker != null) {
6347 if (nai != null && nai.isVPN()) {
6348 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6349 } else {
6350 mLockdownTracker.onNetworkInfoChanged();
6351 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006352 }
6353 }
6354 }
6355
Robert Greenwalt7b816022014-04-18 15:25:25 -07006356 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006357 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006358 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006359 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006360 synchronized (networkAgent) {
6361 oldInfo = networkAgent.networkInfo;
6362 networkAgent.networkInfo = newInfo;
6363 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006364 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006365
Robert Greenwalt7b816022014-04-18 15:25:25 -07006366 if (DBG) {
6367 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6368 (oldInfo == null ? "null" : oldInfo.getState()) +
6369 " to " + state);
6370 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006371
Robin Lee585e2482016-05-01 23:00:00 +01006372 if (!networkAgent.created
6373 && (state == NetworkInfo.State.CONNECTED
6374 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006375
6376 // A network that has just connected has zero requests and is thus a foreground network.
6377 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6378
Robert Greenwalt7b816022014-04-18 15:25:25 -07006379 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006380 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006381 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006382 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006383 (networkAgent.networkMisc == null ||
6384 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006385 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006386 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006387 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006388 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006389 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006390 loge("Error creating network " + networkAgent.network.netId + ": "
6391 + e.getMessage());
6392 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006393 }
Paul Jenseneec75412014-08-04 12:21:19 -04006394 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006395 }
6396
6397 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6398 networkAgent.everConnected = true;
6399
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006400 if (networkAgent.linkProperties == null) {
6401 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6402 }
6403
lucaslin8175ac992019-04-03 17:09:28 +08006404 // NetworkCapabilities need to be set before sending the private DNS config to
6405 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
6406 synchronized (networkAgent) {
6407 networkAgent.setNetworkCapabilities(networkAgent.networkCapabilities);
6408 }
Erik Kline736353a2018-03-21 07:18:33 -07006409 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006410 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6411 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006412
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006413 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6414 // command must be sent after updating LinkProperties to maximize chances of
6415 // NetworkMonitor seeing the correct LinkProperties when starting.
6416 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6417 try {
lucaslin43338992019-03-20 18:21:59 +08006418 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6419 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6420 }
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09006421 networkAgent.networkMonitor().notifyNetworkConnected(
6422 networkAgent.linkProperties, networkAgent.networkCapabilities);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006423 } catch (RemoteException e) {
6424 e.rethrowFromSystemServer();
6425 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006426 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006427
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006428 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6429 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6430 // capabilities, so it only needs to be done once on initial connect, not every time the
6431 // network's capabilities change. Note that we do this before rematching the network,
6432 // so we could decide to tear it down immediately afterwards. That's fine though - on
6433 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6434 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006435 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006436
Varun Anand4fa80e82019-02-06 10:13:38 -08006437 if (networkAgent.isVPN()) {
6438 updateAllVpnsCapabilities();
6439 }
6440
Paul Jensen2161a8e2014-09-11 11:00:39 -04006441 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006442 final long now = SystemClock.elapsedRealtime();
6443 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006444
6445 // This has to happen after matching the requests, because callbacks are just requests.
6446 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006447 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006448 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006449 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006450 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006451 }
Chalard Jean392971c2018-05-11 20:19:20 +09006452 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006453 if (networkAgent.isVPN()) {
6454 // As the active or bound network changes for apps, broadcast the default proxy, as
6455 // apps may need to update their proxy data. This is called after disconnecting from
6456 // VPN to make sure we do not broadcast the old proxy data.
6457 // TODO(b/122649188): send the broadcast only to VPN users.
6458 mProxyTracker.sendProxyBroadcast();
6459 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006460 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6461 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006462 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006463 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006464 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006465 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006466 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6467 networkAgent.networkCapabilities);
6468 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6469 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006470 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6471 ConnectivityManager.CALLBACK_SUSPENDED :
6472 ConnectivityManager.CALLBACK_RESUMED));
6473 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006474 }
6475 }
6476
Robert Greenwaltac96c522014-06-03 16:43:57 -07006477 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006478 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006479 if (score < 0) {
6480 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6481 "). Bumping score to min of 0");
6482 score = 0;
6483 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006484
Paul Jensen2161a8e2014-09-11 11:00:39 -04006485 final int oldScore = nai.getCurrentScore();
6486 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006487
Paul Jensen85cf78e2015-06-25 13:25:07 -04006488 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006489
Paul Jensenc8b9a742014-09-30 15:37:41 -04006490 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006491 }
6492
Erik Klinec75d4fa2017-02-15 19:59:17 +09006493 // Notify only this one new request of the current state. Transfer all the
6494 // current state by calling NetworkCapabilities and LinkProperties callbacks
6495 // so that callers can be guaranteed to have as close to atomicity in state
6496 // transfer as can be supported by this current API.
6497 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006498 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006499 if (nri.mPendingIntent != null) {
6500 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6501 // Attempt no subsequent state pushes where intents are involved.
6502 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006503 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006504
junyulai05986c62018-08-07 19:50:45 +08006505 final boolean metered = nai.networkCapabilities.isMetered();
6506 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6507 metered, mRestrictBackground);
6508 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6509 }
6510
6511 /**
6512 * Notify of the blocked state apps with a registered callback matching a given NAI.
6513 *
6514 * Unlike other callbacks, blocked status is different between each individual uid. So for
6515 * any given nai, all requests need to be considered according to the uid who filed it.
6516 *
6517 * @param nai The target NetworkAgentInfo.
6518 * @param oldMetered True if the previous network capabilities is metered.
6519 * @param newRestrictBackground True if data saver is enabled.
6520 */
6521 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6522 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6523
6524 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6525 NetworkRequest nr = nai.requestAt(i);
6526 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6527 final int uidRules = mUidRules.get(nri.mUid);
6528 final boolean oldBlocked, newBlocked;
6529 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6530 // between these two calls.
6531 synchronized (mVpns) {
6532 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6533 oldRestrictBackground);
6534 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6535 newRestrictBackground);
6536 }
6537 if (oldBlocked != newBlocked) {
6538 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6539 encodeBool(newBlocked));
6540 }
6541 }
6542 }
6543
6544 /**
6545 * Notify apps with a given UID of the new blocked state according to new uid rules.
6546 * @param uid The uid for which the rules changed.
6547 * @param newRules The new rules to apply.
6548 */
6549 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6550 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6551 final boolean metered = nai.networkCapabilities.isMetered();
6552 final boolean oldBlocked, newBlocked;
6553 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6554 // rules changed event. And this function actually loop through all connected nai and
6555 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6556 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6557 synchronized (mVpns) {
6558 oldBlocked = isUidNetworkingWithVpnBlocked(
6559 uid, mUidRules.get(uid), metered, mRestrictBackground);
6560 newBlocked = isUidNetworkingWithVpnBlocked(
6561 uid, newRules, metered, mRestrictBackground);
6562 }
6563 if (oldBlocked == newBlocked) {
Junyu Laic685f502019-04-09 08:59:00 -07006564 continue;
junyulai05986c62018-08-07 19:50:45 +08006565 }
6566 final int arg = encodeBool(newBlocked);
6567 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6568 NetworkRequest nr = nai.requestAt(i);
6569 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6570 if (nri != null && nri.mUid == uid) {
6571 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6572 }
6573 }
6574 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006575 }
6576
Chalard Jeanff46a252019-04-10 23:07:55 +09006577 @VisibleForTesting
6578 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006579 // The NetworkInfo we actually send out has no bearing on the real
6580 // state of affairs. For example, if the default connection is mobile,
6581 // and a request for HIPRI has just gone away, we need to pretend that
6582 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6583 // the state to DISCONNECTED, even though the network is of type MOBILE
6584 // and is still connected.
6585 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6586 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006587 if (state != DetailedState.DISCONNECTED) {
6588 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006589 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006590 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006591 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006592 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6593 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6594 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6595 if (info.isFailover()) {
6596 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6597 nai.networkInfo.setFailover(false);
6598 }
6599 if (info.getReason() != null) {
6600 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6601 }
6602 if (info.getExtraInfo() != null) {
6603 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6604 }
6605 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006606 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006607 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006608 if (newDefaultAgent != null) {
6609 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6610 newDefaultAgent.networkInfo);
6611 } else {
6612 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6613 }
6614 }
6615 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6616 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006617 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006618 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006619 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006620 }
6621 }
6622 }
6623
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006624 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006625 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006626 String notification = ConnectivityManager.getCallbackName(notifyType);
6627 log("notifyType " + notification + " for " + networkAgent.name());
6628 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006629 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6630 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006631 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6632 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006633 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6634 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006635 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006636 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006637 } else {
6638 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6639 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006640 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006641 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006642
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006643 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6644 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6645 }
6646
Jeff Sharkey69736342014-12-08 14:50:12 -08006647 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006648 * Returns the list of all interfaces that could be used by network traffic that does not
6649 * explicitly specify a network. This includes the default network, but also all VPNs that are
6650 * currently connected.
6651 *
6652 * Must be called on the handler thread.
6653 */
6654 private Network[] getDefaultNetworks() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006655 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006656 ArrayList<Network> defaultNetworks = new ArrayList<>();
6657 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6658 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6659 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6660 defaultNetworks.add(nai.network);
6661 }
6662 }
6663 return defaultNetworks.toArray(new Network[0]);
6664 }
6665
6666 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006667 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6668 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006669 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006670 private void notifyIfacesChangedForNetworkStats() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006671 ensureRunningOnConnectivityServiceThread();
6672 String activeIface = null;
6673 LinkProperties activeLinkProperties = getActiveLinkProperties();
6674 if (activeLinkProperties != null) {
6675 activeIface = activeLinkProperties.getInterfaceName();
6676 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006677 try {
Varun Anand02c50ef2019-02-07 14:13:13 -08006678 mStatsService.forceUpdateIfaces(
6679 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006680 } catch (Exception ignored) {
6681 }
6682 }
6683
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006684 @Override
6685 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006686 int user = UserHandle.getUserId(Binder.getCallingUid());
6687 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006688 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006689 return mVpns.get(user).addAddress(address, prefixLength);
6690 }
6691 }
6692
6693 @Override
6694 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006695 int user = UserHandle.getUserId(Binder.getCallingUid());
6696 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006697 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006698 return mVpns.get(user).removeAddress(address, prefixLength);
6699 }
6700 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006701
6702 @Override
6703 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006704 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006705 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006706 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006707 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006708 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006709 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006710 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006711 mHandler.post(() -> {
6712 // Update VPN's capabilities based on updated underlying network set.
6713 updateAllVpnsCapabilities();
6714 notifyIfacesChangedForNetworkStats();
6715 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006716 }
6717 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006718 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006719
6720 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006721 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006722 enforceConnectivityInternalPermission();
Remi NGUYEN VAN9ca4c622019-04-09 02:04:54 -07006723 String settingUrl = mContext.getResources().getString(
6724 R.string.config_networkCaptivePortalServerUrl);
6725
6726 if (!TextUtils.isEmpty(settingUrl)) {
6727 return settingUrl;
6728 }
6729
6730 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
6731 Settings.Global.CAPTIVE_PORTAL_HTTP_URL);
6732 if (!TextUtils.isEmpty(settingUrl)) {
6733 return settingUrl;
6734 }
6735
6736 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainib7c24872016-01-04 12:16:14 -08006737 }
6738
6739 @Override
junyulai7c469172019-01-16 20:23:34 +08006740 public void startNattKeepalive(Network network, int intervalSeconds,
6741 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006742 enforceKeepalivePermission();
6743 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006744 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006745 intervalSeconds, cb,
junyulaie4135282019-01-03 18:50:15 +08006746 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006747 }
6748
6749 @Override
junyulai215b8772019-01-15 11:32:44 +08006750 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006751 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006752 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006753 mKeepaliveTracker.startNattKeepalive(
6754 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006755 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006756 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6757 }
6758
6759 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006760 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006761 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006762 enforceKeepalivePermission();
6763 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006764 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006765 }
6766
6767 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006768 public void stopKeepalive(Network network, int slot) {
6769 mHandler.sendMessage(mHandler.obtainMessage(
junyulaie4135282019-01-03 18:50:15 +08006770 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006771 }
6772
6773 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006774 public void factoryReset() {
6775 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006776
6777 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6778 return;
6779 }
6780
Robin Lee3b3dd942015-05-12 18:14:58 +01006781 final int userId = UserHandle.getCallingUserId();
6782
Stuart Scottf1fb3972015-04-02 18:00:02 -07006783 // Turn airplane mode off
6784 setAirplaneMode(false);
6785
Stuart Scotte3e314d2015-04-20 14:07:45 -07006786 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6787 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006788 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006789 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006790 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006791 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006792 }
6793
Stuart Scotte3e314d2015-04-20 14:07:45 -07006794 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006795 // Remove always-on package
6796 synchronized (mVpns) {
6797 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6798 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006799 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006800 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6801 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006802
Hugo Benichi69744342017-11-27 10:57:16 +09006803 // Turn Always-on VPN off
6804 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6805 final long ident = Binder.clearCallingIdentity();
6806 try {
6807 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6808 mLockdownEnabled = false;
6809 setLockdownTracker(null);
6810 } finally {
6811 Binder.restoreCallingIdentity(ident);
6812 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006813 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006814
Hugo Benichi69744342017-11-27 10:57:16 +09006815 // Turn VPN off
6816 VpnConfig vpnConfig = getVpnConfig(userId);
6817 if (vpnConfig != null) {
6818 if (vpnConfig.legacy) {
6819 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6820 } else {
6821 // Prevent this app (packagename = vpnConfig.user) from initiating
6822 // VPN connections in the future without user intervention.
6823 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006824
Hugo Benichi69744342017-11-27 10:57:16 +09006825 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6826 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006827 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006828 }
6829 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006830
6831 Settings.Global.putString(mContext.getContentResolver(),
6832 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006833 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006834
Ricky Wai44dcbde2018-01-23 04:09:45 +00006835 @Override
6836 public byte[] getNetworkWatchlistConfigHash() {
6837 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6838 if (nwm == null) {
6839 loge("Unable to get NetworkWatchlistManager");
6840 return null;
6841 }
6842 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6843 return nwm.getWatchlistConfigHash();
6844 }
6845
Paul Jensencf4c2c62015-07-01 14:16:32 -04006846 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006847 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6848 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006849 }
6850
6851 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006852 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6853 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6854 }
6855
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006856 @VisibleForTesting
6857 public boolean hasService(String name) {
6858 return ServiceManager.checkService(name) != null;
6859 }
6860
Hugo Benichi64901e52017-10-19 14:42:40 +09006861 @VisibleForTesting
6862 protected IpConnectivityMetrics.Logger metricsLogger() {
6863 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6864 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006865 }
6866
6867 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006868 int[] transports = nai.networkCapabilities.getTransportTypes();
6869 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006870 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006871
6872 private static boolean toBool(int encodedBoolean) {
6873 return encodedBoolean != 0; // Only 0 means false.
6874 }
6875
6876 private static int encodeBool(boolean b) {
6877 return b ? 1 : 0;
6878 }
mswest46386886f2018-03-12 10:34:34 -07006879
6880 @Override
6881 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6882 FileDescriptor err, String[] args, ShellCallback callback,
6883 ResultReceiver resultReceiver) {
6884 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6885 }
6886
6887 private class ShellCmd extends ShellCommand {
6888
6889 @Override
6890 public int onCommand(String cmd) {
6891 if (cmd == null) {
6892 return handleDefaultCommands(cmd);
6893 }
6894 final PrintWriter pw = getOutPrintWriter();
6895 try {
6896 switch (cmd) {
6897 case "airplane-mode":
6898 final String action = getNextArg();
6899 if ("enable".equals(action)) {
6900 setAirplaneMode(true);
6901 return 0;
6902 } else if ("disable".equals(action)) {
6903 setAirplaneMode(false);
6904 return 0;
6905 } else if (action == null) {
6906 final ContentResolver cr = mContext.getContentResolver();
6907 final int enabled = Settings.Global.getInt(cr,
6908 Settings.Global.AIRPLANE_MODE_ON);
6909 pw.println(enabled == 0 ? "disabled" : "enabled");
6910 return 0;
6911 } else {
6912 onHelp();
6913 return -1;
6914 }
6915 default:
6916 return handleDefaultCommands(cmd);
6917 }
6918 } catch (Exception e) {
6919 pw.println(e);
6920 }
6921 return -1;
6922 }
6923
6924 @Override
6925 public void onHelp() {
6926 PrintWriter pw = getOutPrintWriter();
6927 pw.println("Connectivity service commands:");
6928 pw.println(" help");
6929 pw.println(" Print this help text.");
6930 pw.println(" airplane-mode [enable|disable]");
6931 pw.println(" Turn airplane mode on or off.");
6932 pw.println(" airplane-mode");
6933 pw.println(" Get airplane mode.");
6934 }
6935 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006936
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006937 @GuardedBy("mVpns")
6938 private Vpn getVpnIfOwner() {
6939 final int uid = Binder.getCallingUid();
6940 final int user = UserHandle.getUserId(uid);
6941
6942 final Vpn vpn = mVpns.get(user);
6943 if (vpn == null) {
6944 return null;
6945 } else {
6946 final VpnInfo info = vpn.getVpnInfo();
6947 return (info == null || info.ownerUid != uid) ? null : vpn;
6948 }
6949 }
6950
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006951 /**
6952 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6953 * for testing.
6954 */
6955 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6956 if (checkNetworkStackPermission()) {
6957 return null;
6958 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006959 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006960 Vpn vpn = getVpnIfOwner();
6961 if (vpn != null) {
6962 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006963 }
6964 }
6965 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6966 + "permission");
6967 }
6968
6969 /**
6970 * @param connectionInfo the connection to resolve.
6971 * @return {@code uid} if the connection is found and the app has permission to observe it
6972 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6973 * connection is not found.
6974 */
6975 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6976 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6977 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6978 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6979 }
6980
6981 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6982 connectionInfo.local, connectionInfo.remote);
6983
6984 /* Filter out Uids not associated with the VPN. */
6985 if (vpn != null && !vpn.appliesToUid(uid)) {
6986 return INVALID_UID;
6987 }
6988
6989 return uid;
6990 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006991
6992 @Override
6993 public boolean isCallerCurrentAlwaysOnVpnApp() {
6994 synchronized (mVpns) {
6995 Vpn vpn = getVpnIfOwner();
6996 return vpn != null && vpn.getAlwaysOn();
6997 }
6998 }
6999
7000 @Override
7001 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
7002 synchronized (mVpns) {
7003 Vpn vpn = getVpnIfOwner();
7004 return vpn != null && vpn.getLockdown();
7005 }
7006 }
Benedict Wong99a48412018-11-09 14:45:34 -08007007
7008 /**
7009 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
7010 *
7011 * <p>The TestNetworkService must be run in the system server due to TUN creation.
7012 */
7013 @Override
7014 public IBinder startOrGetTestNetworkService() {
7015 synchronized (mTNSLock) {
7016 TestNetworkService.enforceTestNetworkPermissions(mContext);
7017
7018 if (mTNS == null) {
7019 mTNS = new TestNetworkService(mContext, mNMS);
7020 }
7021
7022 return mTNS;
7023 }
7024 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07007025}