blob: 6c27c4a33cae25fa72bca3184a53fe4071b1bc6b [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090020import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090025import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000035import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090037import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090038import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090039import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070049import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090050import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070051import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090052import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070054import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070055import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080056import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080057import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080058import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070059import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040061import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090062import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090063import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090064import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080072import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080074import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Roshan Pius98f59ec2021-02-23 08:47:39 -080076import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
77import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
78import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090079import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090080import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060081import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070082import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080083import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090084import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070085import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
86import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090087import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070088import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080089import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090090import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070091import static android.system.OsConstants.IPPROTO_TCP;
92import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060093
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090094import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
95
Cody Kesting83bb5fa2020-01-05 14:06:39 -080096import static java.util.Map.Entry;
97
Chalard Jean5b639762020-03-09 21:25:37 +090098import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +000099import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800100import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800101import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800102import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800103import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700104import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +0800105import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700106import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800107import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800108import android.content.ContentResolver;
109import android.content.Context;
110import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700111import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800112import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700113import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900114import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900115import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700116import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800117import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800118import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900120import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800121import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900122import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900123import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800124import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900125import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800126import android.net.DnsResolverServiceManager;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900127import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800128import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800130import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800131import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800132import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900133import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900134import android.net.INetworkMonitor;
135import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900136import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900137import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700138import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800139import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900140import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900141import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900142import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800143import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100144import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800145import android.net.NativeNetworkConfig;
146import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800147import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700148import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700149import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900150import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700151import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800152import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700153import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900154import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900155import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000156import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900157import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700158import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900159import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700160import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700162import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800163import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900164import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700165import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000166import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800167import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900168import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800169import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400170import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700171import android.net.QosCallbackException;
172import android.net.QosFilter;
173import android.net.QosSocketFilter;
174import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700175import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800176import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800177import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800178import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900179import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400180import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800181import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800182import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400183import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800184import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900185import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900186import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900187import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800188import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900189import android.net.networkstack.ModuleNetworkStackClient;
190import android.net.networkstack.NetworkStackClientBase;
paulhu7c0a2e62021-01-08 00:51:49 +0800191import android.net.resolv.aidl.DnsHealthEventParcel;
192import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
193import android.net.resolv.aidl.Nat64PrefixEventParcel;
194import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900195import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900196import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800197import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800199import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700200import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700202import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700203import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800204import android.os.Looper;
205import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700206import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700207import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900208import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800209import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700210import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700211import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800212import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700213import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900214import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900215import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700216import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700217import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400218import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900220import android.sysprop.NetworkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -0700221import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700222import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800223import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900224import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000225import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600226import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900227import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700228import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700229import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900231import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400232import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400233import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700234import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900235import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800236import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900237import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800238import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900239import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900240import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900241import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
242import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900243import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800244import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800245import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000246import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900247import com.android.server.connectivity.AutodestructReference;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900248import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900249import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500250import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900251import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900252import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100253import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700254import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700255import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600256import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900257import com.android.server.connectivity.NetworkNotificationManager;
258import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900259import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900260import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700261import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800262import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900263import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700264import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800265import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600266
Josh Gao461a1222020-06-16 15:58:11 -0700267import libcore.io.IoUtils;
268
The Android Open Source Project28527d22009-03-03 19:31:44 -0800269import java.io.FileDescriptor;
270import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900271import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700272import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700273import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900274import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700275import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700276import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700277import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700278import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800279import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900280import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800281import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700282import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700283import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700284import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700285import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900286import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700287import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900288import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600289import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900290import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600291import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900292import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800293
294/**
295 * @hide
296 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800297public class ConnectivityService extends IConnectivityManager.Stub
298 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900299 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800300
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900301 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900302 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900303 private static final String NETWORK_ARG = "networks";
304 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900305
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900306 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900307 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
308 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800309
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900310 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700311
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100312 /**
313 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
314 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800315 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100316 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
317 * (preferably via runtime resource overlays).
318 */
319 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
320 "http://connectivitycheck.gstatic.com/generate_204";
321
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700322 // TODO: create better separation between radio types and network types
323
Robert Greenwalt2034b912009-08-12 16:08:25 -0700324 // how long to wait before switching back to a radio's default network
325 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
326 // system property that can override the above value
327 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
328 "android.telephony.apn-restore";
329
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900330 // How long to wait before putting up a "This network doesn't have an Internet connection,
331 // connect anyway?" dialog after the user selects a network that doesn't validate.
332 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
333
junyulai0ac374f2020-12-14 18:41:52 +0800334 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900335 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
336 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800337 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700338
339 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900340 @VisibleForTesting
341 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700342
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900343 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700344 @VisibleForTesting
345 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900346
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900347 @VisibleForTesting
348 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800349 @VisibleForTesting
350 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900351 // True if the cell radio of the device is capable of time-sharing.
352 @VisibleForTesting
353 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900354
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800355 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800356 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800357 private final int mReleasePendingIntentDelayMs;
358
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900359 private MockableSystemProperties mSystemProperties;
360
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000361 @VisibleForTesting
362 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700363
Chalard Jean9473c982021-07-29 20:03:04 +0900364 @VisibleForTesting
365 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700366 @VisibleForTesting
367 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700368
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900369 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700370
junyulaif2c67e42018-08-07 19:50:45 +0800371 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000372 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
373 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800374 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000375 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800376
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900377 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900378 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000379 // The Context is created for UserHandle.ALL.
380 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900381 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900382 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700383 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700384 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800385
Chenbo Feng15416292018-11-08 17:36:21 -0800386 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800387 protected IDnsResolver mDnsResolver;
388 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800389 protected INetd mNetd;
junyulaie7c7d2a2021-01-26 15:29:15 +0800390 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800391 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800392 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700393
Benedict Wong493e04b2018-11-09 14:45:34 -0800394 /**
395 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
396 * instances.
397 */
398 @GuardedBy("mTNSLock")
399 private TestNetworkService mTNS;
400
401 private final Object mTNSLock = new Object();
402
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700403 private String mCurrentTcpBufferSizes;
404
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900405 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800406 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900407
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500408 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400409 // Tear down networks that have no chance (e.g. even if validated) of becoming
410 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500411 // all networks have been rematched against all NetworkRequests.
412 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400413 // Don't reap networks. This should be passed when some networks have not yet been
414 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500415 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900416 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500417
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900418 private enum UnneededFor {
419 LINGER, // Determine whether this network is unneeded and should be lingered.
420 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
421 }
422
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700423 /**
paulhuaa0743d2021-05-26 21:56:03 +0800424 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800425 * should have priority. The order is passed to netd which will use it together
426 * with UID ranges to generate the corresponding IP rule. This serves to
427 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800428 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800429 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800430 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800431 *
paulhu48291862021-07-14 14:53:57 +0800432 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
433 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800434 */
paulhu48291862021-07-14 14:53:57 +0800435 // Bound for the lowest valid preference order.
436 static final int PREFERENCE_ORDER_LOWEST = 999;
437 // Used when sending to netd to code for "no order".
438 static final int PREFERENCE_ORDER_NONE = 0;
439 // Order for requests that don't code for a per-app preference. As it is
440 // out of the valid range, the corresponding order should be
441 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800442 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800443 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
444 // Order for the default internet request. Since this must always have the
paulhuaa0743d2021-05-26 21:56:03 +0800445 // lowest priority, its value is larger than the largest acceptable value. As
paulhu48291862021-07-14 14:53:57 +0800446 // it is out of the valid range, the corresponding order should be
447 // PREFERENCE_ORDER_NONE when sending to netd.
448 static final int PREFERENCE_ORDER_DEFAULT = 1000;
paulhuaa0743d2021-05-26 21:56:03 +0800449 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800450 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
451 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800452 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800453 static final int PREFERENCE_ORDER_OEM = 10;
454 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800455 // See {@link #setProfileNetworkPreference}.
456 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800457 static final int PREFERENCE_ORDER_PROFILE = 20;
458 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800459 // better scores are connected.
460 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800461 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800462 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
paulhue9913722021-05-26 15:19:20 +0800463
464 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700465 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700466 * from one net to another. Clear happens when we get a new
467 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
468 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700469 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700470 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700471
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700472 /**
473 * used internally to reload global proxy settings
474 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700475 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700476
Robert Greenwalt34848c02011-03-25 13:09:25 -0700477 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400478 * PAC manager has received new port.
479 */
480 private static final int EVENT_PROXY_HAS_CHANGED = 16;
481
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700482 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900483 * used internally when registering NetworkProviders
484 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700485 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900486 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700487
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700488 /**
489 * used internally when registering NetworkAgents
490 * obj = Messenger
491 */
492 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
493
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700494 /**
495 * used to add a network request
496 * includes a NetworkRequestInfo
497 */
498 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
499
500 /**
501 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900502 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700503 * cancel it.
504 * includes a NetworkRequestInfo
505 */
506 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
507
508 /**
509 * used to add a network listener - no request
510 * includes a NetworkRequestInfo
511 */
512 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
513
514 /**
515 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400516 * arg1 = UID of caller
517 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700518 */
519 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
520
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700521 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900522 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700523 * obj = Messenger
524 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900525 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700526
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700527 /**
528 * used internally to expire a wakelock when transitioning
529 * from one net to another. Expire happens when we fail to find
530 * a new network (typically after 1 minute) -
531 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
532 * a replacement network.
533 */
534 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
535
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700536 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800537 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400538 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800539 */
540 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
541
542 /**
543 * used to remove a pending intent and its associated network request.
544 * arg1 = UID of caller
545 * obj = PendingIntent
546 */
547 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
548
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900549 /**
550 * used to specify whether a network should be used even if unvalidated.
551 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
552 * arg2 = whether to remember this choice in the future (1 or 0)
553 * obj = network
554 */
555 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
556
557 /**
558 * used to ask the user to confirm a connection to an unvalidated network.
559 * obj = network
560 */
561 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700562
Erik Kline05f2b402015-04-30 12:58:40 +0900563 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700564 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900565 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700566 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900567
Paul Jensenc8873fc2015-06-17 14:15:39 -0400568 /**
569 * used to add a network listener with a pending intent
570 * obj = NetworkRequestInfo
571 */
572 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
573
Hugo Benichid6b510a2017-04-06 17:22:18 +0900574 /**
575 * used to specify whether a network should not be penalized when it becomes unvalidated.
576 */
577 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
578
579 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700580 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900581 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700582 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900583
Erik Kline31b4a9e2018-01-11 21:07:29 +0900584 // Handle changes in Private DNS settings.
585 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
586
dalyk1720e542018-03-05 12:42:22 -0500587 // Handle private DNS validation status updates.
588 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
589
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900590 /**
591 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
592 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800593 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
594 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
595 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900596 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900597 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900598
599 /**
600 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
601 * config was resolved.
602 * obj = PrivateDnsConfig
603 * arg2 = netid
604 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900605 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900606
607 /**
608 * Request ConnectivityService display provisioning notification.
609 * arg1 = Whether to make the notification visible.
610 * arg2 = NetID.
611 * obj = Intent to be launched when notification selected by user, null if !arg1.
612 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900613 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900614
615 /**
lucaslin2240ef62019-03-12 13:08:03 +0800616 * Used to specify whether a network should be used even if connectivity is partial.
617 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
618 * false)
619 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
620 * obj = network
621 */
lucaslin444d43a2020-02-20 16:56:59 +0800622 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800623
624 /**
lucasline117e2e2019-10-22 18:27:33 +0800625 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
626 * Both of the arguments are bitmasks, and the value of bits come from
627 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
628 * arg1 = A bitmask to describe which probes are completed.
629 * arg2 = A bitmask to describe which probes are successful.
630 */
lucaslin444d43a2020-02-20 16:56:59 +0800631 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800632
633 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900634 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
635 * arg1 = unused
636 * arg2 = netId
637 * obj = captive portal data
638 */
lucaslin444d43a2020-02-20 16:56:59 +0800639 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900640
641 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900642 * Used by setRequireVpnForUids.
643 * arg1 = whether the specified UID ranges are required to use a VPN.
644 * obj = Array of UidRange objects.
645 */
646 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
647
648 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900649 * Used internally when setting the default networks for OemNetworkPreferences.
650 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800651 */
652 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
653
654 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800655 * Used to indicate the system default network becomes active.
656 */
657 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
658
659 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900660 * Used internally when setting a network preference for a user profile.
661 * obj = Pair<ProfileNetworkPreference, Listener>
662 */
663 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
664
665 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000666 * Event to specify that reasons for why an uid is blocked changed.
667 * arg1 = uid
668 * arg2 = blockedReasons
669 */
670 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
671
672 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900673 * Event to register a new network offer
674 * obj = NetworkOffer
675 */
676 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
677
678 /**
679 * Event to unregister an existing network offer
680 * obj = INetworkOfferCallback
681 */
682 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
683
684 /**
paulhu51f77dc2021-06-07 02:34:20 +0000685 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
686 */
687 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
688
689 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800690 * Event to set temporary allow bad wifi within a limited time to override
691 * {@code config_networkAvoidBadWifi}.
692 */
693 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
694
695 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900696 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
697 * should be shown.
698 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900699 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900700
701 /**
702 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
703 * should be hidden.
704 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900705 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900706
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800707 /**
708 * The maximum alive time to allow bad wifi configuration for testing.
709 */
710 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
711
Hugo Benichi47011212017-03-30 10:46:05 +0900712 private static String eventName(int what) {
713 return sMagicDecoderRing.get(what, Integer.toString(what));
714 }
715
paulhua10d8212020-11-10 15:32:56 +0800716 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900717 final DnsResolverServiceManager dsm = context.getSystemService(
718 DnsResolverServiceManager.class);
719 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800720 }
721
Cody Kesting73708bf2019-12-18 10:57:50 -0800722 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900723 @VisibleForTesting
724 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700725 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700726 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700727 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700728 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800729 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
730 @VisibleForTesting
731 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
732
Erik Kline32120082017-12-13 19:40:49 +0900733 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900734 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700735
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400736 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800737 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400738
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700739 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800740 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700741
Chalard Jean5d70ba42018-06-07 16:44:04 +0900742 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
743 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000744 @VisibleForTesting
745 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400746
Erik Kline05f2b402015-04-30 12:58:40 +0900747 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700748
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400749 private UserManager mUserManager;
750
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700751 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900752 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700753
Valentin Iftime9fa35092019-09-24 13:32:13 +0200754 private Set<String> mWolSupportedInterfaces;
755
Roshan Pius08c94fb2020-01-16 12:17:17 -0800756 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800757 private final AppOpsManager mAppOpsManager;
758
759 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400760
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900761 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700762 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900763 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900764 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900765
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700766 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800767 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700768
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900769 // Sequence number for NetworkProvider IDs.
770 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
771 NetworkProvider.FIRST_PROVIDER_ID);
772
Erik Klineedf878b2015-07-09 18:24:03 +0900773 // NetworkRequest activity String log entries.
774 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
775 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
776
Hugo Benichid159fdd2016-07-11 11:05:12 +0900777 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900778 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900779 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
780
Hugo Benichi47011212017-03-30 10:46:05 +0900781 private static final int MAX_WAKELOCK_LOGS = 20;
782 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900783 private int mTotalWakelockAcquisitions = 0;
784 private int mTotalWakelockReleases = 0;
785 private long mTotalWakelockDurationMs = 0;
786 private long mMaxWakelockDurationMs = 0;
787 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900788
Hugo Benichi208c0102016-07-28 17:53:06 +0900789 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900790
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700791 @GuardedBy("mBandwidthRequests")
792 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
793
Erik Kline95ecfee2016-10-02 18:02:14 +0900794 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900795 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900796
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900797 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800798 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
799 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800800
Robert Greenwalt802c1102014-06-02 15:32:02 -0700801 /**
802 * Implements support for the legacy "one network per network type" model.
803 *
804 * We used to have a static array of NetworkStateTrackers, one for each
805 * network type, but that doesn't work any more now that we can have,
806 * for example, more that one wifi network. This class stores all the
807 * NetworkAgentInfo objects that support a given type, but the legacy
808 * API will only see the first one.
809 *
810 * It serves two main purposes:
811 *
812 * 1. Provide information about "the network for a given type" (since this
813 * API only supports one).
814 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
815 * the first network for a given type changes, or if the default network
816 * changes.
817 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900818 @VisibleForTesting
819 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900820
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900821 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900822 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900823
Robert Greenwalt802c1102014-06-02 15:32:02 -0700824 /**
825 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
826 * Each list holds references to all NetworkAgentInfos that are used to
827 * satisfy requests for that network type.
828 *
829 * This array is built out at startup such that an unsupported network
830 * doesn't get an ArrayList instance, making this a tristate:
831 * unsupported, supported but not active and active.
832 *
833 * The actual lists are populated when we scan the network types that
834 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900835 *
836 * Threading model:
837 * - addSupportedType() is only called in the constructor
838 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
839 * They are therefore not thread-safe with respect to each other.
840 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
841 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900842 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900843 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700844 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900845 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900846 @NonNull
847 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700848
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900849 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
850 // an entry have no timer (equivalent to -1). Lazily loaded.
851 @NonNull
852 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
853
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900854 LegacyTypeTracker(@NonNull ConnectivityService service) {
855 mService = service;
856 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700857 }
858
Chiachang Wang3bc52762021-11-25 14:17:57 +0800859 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
860 // addressed.
861 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900862 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
863 final PackageManager pm = ctx.getPackageManager();
864 if (pm.hasSystemFeature(FEATURE_WIFI)) {
865 addSupportedType(TYPE_WIFI);
866 }
867 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
868 addSupportedType(TYPE_WIFI_P2P);
869 }
870 if (tm.isDataCapable()) {
871 // Telephony does not have granular support for these types: they are either all
872 // supported, or none is supported
873 addSupportedType(TYPE_MOBILE);
874 addSupportedType(TYPE_MOBILE_MMS);
875 addSupportedType(TYPE_MOBILE_SUPL);
876 addSupportedType(TYPE_MOBILE_DUN);
877 addSupportedType(TYPE_MOBILE_HIPRI);
878 addSupportedType(TYPE_MOBILE_FOTA);
879 addSupportedType(TYPE_MOBILE_IMS);
880 addSupportedType(TYPE_MOBILE_CBS);
881 addSupportedType(TYPE_MOBILE_IA);
882 addSupportedType(TYPE_MOBILE_EMERGENCY);
883 }
884 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
885 addSupportedType(TYPE_BLUETOOTH);
886 }
887 if (pm.hasSystemFeature(FEATURE_WATCH)) {
888 // TYPE_PROXY is only used on Wear
889 addSupportedType(TYPE_PROXY);
890 }
891 // Ethernet is often not specified in the configs, although many devices can use it via
892 // USB host adapters. Add it as long as the ethernet service is here.
893 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
894 addSupportedType(TYPE_ETHERNET);
895 }
896
897 // Always add TYPE_VPN as a supported type
898 addSupportedType(TYPE_VPN);
899 }
900
901 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700902 if (mTypeLists[type] != null) {
903 throw new IllegalStateException(
904 "legacy list for type " + type + "already initialized");
905 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900906 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700907 }
908
Robert Greenwalt802c1102014-06-02 15:32:02 -0700909 public boolean isTypeSupported(int type) {
910 return isNetworkTypeValid(type) && mTypeLists[type] != null;
911 }
912
913 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900914 synchronized (mTypeLists) {
915 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
916 return mTypeLists[type].get(0);
917 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700918 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900919 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700920 }
921
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900922 public int getRestoreTimerForType(int type) {
923 synchronized (mTypeLists) {
924 if (mRestoreTimers == null) {
925 mRestoreTimers = loadRestoreTimers();
926 }
927 return mRestoreTimers.getOrDefault(type, -1);
928 }
929 }
930
931 private ArrayMap<Integer, Integer> loadRestoreTimers() {
932 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900933 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900934 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
935 for (final String config : configs) {
936 final String[] splits = TextUtils.split(config, ",");
937 if (splits.length != 2) {
938 logwtf("Invalid restore timer token count: " + config);
939 continue;
940 }
941 try {
942 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
943 } catch (NumberFormatException e) {
944 logwtf("Invalid restore timer number format: " + config, e);
945 }
946 }
947 return ret;
948 }
949
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700950 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900951 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900952 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900953 log("Sending " + state
954 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900955 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900956 }
957 }
958
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900959 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
960 // network type, to preserve previous behaviour.
961 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
962 if (vpnNai != mService.getLegacyLockdownNai()) return;
963
964 if (vpnNai.declaredUnderlyingNetworks == null
965 || vpnNai.declaredUnderlyingNetworks.length != 1) {
966 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
967 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
968 return;
969 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900970 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900971 vpnNai.declaredUnderlyingNetworks[0]);
972 if (underlyingNai == null) return;
973
974 final int type = underlyingNai.networkInfo.getType();
975 final DetailedState state = DetailedState.CONNECTED;
976 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
977 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
978 }
979
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900980 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700981 public void add(int type, NetworkAgentInfo nai) {
982 if (!isTypeSupported(type)) {
983 return; // Invalid network type.
984 }
985 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
986
987 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
988 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700989 return;
990 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900991 synchronized (mTypeLists) {
992 list.add(nai);
993 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +0900994
Chalard Jean5b409c72021-02-04 13:12:59 +0900995 // Send a broadcast if this is the first network of its type or if it's the default.
996 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900997
998 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
999 // to preserve previous behaviour.
1000 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001001 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001002 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1003 mService.sendLegacyNetworkBroadcast(nai, state, type);
1004 }
1005
1006 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1007 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001008 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001009 }
1010
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001011 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001012 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001013 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1014 if (list == null || list.isEmpty()) {
1015 return;
1016 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001017 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001018
Hugo Benichi389633f2016-06-21 09:48:07 +09001019 synchronized (mTypeLists) {
1020 if (!list.remove(nai)) {
1021 return;
1022 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001023 }
1024
Lorenzo Colitti49767722015-05-01 00:30:10 +09001025 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001026 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1027 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001028 }
1029
1030 if (!list.isEmpty() && wasFirstNetwork) {
1031 if (DBG) log("Other network available for type " + type +
1032 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001033 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001034 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001035 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001036 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001037 }
1038 }
1039
1040 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001041 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1042 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001043 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001044 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001045 }
1046 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001047
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001048 // send out another legacy broadcast - currently only used for suspend/unsuspend
1049 // toggle
1050 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001051 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001052 final DetailedState state = nai.networkInfo.getDetailedState();
1053 for (int type = 0; type < mTypeLists.length; type++) {
1054 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001055 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001056 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001057 if (isFirst || contains && isDefault) {
1058 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001059 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001060 }
1061 }
1062 }
1063
Robert Greenwalt94e22142014-07-30 16:31:24 -07001064 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001065 pw.println("mLegacyTypeTracker:");
1066 pw.increaseIndent();
1067 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001068 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001069 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001070 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001071 pw.println();
1072 pw.println("Current state:");
1073 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001074 synchronized (mTypeLists) {
1075 for (int type = 0; type < mTypeLists.length; type++) {
1076 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1077 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001078 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001079 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001080 }
1081 }
1082 pw.decreaseIndent();
1083 pw.decreaseIndent();
1084 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001085 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001086 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001087 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001088
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001089 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001090 /**
1091 * Helper class which parses out priority arguments and dumps sections according to their
1092 * priority. If priority arguments are omitted, function calls the legacy dump command.
1093 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001094 private class LocalPriorityDump {
1095 private static final String PRIORITY_ARG = "--dump-priority";
1096 private static final String PRIORITY_ARG_HIGH = "HIGH";
1097 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1098
1099 LocalPriorityDump() {}
1100
1101 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1102 doDump(fd, pw, new String[] {DIAG_ARG});
1103 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001104 }
1105
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001106 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1107 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001108 }
1109
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001110 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1111 if (args == null) {
1112 dumpNormal(fd, pw, args);
1113 return;
1114 }
1115
1116 String priority = null;
1117 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1118 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1119 argIndex++;
1120 priority = args[argIndex];
1121 }
1122 }
1123
1124 if (PRIORITY_ARG_HIGH.equals(priority)) {
1125 dumpHigh(fd, pw);
1126 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1127 dumpNormal(fd, pw, args);
1128 } else {
1129 // ConnectivityService publishes binder service using publishBinderService() with
1130 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001131 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1132 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001133 // TODO: Integrate into signal dump.
1134 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001135 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001136 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001137 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001138
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001139 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001140 * Keeps track of the number of requests made under different uids.
1141 */
1142 public static class PerUidCounter {
1143 private final int mMaxCountPerUid;
1144
1145 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001146 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001147 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001148 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001149
1150 /**
1151 * Constructor
1152 *
1153 * @param maxCountPerUid the maximum count per uid allowed
1154 */
1155 public PerUidCounter(final int maxCountPerUid) {
1156 mMaxCountPerUid = maxCountPerUid;
1157 }
1158
1159 /**
1160 * Increments the request count of the given uid. Throws an exception if the number
1161 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1162 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1163 *
1164 * @throws ServiceSpecificException with
1165 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1166 * the uid exceed the allowed number.
1167 *
1168 * @param uid the uid that the request was made under
1169 */
1170 public void incrementCountOrThrow(final int uid) {
1171 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001172 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001173 }
1174 }
1175
James Mattis20a4a8b2021-03-28 17:41:09 -07001176 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1177 final int newRequestCount =
1178 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001179 if (newRequestCount >= mMaxCountPerUid
1180 // HACK : the system server is allowed to go over the request count limit
1181 // when it is creating requests on behalf of another app (but not itself,
1182 // so it can still detect its own request leaks). This only happens in the
1183 // per-app API flows in which case the old requests for that particular
1184 // UID will be removed soon.
1185 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1186 // users of transact() should unregister the requests to decrease the count
1187 // before they increase it again by creating a new NRI. Then remove the
1188 // transact() method.
1189 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001190 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001191 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1192 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001193 }
1194 mUidToNetworkRequestCount.put(uid, newRequestCount);
1195 }
1196
Daniel Brightf9e945b2020-06-15 16:10:01 -07001197 /**
1198 * Decrements the request count of the given uid.
1199 *
1200 * @param uid the uid that the request was made under
1201 */
1202 public void decrementCount(final int uid) {
1203 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001204 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001205 }
1206 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001207
1208 private void decrementCount(final int uid, final int numToDecrement) {
1209 final int newRequestCount =
1210 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1211 if (newRequestCount < 0) {
1212 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1213 } else if (newRequestCount == 0) {
1214 mUidToNetworkRequestCount.delete(uid);
1215 } else {
1216 mUidToNetworkRequestCount.put(uid, newRequestCount);
1217 }
1218 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001219 }
1220
1221 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001222 * Dependencies of ConnectivityService, for injection in tests.
1223 */
1224 @VisibleForTesting
1225 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001226 public int getCallingUid() {
1227 return Binder.getCallingUid();
1228 }
1229
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001230 /**
1231 * Get system properties to use in ConnectivityService.
1232 */
1233 public MockableSystemProperties getSystemProperties() {
1234 return new MockableSystemProperties();
1235 }
1236
1237 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001238 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1239 */
1240 public ConnectivityResources getResources(@NonNull Context ctx) {
1241 return new ConnectivityResources(ctx);
1242 }
1243
1244 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001245 * Create a HandlerThread to use in ConnectivityService.
1246 */
1247 public HandlerThread makeHandlerThread() {
1248 return new HandlerThread("ConnectivityServiceThread");
1249 }
1250
1251 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001252 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001253 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001254 public NetworkStackClientBase getNetworkStack() {
1255 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001256 }
1257
1258 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001259 * @see ProxyTracker
1260 */
1261 public ProxyTracker makeProxyTracker(@NonNull Context context,
1262 @NonNull Handler connServiceHandler) {
1263 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1264 }
1265
1266 /**
1267 * @see NetIdManager
1268 */
1269 public NetIdManager makeNetIdManager() {
1270 return new NetIdManager();
1271 }
1272
1273 /**
1274 * @see NetworkUtils#queryUserAccess(int, int)
1275 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001276 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1277 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001278 }
1279
1280 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001281 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1282 * requires CAP_NET_ADMIN, which the unit tests do not have.
1283 */
1284 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1285 InetSocketAddress remote) {
1286 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1287 }
1288
1289 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001290 * @see MultinetworkPolicyTracker
1291 */
1292 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1293 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1294 return new MultinetworkPolicyTracker(c, h, r);
1295 }
1296
Aaron Huang330a4c02020-10-27 03:36:19 +08001297 /**
1298 * @see BatteryStatsManager
1299 */
1300 public void reportNetworkInterfaceForTransports(Context context, String iface,
1301 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001302 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001303 context.getSystemService(BatteryStatsManager.class);
1304 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1305 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001306
1307 public boolean getCellular464XlatEnabled() {
1308 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1309 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001310
1311 /**
1312 * @see PendingIntent#intentFilterEquals
1313 */
1314 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1315 return a.intentFilterEquals(b);
1316 }
1317
1318 /**
1319 * @see LocationPermissionChecker
1320 */
1321 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1322 return new LocationPermissionChecker(context);
1323 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001324
1325 /**
1326 * @see DeviceConfigUtils#isFeatureEnabled
1327 */
1328 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1329 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1330 TETHERING_MODULE_NAME, defaultEnabled);
1331 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001332 }
1333
junyulaie7c7d2a2021-01-26 15:29:15 +08001334 public ConnectivityService(Context context) {
1335 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001336 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1337 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001338 }
1339
1340 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001341 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1342 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001343 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001344
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001345 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001346 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001347 mSystemProperties = mDeps.getSystemProperties();
1348 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001349 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001350 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001351 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001352 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001353
Hugo Benichi208c0102016-07-28 17:53:06 +09001354 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001355 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001356 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1357 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001358 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001359 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001360 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001361 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1362 mDefaultNetworkRequests.add(mDefaultRequest);
1363 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001364
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001365 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001366 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001367
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001368 // The default WiFi request is a background request so that apps using WiFi are
1369 // migrated to a better network (typically ethernet) when one comes up, instead
1370 // of staying on WiFi forever.
1371 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1372 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1373
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001374 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1375 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1376 NetworkRequest.Type.BACKGROUND_REQUEST);
1377
Chalard Jean0702f982021-09-16 21:50:07 +09001378 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1379 // TODO: Consider making the timer customizable.
1380 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1381 mCellularRadioTimesharingCapable =
1382 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1383
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001385 mHandlerThread.start();
1386 mHandler = new InternalHandler(mHandlerThread.getLooper());
1387 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001388 mConnectivityDiagnosticsHandler =
1389 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001390
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001391 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001392 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001393
junyulaie7c7d2a2021-01-26 15:29:15 +08001394 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001395 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001396 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001397 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001398
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001399 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001400 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001401 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001402 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001403
Sudheer Shanka9967d462021-03-18 19:09:25 +00001404 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001405 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1406 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001407 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001408
1409 final PowerManager powerManager = (PowerManager) context.getSystemService(
1410 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001411 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001412 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001413
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001414 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1415 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001416 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001417 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001418 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001419 mProtectedNetworks.add(p);
1420 } else {
1421 if (DBG) loge("Ignoring protectedNetwork " + p);
1422 }
1423 }
1424
soma, kawata29444ae2019-05-23 09:30:40 +09001425 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1426
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001427 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001428
James Mattis02220e22021-03-13 19:27:21 -08001429 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001430 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001431 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001432 final IntentFilter userIntentFilter = new IntentFilter();
1433 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1434 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1435 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1436 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001437
James Mattis02220e22021-03-13 19:27:21 -08001438 // Listen to package add/removes for netd
1439 final IntentFilter packageIntentFilter = new IntentFilter();
1440 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1441 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1442 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1443 packageIntentFilter.addDataScheme("package");
1444 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001445 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001446
lucaslind5c2d072021-02-20 18:59:47 +08001447 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001448
lucaslin66f44212021-02-23 01:12:55 +08001449 mNetdCallback = new NetdCallback();
1450 try {
1451 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1452 } catch (RemoteException | ServiceSpecificException e) {
1453 loge("Error registering event listener :" + e);
1454 }
1455
Erik Kline05f2b402015-04-30 12:58:40 +09001456 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1457 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001458
junyulai7e06ad42019-03-04 22:45:36 +08001459 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001460 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001461 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001462
1463 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001464 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001465 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1466 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001467 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001468 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1469 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001470
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001471 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001472 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001473 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001474
Chiachang Wangc1215d32020-10-20 15:38:58 +08001475 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001476 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001477
Chalard Jean28018572020-12-21 18:36:52 +09001478 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1479 // request that doesn't allow fallback to the default network. It should never be visible
1480 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1481 // arguments like the handler or the DnsResolver.
1482 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001483 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001484 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001485 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001486 new LinkProperties(), new NetworkCapabilities(),
1487 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001488 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1489 mLingerDelayMs, mQosCallbackTracker, mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001490 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001491
Chalard Jean46adcf32018-04-18 20:18:38 +09001492 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001493 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1494 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001495 }
1496
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001497 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1498 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001499 final NetworkCapabilities netCap = new NetworkCapabilities();
1500 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001501 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001502 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001503 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001504 return netCap;
1505 }
1506
James Mattis45d81842021-01-10 14:24:24 -08001507 private NetworkRequest createDefaultRequest() {
1508 return createDefaultInternetRequestForTransport(
1509 TYPE_NONE, NetworkRequest.Type.REQUEST);
1510 }
1511
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001512 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001513 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001514 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001515 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001516 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001517 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001518 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001519 netCap.addTransportType(transportType);
1520 }
James Mattis45d81842021-01-10 14:24:24 -08001521 return createNetworkRequest(type, netCap);
1522 }
1523
1524 private NetworkRequest createNetworkRequest(
1525 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001526 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001527 }
1528
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001529 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1530 NetworkRequest.Type type) {
1531 final NetworkCapabilities netCap = new NetworkCapabilities();
1532 netCap.clearAll();
1533 netCap.addCapability(capability);
1534 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1535 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1536 }
1537
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001538 // Used only for testing.
1539 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001540 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001541 // changing ContentResolver to make registerContentObserver non-final).
1542 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1543 // by subclassing SettingsObserver.
1544 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001545 void updateAlwaysOnNetworks() {
1546 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001547 }
1548
Erik Kline9a62f012018-03-21 07:18:33 -07001549 // See FakeSettingsProvider comment above.
1550 @VisibleForTesting
1551 void updatePrivateDnsSettings() {
1552 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1553 }
1554
paulhu51f77dc2021-06-07 02:34:20 +00001555 @VisibleForTesting
1556 void updateMobileDataPreferredUids() {
1557 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1558 }
1559
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001560 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001561 final boolean enable = mContext.getResources().getBoolean(id);
1562 handleAlwaysOnNetworkRequest(networkRequest, enable);
1563 }
1564
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001565 private void handleAlwaysOnNetworkRequest(
1566 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001567 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001568 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001569 handleAlwaysOnNetworkRequest(networkRequest, enable);
1570 }
1571
1572 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001573 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001574 if (enable == isEnabled) {
1575 return; // Nothing to do.
1576 }
1577
1578 if (enable) {
1579 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001580 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001581 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001582 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001583 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001584 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1585 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001586 }
1587 }
1588
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001589 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001590 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1591 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1592 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1593 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001594 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1595 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001596 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001597 }
1598
paulhu51f77dc2021-06-07 02:34:20 +00001599 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001600 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001601 private void registerSettingsCallbacks() {
1602 // Watch for global HTTP proxy changes.
1603 mSettingsObserver.observe(
1604 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1605 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1606
1607 // Watch for whether or not to keep mobile data always on.
1608 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001609 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001610 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1611
1612 // Watch for whether or not to keep wifi always on.
1613 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001614 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001615 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001616
1617 // Watch for mobile data preferred uids changes.
1618 mSettingsObserver.observe(
1619 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1620 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001621 }
1622
Erik Kline31b4a9e2018-01-11 21:07:29 +09001623 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001624 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1625 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001626 }
1627 }
1628
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001629 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001630 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1631 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001632 return mNextNetworkRequestId++;
1633 }
1634
junyulai74f9a8b2018-06-13 15:00:37 +08001635 @VisibleForTesting
1636 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001637 if (network == null) {
1638 return null;
1639 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001640 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001641 }
1642
1643 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001644 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001645 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001646 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001647 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001648
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001649 // TODO: determine what to do when more than one VPN applies to |uid|.
1650 private NetworkAgentInfo getVpnForUid(int uid) {
1651 synchronized (mNetworkForNetId) {
1652 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1653 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1654 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1655 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001656 }
1657 }
1658 }
1659 return null;
1660 }
1661
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001662 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001663 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001664 final NetworkAgentInfo nai = getVpnForUid(uid);
1665 if (nai != null) return nai.declaredUnderlyingNetworks;
1666 return null;
1667 }
1668
Lorenzo Colittia7574052021-01-19 01:33:05 +09001669 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001670 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001671
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001672 final Network[] networks = getVpnUnderlyingNetworks(uid);
1673 if (networks != null) {
1674 // getUnderlyingNetworks() returns:
1675 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1676 // empty array => the VPN explicitly said "no default network".
1677 // non-empty array => the VPN specified one or more default networks; we use the
1678 // first one.
1679 if (networks.length > 0) {
1680 nai = getNetworkAgentInfoForNetwork(networks[0]);
1681 } else {
1682 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001683 }
1684 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001685 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001686 }
1687
1688 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001689 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001690 */
paulhu7aeba372020-12-30 00:42:19 +08001691 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1692 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001693 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001694 if (ignoreBlocked) {
1695 return false;
1696 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001697 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001698 final long ident = Binder.clearCallingIdentity();
1699 try {
1700 final boolean metered = nc == null ? true : nc.isMetered();
1701 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1702 } finally {
1703 Binder.restoreCallingIdentity(ident);
1704 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001705 }
1706
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001707 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001708 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1709 return;
1710 }
Hugo Benichi47011212017-03-30 10:46:05 +09001711 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001712 synchronized (mBlockedAppUids) {
1713 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001714 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001715 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001716 blocked = false;
1717 } else {
1718 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001719 }
1720 }
Hugo Benichi47011212017-03-30 10:46:05 +09001721 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1722 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1723 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001724 }
1725
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001726 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001727 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1728 return;
1729 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001730 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001731 final int requestId = nri.getActiveRequest() != null
1732 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001733 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001734 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001735 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001736 }
1737
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001738 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001739 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001740 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001741 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001742 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001743 @NonNull
1744 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1745 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001746 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1747 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1748 // but only exists if an app asks about them or requests them. Ensure the requesting app
1749 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001750 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001751 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1752 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1753 null /* extraInfo */);
1754 }
1755 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001756 return filtered;
1757 }
1758
1759 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1760 boolean ignoreBlocked) {
1761 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1762 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001763 }
1764
1765 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001766 * Return NetworkInfo for the active (i.e., connected) network interface.
1767 * It is assumed that at most one network is active at a time. If more
1768 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001769 * @return the info for the active network, or {@code null} if none is
1770 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001771 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001772 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001773 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001774 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001775 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001776 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1777 if (nai == null) return null;
1778 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1779 maybeLogBlockedNetworkInfo(networkInfo, uid);
1780 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001781 }
1782
Paul Jensen1f567382015-02-13 14:18:39 -05001783 @Override
1784 public Network getActiveNetwork() {
1785 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001786 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001787 }
1788
1789 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001790 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001791 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001792 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001793 }
1794
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001795 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001796 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1797 if (vpnNai != null) {
1798 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1799 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1800 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001801 }
Paul Jensen1f567382015-02-13 14:18:39 -05001802 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001803
James Mattis2516da32021-01-31 17:06:19 -08001804 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001805 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1806 ignoreBlocked)) {
1807 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001808 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001809 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001810 }
1811
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001812 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001813 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001814 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001815 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1816 if (nai == null) return null;
1817 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001818 }
1819
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001820 /** Returns a NetworkInfo object for a network that doesn't exist. */
1821 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1822 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1823 getNetworkTypeName(networkType), "" /* subtypeName */);
1824 info.setIsAvailable(true);
1825 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1826 // background data is restricted.
1827 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1828 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1829 ? DetailedState.BLOCKED
1830 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001831 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1832 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001833 return info;
1834 }
1835
Lorenzo Colittia7574052021-01-19 01:33:05 +09001836 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001837 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1838 return null;
1839 }
1840 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001841 if (nai == null) {
1842 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001843 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001844 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1845 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001846 }
1847
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001848 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001849 public NetworkInfo getNetworkInfo(int networkType) {
1850 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001851 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001852 if (getVpnUnderlyingNetworks(uid) != null) {
1853 // A VPN is active, so we may need to return one of its underlying networks. This
1854 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001855 // getNetworkAgentInfoForUid.
1856 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1857 if (nai == null) return null;
1858 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1859 if (networkInfo.getType() == networkType) {
1860 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001861 }
1862 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001863 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001864 }
1865
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001866 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001867 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001868 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001869 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001870 if (nai == null) return null;
1871 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001872 }
1873
1874 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001875 public NetworkInfo[] getAllNetworkInfo() {
1876 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001877 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001878 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1879 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001880 NetworkInfo info = getNetworkInfo(networkType);
1881 if (info != null) {
1882 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001883 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001884 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001885 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001886 }
1887
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001888 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001889 public Network getNetworkForType(int networkType) {
1890 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001891 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1892 return null;
1893 }
1894 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1895 if (nai == null) {
1896 return null;
1897 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001898 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001899 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1900 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001901 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001902 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001903 }
1904
1905 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001906 public Network[] getAllNetworks() {
1907 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001908 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001909 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001910 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001911 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001912 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001913 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001914 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001915 }
1916
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001917 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001918 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001919 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001920 // The basic principle is: if an app's traffic could possibly go over a
1921 // network, without the app doing anything multinetwork-specific,
1922 // (hence, by "default"), then include that network's capabilities in
1923 // the array.
1924 //
1925 // In the normal case, app traffic only goes over the system's default
1926 // network connection, so that's the only network returned.
1927 //
1928 // With a VPN in force, some app traffic may go into the VPN, and thus
1929 // over whatever underlying networks the VPN specifies, while other app
1930 // traffic may go over the system default network (e.g.: a split-tunnel
1931 // VPN, or an app disallowed by the VPN), so the set of networks
1932 // returned includes the VPN's underlying networks and the system
1933 // default.
1934 enforceAccessPermission();
1935
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001936 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001937
James Mattis2516da32021-01-31 17:06:19 -08001938 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1939 if (!nri.isBeingSatisfied()) {
1940 continue;
1941 }
1942 final NetworkAgentInfo nai = nri.getSatisfier();
1943 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1944 if (null != nc
1945 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1946 && !result.containsKey(nai.network)) {
1947 result.put(
1948 nai.network,
1949 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001950 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001951 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1952 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001953 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001954 }
1955
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001956 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001957 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001958 if (null != networks) {
1959 for (final Network network : networks) {
1960 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1961 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001962 result.put(
1963 network,
1964 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001965 nc,
1966 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001967 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001968 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001969 }
1970 }
1971 }
1972
1973 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1974 out = result.values().toArray(out);
1975 return out;
1976 }
1977
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001978 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001979 public boolean isNetworkSupported(int networkType) {
1980 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001981 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001982 }
1983
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001984 /**
1985 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001986 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001987 * @return the ip properties for the active network, or {@code null} if
1988 * none is active
1989 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001990 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001991 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001992 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001993 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001994 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1995 if (nai == null) return null;
1996 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001997 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001998 }
1999
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002000 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002001 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002002 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002003 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002004 final LinkProperties lp = getLinkProperties(nai);
2005 if (lp == null) return null;
2006 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002007 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002008 }
2009
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002010 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002011 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002012 public LinkProperties getLinkProperties(Network network) {
2013 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002014 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2015 if (lp == null) return null;
2016 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002017 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002018 }
2019
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002020 @Nullable
2021 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002022 if (nai == null) {
2023 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002024 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002025 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002026 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002027 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002028 }
2029
Qingxi Lib2748102020-01-08 12:51:49 -08002030 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2031 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2032 }
2033
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002034 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002035 if (nai == null) return null;
2036 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002037 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002038 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002039 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002040 }
2041
2042 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002043 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2044 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002045 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002046 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002047 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002048 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002049 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002050 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002051 }
2052
Qingxi Libb8da982020-01-17 17:54:27 -08002053 @VisibleForTesting
2054 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002055 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002056 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002057 if (!checkSettingsPermission(callerPid, callerUid)) {
2058 newNc.setUids(null);
2059 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002060 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002061 }
Etan Cohen107ae952018-12-30 17:59:59 -08002062 if (newNc.getNetworkSpecifier() != null) {
2063 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2064 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002065 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002066 if (!checkAnyPermissionOf(
2067 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08002068 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002069 }
Qingxi Libb8da982020-01-17 17:54:27 -08002070
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002071 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002072 }
2073
Roshan Pius98f59ec2021-02-23 08:47:39 -08002074 /**
2075 * Wrapper used to cache the permission check results performed for the corresponding
2076 * app. This avoid performing multiple permission checks for different fields in
2077 * NetworkCapabilities.
2078 * Note: This wrapper does not support any sort of invalidation and thus must not be
2079 * persistent or long-lived. It may only be used for the time necessary to
2080 * compute the redactions required by one particular NetworkCallback or
2081 * synchronous call.
2082 */
2083 private class RedactionPermissionChecker {
2084 private final int mCallingPid;
2085 private final int mCallingUid;
2086 @NonNull private final String mCallingPackageName;
2087 @Nullable private final String mCallingAttributionTag;
2088
2089 private Boolean mHasLocationPermission = null;
2090 private Boolean mHasLocalMacAddressPermission = null;
2091 private Boolean mHasSettingsPermission = null;
2092
2093 RedactionPermissionChecker(int callingPid, int callingUid,
2094 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2095 mCallingPid = callingPid;
2096 mCallingUid = callingUid;
2097 mCallingPackageName = callingPackageName;
2098 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002099 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002100
2101 private boolean hasLocationPermissionInternal() {
2102 final long token = Binder.clearCallingIdentity();
2103 try {
2104 return mLocationPermissionChecker.checkLocationPermission(
2105 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2106 null /* message */);
2107 } finally {
2108 Binder.restoreCallingIdentity(token);
2109 }
2110 }
2111
2112 /**
2113 * Returns whether the app holds location permission or not (might return cached result
2114 * if the permission was already checked before).
2115 */
2116 public boolean hasLocationPermission() {
2117 if (mHasLocationPermission == null) {
2118 // If there is no cached result, perform the check now.
2119 mHasLocationPermission = hasLocationPermissionInternal();
2120 }
2121 return mHasLocationPermission;
2122 }
2123
2124 /**
2125 * Returns whether the app holds local mac address permission or not (might return cached
2126 * result if the permission was already checked before).
2127 */
2128 public boolean hasLocalMacAddressPermission() {
2129 if (mHasLocalMacAddressPermission == null) {
2130 // If there is no cached result, perform the check now.
2131 mHasLocalMacAddressPermission =
2132 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2133 }
2134 return mHasLocalMacAddressPermission;
2135 }
2136
2137 /**
2138 * Returns whether the app holds settings permission or not (might return cached
2139 * result if the permission was already checked before).
2140 */
2141 public boolean hasSettingsPermission() {
2142 if (mHasSettingsPermission == null) {
2143 // If there is no cached result, perform the check now.
2144 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2145 }
2146 return mHasSettingsPermission;
2147 }
2148 }
2149
2150 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2151 @NetworkCapabilities.NetCapability long redaction) {
2152 return (redactions & redaction) != 0;
2153 }
2154
2155 /**
2156 * Use the provided |applicableRedactions| to check the receiving app's
2157 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2158 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2159 * before being sent to the corresponding app.
2160 */
2161 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2162 @NetworkCapabilities.RedactionType long applicableRedactions,
2163 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2164 boolean includeLocationSensitiveInfo) {
2165 long redactions = applicableRedactions;
2166 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2167 if (includeLocationSensitiveInfo
2168 && redactionPermissionChecker.hasLocationPermission()) {
2169 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2170 }
2171 }
2172 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2173 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2174 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2175 }
2176 }
2177 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2178 if (redactionPermissionChecker.hasSettingsPermission()) {
2179 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2180 }
2181 }
2182 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002183 }
2184
Qingxi Lib2748102020-01-08 12:51:49 -08002185 @VisibleForTesting
2186 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002187 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002188 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002189 int callingPid, int callingUid, @NonNull String callingPkgName,
2190 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002191 if (nc == null) {
2192 return null;
2193 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002194 // Avoid doing location permission check if the transport info has no location sensitive
2195 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002196 final RedactionPermissionChecker redactionPermissionChecker =
2197 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2198 callingAttributionTag);
2199 final long redactions = retrieveRequiredRedactions(
2200 nc.getApplicableRedactions(), redactionPermissionChecker,
2201 includeLocationSensitiveInfo);
2202 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002203 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002204 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002205 newNc.setOwnerUid(INVALID_UID);
2206 return newNc;
2207 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002208 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2209 if (nc.hasTransport(TRANSPORT_VPN)) {
2210 // Owner UIDs already checked above. No need to re-check.
2211 return newNc;
2212 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002213 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2214 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002215 // compatibility for older apps.
2216 if (!includeLocationSensitiveInfo
2217 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002218 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002219 newNc.setOwnerUid(INVALID_UID);
2220 return newNc;
2221 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002222 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002223 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002224 newNc.setOwnerUid(INVALID_UID);
2225 }
Qingxi Lib2748102020-01-08 12:51:49 -08002226 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002227 }
2228
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002229 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2230 LinkProperties lp, int callerPid, int callerUid) {
2231 if (lp == null) return new LinkProperties();
2232
2233 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2234 final boolean needsSanitization =
2235 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2236 if (!needsSanitization) {
2237 return new LinkProperties(lp);
2238 }
2239
2240 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002241 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002242 }
2243
2244 final LinkProperties newLp = new LinkProperties(lp);
2245 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2246 // object gets parceled.
2247 newLp.setCaptivePortalApiUrl(null);
2248 newLp.setCaptivePortalData(null);
2249 return newLp;
2250 }
2251
Roshan Pius08c94fb2020-01-16 12:17:17 -08002252 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2253 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002254 // There is no need to track the effective UID of the request here. If the caller
2255 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002256 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002257 // Unprivileged apps can only pass in null or their own UID.
2258 if (nc.getUids() == null) {
2259 // If the caller passes in null, the callback will also match networks that do not
2260 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2261 // In this case, redact everything in the request immediately. This ensures that the
2262 // app is not able to get any redacted information by filing an unredacted request
2263 // and observing whether the request matches something.
2264 if (nc.getNetworkSpecifier() != null) {
2265 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2266 }
2267 } else {
2268 nc.setSingleUid(callerUid);
2269 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002270 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002271 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002272 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002273
2274 // Clear owner UID; this can never come from an app.
2275 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002276 }
2277
Chalard Jean38354d12018-03-20 19:13:57 +09002278 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002279 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002280 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2281 }
2282 }
2283
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002284 @Override
2285 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2286 enforceAccessPermission();
2287 final int callerUid = Binder.getCallingUid();
2288 final long token = Binder.clearCallingIdentity();
2289 try {
2290 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2291 } finally {
2292 Binder.restoreCallingIdentity(token);
2293 }
2294 }
2295
junyulaiebd15162021-03-03 12:09:05 +08002296 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002297 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002298 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002299 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002300 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002301
Serik Beketayev05130302021-01-15 16:47:25 -08002302 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002303 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002304 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2305 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002306 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002307 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002308 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002309 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2310 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002311 }
2312 }
2313 return result.toArray(new NetworkState[result.size()]);
2314 }
2315
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002316 @Override
junyulaiebd15162021-03-03 12:09:05 +08002317 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002318 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002319 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002320 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002321
2322 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2323 for (Network network : getAllNetworks()) {
2324 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002325 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002326 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2327 // NetworkCapabilities, which may contain UIDs of apps to which the
2328 // network applies. Should the UIDs be cleared so as not to leak or
2329 // interfere ?
2330 result.add(nai.getNetworkStateSnapshot());
2331 }
2332 }
2333 return result;
2334 }
2335
2336 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002337 public boolean isActiveNetworkMetered() {
2338 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002339
Qingxi Lib2748102020-01-08 12:51:49 -08002340 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002341 if (caps != null) {
2342 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2343 } else {
2344 // Always return the most conservative value
2345 return true;
2346 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002347 }
2348
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002349 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002350 * Ensures that the system cannot call a particular method.
2351 */
2352 private boolean disallowedBecauseSystemCaller() {
2353 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002354 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2355 // for devices launched with Q and above. However, existing devices upgrading to Q and
2356 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002357 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002358 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002359 log("This method exists only for app backwards compatibility"
2360 + " and must not be called by system services.");
2361 return true;
2362 }
2363 return false;
2364 }
2365
paulhub2c28682021-08-18 18:35:54 +08002366 private int getAppUid(final String app, final UserHandle user) {
2367 final PackageManager pm =
2368 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2369 final long token = Binder.clearCallingIdentity();
2370 try {
2371 return pm.getPackageUid(app, 0 /* flags */);
2372 } catch (PackageManager.NameNotFoundException e) {
2373 return -1;
2374 } finally {
2375 Binder.restoreCallingIdentity(token);
2376 }
2377 }
2378
2379 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2380 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2381 if (getAppUid(packageName, user) != callingUid) {
2382 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2383 }
2384 }
2385
Lorenzo Colitti23862912018-09-28 11:31:55 +09002386 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002387 * Ensure that a network route exists to deliver traffic to the specified
2388 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002389 * @param networkType the type of the network over which traffic to the
2390 * specified host is to be routed
2391 * @param hostAddress the IP address of the host to which the route is
2392 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002393 * @return {@code true} on success, {@code false} on failure
2394 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002395 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002396 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2397 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002398 if (disallowedBecauseSystemCaller()) {
2399 return false;
2400 }
paulhub2c28682021-08-18 18:35:54 +08002401 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002402 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002403 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002404 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002405 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002406
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002407 InetAddress addr;
2408 try {
2409 addr = InetAddress.getByAddress(hostAddress);
2410 } catch (UnknownHostException e) {
2411 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2412 return false;
2413 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002414
The Android Open Source Project28527d22009-03-03 19:31:44 -08002415 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002416 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002417 return false;
2418 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002419
2420 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2421 if (nai == null) {
2422 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2423 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2424 } else {
2425 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2426 }
2427 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002428 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002429
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002430 DetailedState netState;
2431 synchronized (nai) {
2432 netState = nai.networkInfo.getDetailedState();
2433 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002434
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002435 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002436 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002437 log("requestRouteToHostAddress on down network "
2438 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002439 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002440 }
2441 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002442 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002443
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002444 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002445 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002446 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002447 LinkProperties lp;
2448 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002449 synchronized (nai) {
2450 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002451 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002452 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002453 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002454 if (DBG) {
2455 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2456 }
Wink Saville32506bc2013-06-29 21:10:57 -07002457 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002458 } finally {
2459 Binder.restoreCallingIdentity(token);
2460 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002461 }
2462
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002463 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002464 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002465 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002466 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002467 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002468 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002469 if (bestRoute.getGateway().equals(addr)) {
2470 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002471 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002472 } else {
2473 // if we will connect to this through another route, add a direct route
2474 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002475 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002476 }
2477 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002478 if (DBG) log("Adding legacy route " + bestRoute +
2479 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002480
2481 final String dst = bestRoute.getDestinationLinkAddress().toString();
2482 final String nextHop = bestRoute.hasGateway()
2483 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002484 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002485 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2486 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002487 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002488 return false;
2489 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002490 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002491 }
2492
paulhu7c0a2e62021-01-08 00:51:49 +08002493 class DnsResolverUnsolicitedEventCallback extends
2494 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002495 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002496 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002497 try {
2498 mHandler.sendMessage(mHandler.obtainMessage(
2499 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002500 new PrivateDnsValidationUpdate(event.netId,
2501 InetAddresses.parseNumericAddress(event.ipAddress),
2502 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002503 } catch (IllegalArgumentException e) {
2504 loge("Error parsing ip address in validation event");
2505 }
2506 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002507
2508 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002509 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2510 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002511 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2512 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2513 // event callback for certain nai. e.g. cellular. Register here to pass to
2514 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002515 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2516 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2517 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002518 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002519 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002520 }
2521 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002522
2523 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002524 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2525 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2526 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002527 }
dalyk1720e542018-03-05 12:42:22 -05002528
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002529 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002530 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002531 return this.VERSION;
2532 }
2533
2534 @Override
2535 public String getInterfaceHash() {
2536 return this.HASH;
2537 }
paulhu7c0a2e62021-01-08 00:51:49 +08002538 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002539
2540 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002541 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2542 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002543
paulhu7c0a2e62021-01-08 00:51:49 +08002544 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002545 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002546 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002547 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002548 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002549 }
2550 }
2551
Sudheer Shanka9967d462021-03-18 19:09:25 +00002552 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002553 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002554 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2556 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002557 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002558 };
2559
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002560 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002561 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002562 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002563 }
2564
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002565 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002566 for (String permission : permissions) {
2567 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002568 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002569 }
2570 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002571 return false;
2572 }
2573
paulhu1a407652019-03-22 16:35:06 +08002574 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2575 for (String permission : permissions) {
2576 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2577 return true;
2578 }
2579 }
2580 return false;
2581 }
2582
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002583 private void enforceAnyPermissionOf(String... permissions) {
2584 if (!checkAnyPermissionOf(permissions)) {
2585 throw new SecurityException("Requires one of the following permissions: "
2586 + String.join(", ", permissions) + ".");
2587 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002588 }
2589
Paul Jensen83f5d572014-08-29 09:54:01 -04002590 private void enforceInternetPermission() {
2591 mContext.enforceCallingOrSelfPermission(
2592 android.Manifest.permission.INTERNET,
2593 "ConnectivityService");
2594 }
2595
The Android Open Source Project28527d22009-03-03 19:31:44 -08002596 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002597 mContext.enforceCallingOrSelfPermission(
2598 android.Manifest.permission.ACCESS_NETWORK_STATE,
2599 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002600 }
2601
paulhua6ee2122021-02-22 15:40:43 +08002602 /**
2603 * Performs a strict and comprehensive check of whether a calling package is allowed to
2604 * change the state of network, as the condition differs for pre-M, M+, and
2605 * privileged/preinstalled apps. The caller is expected to have either the
2606 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2607 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2608 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2609 * permission and cannot be revoked. See http://b/23597341
2610 *
2611 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2612 * of this app will be updated to the current time.
2613 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002614 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002615 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2616 == PackageManager.PERMISSION_GRANTED) {
2617 return;
2618 }
2619
2620 if (callingPkg == null) {
2621 throw new SecurityException("Calling package name is null.");
2622 }
2623
2624 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2625 final int uid = mDeps.getCallingUid();
2626 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2627 callingPkg, callingAttributionTag, null /* message */);
2628
2629 if (mode == AppOpsManager.MODE_ALLOWED) {
2630 return;
2631 }
2632
2633 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2634 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2635 return;
2636 }
2637
2638 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2639 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2640 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002641 }
2642
Charles He9369e612017-05-15 17:07:18 +01002643 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002644 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002645 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002646 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002647 }
2648
paulhu8e96a752019-08-12 16:25:11 +08002649 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002650 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002651 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002652 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002653 }
2654
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002655 private void enforceNetworkFactoryOrSettingsPermission() {
2656 enforceAnyPermissionOf(
2657 android.Manifest.permission.NETWORK_SETTINGS,
2658 android.Manifest.permission.NETWORK_FACTORY,
2659 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2660 }
2661
2662 private void enforceNetworkFactoryOrTestNetworksPermission() {
2663 enforceAnyPermissionOf(
2664 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2665 android.Manifest.permission.NETWORK_FACTORY,
2666 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2667 }
2668
Chalard Jean9a396cc2018-02-21 18:43:54 +09002669 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002670 return checkAnyPermissionOf(
2671 android.Manifest.permission.NETWORK_SETTINGS,
2672 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002673 }
2674
2675 private boolean checkSettingsPermission(int pid, int uid) {
2676 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002677 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2678 || PERMISSION_GRANTED == mContext.checkPermission(
2679 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002680 }
2681
paulhu8e96a752019-08-12 16:25:11 +08002682 private void enforceNetworkStackOrSettingsPermission() {
2683 enforceAnyPermissionOf(
2684 android.Manifest.permission.NETWORK_SETTINGS,
2685 android.Manifest.permission.NETWORK_STACK,
2686 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2687 }
2688
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002689 private void enforceNetworkStackSettingsOrSetup() {
2690 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002691 android.Manifest.permission.NETWORK_SETTINGS,
2692 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002693 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002694 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002695 }
2696
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002697 private void enforceAirplaneModePermission() {
2698 enforceAnyPermissionOf(
2699 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2700 android.Manifest.permission.NETWORK_SETTINGS,
2701 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2702 android.Manifest.permission.NETWORK_STACK,
2703 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2704 }
2705
James Mattis8378aec2021-01-26 14:05:36 -08002706 private void enforceOemNetworkPreferencesPermission() {
2707 mContext.enforceCallingOrSelfPermission(
2708 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2709 "ConnectivityService");
2710 }
2711
James Mattisfa270db2021-05-31 17:11:10 -07002712 private void enforceManageTestNetworksPermission() {
2713 mContext.enforceCallingOrSelfPermission(
2714 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2715 "ConnectivityService");
2716 }
2717
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002718 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002719 return checkAnyPermissionOf(
2720 android.Manifest.permission.NETWORK_STACK,
2721 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002722 }
2723
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002724 private boolean checkNetworkStackPermission(int pid, int uid) {
2725 return checkAnyPermissionOf(pid, uid,
2726 android.Manifest.permission.NETWORK_STACK,
2727 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2728 }
2729
paulhu1a407652019-03-22 16:35:06 +08002730 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2731 return checkAnyPermissionOf(pid, uid,
2732 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002733 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2734 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002735 }
2736
Hugo Benichibd0cc762016-07-19 15:59:27 +09002737 private void enforceConnectivityRestrictedNetworksPermission() {
2738 try {
2739 mContext.enforceCallingOrSelfPermission(
2740 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2741 "ConnectivityService");
2742 return;
2743 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002744 // TODO: Remove this fallback check after all apps have declared
2745 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2746 mContext.enforceCallingOrSelfPermission(
2747 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2748 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002749 }
2750
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002751 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002752 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002753 }
2754
Roshan Pius98f59ec2021-02-23 08:47:39 -08002755 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2756 return PERMISSION_GRANTED == mContext.checkPermission(
2757 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2758 }
2759
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002760 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002761 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002762 }
2763
2764 private void sendInetConditionBroadcast(NetworkInfo info) {
2765 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2766 }
2767
Wink Saville4f0de1e2011-08-04 15:01:58 -07002768 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002769 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002770 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002771 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002772 if (info.isFailover()) {
2773 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2774 info.setFailover(false);
2775 }
2776 if (info.getReason() != null) {
2777 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2778 }
2779 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002780 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2781 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002782 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002783 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002784 return intent;
2785 }
2786
2787 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2788 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2789 }
2790
Chiachang Wang3bc52762021-11-25 14:17:57 +08002791 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2792 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002793 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002794 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002795 if (!mSystemReady
2796 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002797 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002798 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002799 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002800 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002801 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002802 }
2803
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002804 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002805 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002806 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002807 final NetworkInfo ni = intent.getParcelableExtra(
2808 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002809 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2810 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2811 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002812 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002813 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002814 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002815 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002816 } finally {
2817 Binder.restoreCallingIdentity(ident);
2818 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002819 }
2820 }
2821
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002822 /**
Aaron Huang96011892020-06-27 07:18:23 +08002823 * Called by SystemServer through ConnectivityManager when the system is ready.
2824 */
2825 @Override
2826 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002827 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002828 throw new SecurityException("Calling Uid is not system uid.");
2829 }
2830 systemReadyInternal();
2831 }
2832
2833 /**
2834 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002835 */
2836 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002837 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002838 // Load flags after PackageManager is ready to query module version
2839 mFlags.loadFlags(mDeps, mContext);
2840
Aaron Huang9a57acf2020-12-08 10:03:29 +08002841 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2842 // listening network request which is sent by MultipathPolicyTracker won't be added
2843 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2844 // be called after PermissionMonitor#startMonitoring().
2845 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2846 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2847 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002848 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002849 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002850 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002851
Hugo Benichie5220992017-04-26 14:53:28 +09002852 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002853 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002854 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002855 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002856 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002857 }
2858 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002859
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002860 // Create network requests for always-on networks.
2861 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002862
2863 // Update mobile data preference if necessary.
2864 // Note that empty uid list can be skip here only because no uid rules applied before system
2865 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2866 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2867 updateMobileDataPreferredUids();
2868 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002869 }
2870
The Android Open Source Project28527d22009-03-03 19:31:44 -08002871 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002872 * Start listening for default data network activity state changes.
2873 */
2874 @Override
2875 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002876 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002877 }
2878
2879 /**
2880 * Stop listening for default data network activity state changes.
2881 */
2882 @Override
2883 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002884 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002885 }
2886
2887 /**
2888 * Check whether the default network radio is currently active.
2889 */
2890 @Override
2891 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002892 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002893 }
2894
2895 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002896 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002897 * and set it on it's iface.
2898 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002899 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2900 final String iface = newLp.getInterfaceName();
2901 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002902 if (oldLp == null && mtu == 0) {
2903 // Silently ignore unset MTU value.
2904 return;
2905 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002906 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2907 if (VDBG) log("identical MTU - not setting");
2908 return;
2909 }
paulhucbbc3db2019-03-08 16:35:20 +08002910 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002911 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002912 return;
2913 }
sy.yun4aa73922013-09-02 05:24:09 +09002914
w19976e714f1d2014-08-05 15:18:11 -07002915 // Cannot set MTU without interface name
2916 if (TextUtils.isEmpty(iface)) {
2917 loge("Setting MTU size with null iface.");
2918 return;
2919 }
2920
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002921 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002922 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002923 mNetd.interfaceSetMtu(iface, mtu);
2924 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002925 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002926 }
2927 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002928
Chenbo Feng15416292018-11-08 17:36:21 -08002929 @VisibleForTesting
2930 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002931
lucaslin821c9782018-11-28 19:27:52 +08002932 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002933 String[] values = null;
2934 if (tcpBufferSizes != null) {
2935 values = tcpBufferSizes.split(",");
2936 }
2937
2938 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002939 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002940 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2941 values = tcpBufferSizes.split(",");
2942 }
2943
2944 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2945
2946 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002947 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002948
Chenbo Feng15416292018-11-08 17:36:21 -08002949 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2950 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2951 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002952 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002953 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002954 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002955 }
2956 }
2957
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002958 @Override
2959 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002960 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002961 NETWORK_RESTORE_DELAY_PROP_NAME);
2962 if(restoreDefaultNetworkDelayStr != null &&
2963 restoreDefaultNetworkDelayStr.length() != 0) {
2964 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002965 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002966 } catch (NumberFormatException e) {
2967 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002968 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002969 // if the system property isn't set, use the value for the apn type
2970 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2971
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002972 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2973 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002974 }
2975 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002976 }
2977
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002978 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2979 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2980 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002981 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002982 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002983 // Start gathering diagnostic information.
2984 netDiags.add(new NetworkDiagnostics(
2985 nai.network,
2986 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002987 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002988 DIAG_TIME_MS));
2989 }
2990
2991 for (NetworkDiagnostics netDiag : netDiags) {
2992 pw.println();
2993 netDiag.waitForMeasurements();
2994 netDiag.dump(pw);
2995 }
2996 }
2997
The Android Open Source Project28527d22009-03-03 19:31:44 -08002998 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09002999 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3000 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003001 if (!checkDumpPermission(mContext, TAG, writer)) return;
3002
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003003 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003004 }
3005
lucaslin99473f62020-12-10 15:10:54 +08003006 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3007 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3008 != PackageManager.PERMISSION_GRANTED) {
3009 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003010 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003011 + " due to missing android.permission.DUMP permission");
3012 return false;
3013 } else {
3014 return true;
3015 }
3016 }
3017
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003018 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003019 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003020
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003021 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003022 dumpNetworkDiagnostics(pw);
3023 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003024 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003025 dumpNetworks(pw);
3026 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003027 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003028 dumpNetworkRequests(pw);
3029 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003030 }
Erik Kline9647f382015-06-05 17:47:34 +09003031
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003032 pw.print("NetworkProviders for:");
3033 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3034 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003035 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003036 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003037 pw.println();
3038
Chalard Jean5b409c72021-02-04 13:12:59 +09003039 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003040 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003041 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003042 pw.println("none");
3043 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003044 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003045 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003046 pw.println();
3047
James Mattis8b298a02021-06-01 22:34:04 -07003048 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003049 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003050 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003051 pw.decreaseIndent();
3052 pw.println();
3053
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003054 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003055 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003056 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003057 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003058 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003059
junyulaif2c67e42018-08-07 19:50:45 +08003060 pw.println("Status for known UIDs:");
3061 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003062 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003063 for (int i = 0; i < size; i++) {
3064 // Don't crash if the array is modified while dumping in bugreports.
3065 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003066 final int uid = mUidBlockedReasons.keyAt(i);
3067 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3068 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003069 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003070 } catch (ArrayIndexOutOfBoundsException e) {
3071 pw.println(" ArrayIndexOutOfBoundsException");
3072 } catch (ConcurrentModificationException e) {
3073 pw.println(" ConcurrentModificationException");
3074 }
3075 }
3076 pw.println();
3077 pw.decreaseIndent();
3078
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003079 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003080 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003081 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003082 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003083 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003084
Robert Greenwalt94e22142014-07-30 16:31:24 -07003085 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003086
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003087 pw.println();
markchien5e866652019-09-30 14:40:57 +08003088 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003089
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003090 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003091 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003092
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003093 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003094
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003095 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003096 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003097 pw.println("mNetworkRequestInfoLogs (most recent first):");
3098 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003099 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003100 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003101
3102 pw.println();
3103 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3104 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003105 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003106 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003107
3108 pw.println();
3109 pw.println("NetTransition WakeLock activity (most recent first):");
3110 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003111 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3112 pw.println("total releases: " + mTotalWakelockReleases);
3113 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3114 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3115 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3116 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3117 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3118 }
James Mattiscb1e0362021-04-06 17:07:42 -07003119 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003120
3121 pw.println();
3122 pw.println("bandwidth update requests (by uid):");
3123 pw.increaseIndent();
3124 synchronized (mBandwidthRequests) {
3125 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3126 pw.println("[" + mBandwidthRequests.keyAt(i)
3127 + "]: " + mBandwidthRequests.valueAt(i));
3128 }
3129 }
3130 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003131 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003132
James Mattiscb1e0362021-04-06 17:07:42 -07003133 pw.println();
3134 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3135 pw.increaseIndent();
3136 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003137 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003138 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003139
3140 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003141
3142 pw.println();
3143 pw.println("Permission Monitor:");
3144 pw.increaseIndent();
3145 mPermissionMonitor.dump(pw);
3146 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003147
3148 pw.println();
3149 pw.println("Legacy network activity:");
3150 pw.increaseIndent();
3151 mNetworkActivityTracker.dump(pw);
3152 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003153 }
3154
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003155 private void dumpNetworks(IndentingPrintWriter pw) {
3156 for (NetworkAgentInfo nai : networksSortedById()) {
3157 pw.println(nai.toString());
3158 pw.increaseIndent();
3159 pw.println(String.format(
3160 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3161 nai.numForegroundNetworkRequests(),
3162 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3163 nai.numBackgroundNetworkRequests(),
3164 nai.numNetworkRequests()));
3165 pw.increaseIndent();
3166 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3167 pw.println(nai.requestAt(i).toString());
3168 }
3169 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003170 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003171 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003172 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003173 pw.decreaseIndent();
3174 pw.decreaseIndent();
3175 }
3176 }
3177
James Mattis8b298a02021-06-01 22:34:04 -07003178 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3179 if (!mProfileNetworkPreferences.isEmpty()) {
3180 pw.println("Profile preferences:");
3181 pw.increaseIndent();
3182 pw.println(mProfileNetworkPreferences.preferences);
3183 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003184 }
James Mattis8b298a02021-06-01 22:34:04 -07003185 if (!mOemNetworkPreferences.isEmpty()) {
3186 pw.println("OEM preferences:");
3187 pw.increaseIndent();
3188 pw.println(mOemNetworkPreferences);
3189 pw.decreaseIndent();
3190 }
3191 if (!mMobileDataPreferredUids.isEmpty()) {
3192 pw.println("Mobile data preferred UIDs:");
3193 pw.increaseIndent();
3194 pw.println(mMobileDataPreferredUids);
3195 pw.decreaseIndent();
3196 }
James Mattis45d81842021-01-10 14:24:24 -08003197
James Mattis8b298a02021-06-01 22:34:04 -07003198 pw.println("Default requests:");
3199 pw.increaseIndent();
3200 dumpPerAppDefaultRequests(pw);
3201 pw.decreaseIndent();
3202 }
3203
3204 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003205 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3206 if (mDefaultRequest == defaultRequest) {
3207 continue;
3208 }
3209
James Mattis8b298a02021-06-01 22:34:04 -07003210 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3211 final String networkOutput;
3212 if (null == satisfier) {
3213 networkOutput = "null";
3214 } else if (mNoServiceNetwork.equals(satisfier)) {
3215 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003216 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003217 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003218 }
James Mattis8b298a02021-06-01 22:34:04 -07003219 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3220 ? "" : " asUid: " + defaultRequest.mAsUid;
3221 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3222 + defaultRequest.mPid + asUidString + "]";
3223 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3224 + " Preference order: " + defaultRequest.mPreferenceOrder
3225 + " Tracked UIDs: " + defaultRequest.getUids();
3226 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003227 }
3228 }
3229
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003230 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003231 NetworkRequestInfo[] infos = null;
3232 while (infos == null) {
3233 try {
3234 infos = requestsSortedById();
3235 } catch (ConcurrentModificationException e) {
3236 // mNetworkRequests should only be accessed from handler thread, except dump().
3237 // As dump() is never called in normal usage, it would be needlessly expensive
3238 // to lock the collection only for its benefit. Instead, retry getting the
3239 // requests if ConcurrentModificationException is thrown during dump().
3240 }
3241 }
3242 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003243 pw.println(nri.toString());
3244 }
3245 }
3246
Chalard Jean524f0b12021-10-25 21:11:56 +09003247 private void dumpAllRequestInfoLogsToLogcat() {
3248 try (PrintWriter logPw = new PrintWriter(new Writer() {
3249 @Override
3250 public void write(final char[] cbuf, final int off, final int len) {
3251 // This method is called with 0-length and 1-length arrays for empty strings
3252 // or strings containing only the DEL character.
3253 if (len <= 1) return;
3254 Log.e(TAG, new String(cbuf, off, len));
3255 }
3256 @Override public void flush() {}
3257 @Override public void close() {}
3258 })) {
3259 mNetworkRequestInfoLogs.dump(logPw);
3260 }
3261 }
3262
Hugo Benichia480ba52018-09-03 08:19:02 +09003263 /**
3264 * Return an array of all current NetworkAgentInfos sorted by network id.
3265 */
3266 private NetworkAgentInfo[] networksSortedById() {
3267 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003268 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003269 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003270 return networks;
3271 }
3272
3273 /**
3274 * Return an array of all current NetworkRequest sorted by request id.
3275 */
James Mattis258ea3c2020-11-15 15:04:40 -08003276 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003277 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003278 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003279 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003280 // Sort the array based off the NRI containing the min requestId in its requests.
3281 Arrays.sort(requests,
3282 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3283 Comparator.comparingInt(req -> req.requestId)).requestId
3284 )
3285 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003286 return requests;
3287 }
3288
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003289 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003290 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003291 if (officialNai != null && officialNai.equals(nai)) return true;
3292 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003293 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003294 " - " + nai);
3295 }
3296 return false;
3297 }
3298
Robert Greenwalt2034b912009-08-12 16:08:25 -07003299 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003300 private class NetworkStateTrackerHandler extends Handler {
3301 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003302 super(looper);
3303 }
3304
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003305 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003306 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3307 final NetworkAgentInfo nai = arg.first;
3308 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003309 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003310 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003311 }
3312 return;
3313 }
3314
3315 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003316 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003317 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003318 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003319 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003320 }
Chalard Jean5b639762020-03-09 21:25:37 +09003321 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3322 // Make sure the original object is not mutated. NetworkAgent normally
3323 // makes a copy of the capabilities when sending the message through
3324 // the Messenger, but if this ever changes, not making a defensive copy
3325 // here will give attack vectors to clients using this code path.
3326 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08003327 networkCapabilities.restrictCapabilitiesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003328 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003329 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003330 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003331 break;
3332 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003333 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003334 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003335 processLinkPropertiesFromAgent(nai, newLp);
3336 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003337 break;
3338 }
3339 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003340 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003341 updateNetworkInfo(nai, info);
3342 break;
3343 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003344 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003345 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003346 break;
3347 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003348 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003349 if (nai.everConnected) {
3350 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003351 // Note that if the NAI had been connected, this would affect the
3352 // score, and therefore would require re-mixing the score and performing
3353 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003354 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003355 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3356 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003357 // Mark the network as temporarily accepting partial connectivity so that it
3358 // will be validated (and possibly become default) even if it only provides
3359 // partial internet access. Note that if user connects to partial connectivity
3360 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3361 // out of wifi coverage) and if the same wifi is available again, the device
3362 // will auto connect to this wifi even though the wifi has "no internet".
3363 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003364 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003365 break;
3366 }
junyulai011b1f12019-01-03 18:50:15 +08003367 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003368 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003369 break;
3370 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003371 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003372 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003373 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003374
3375 if (isLegacyLockdownNai(nai)
3376 && (underlying == null || underlying.size() != 1)) {
3377 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3378 + " must have exactly one underlying network: " + underlying);
3379 }
3380
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003381 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3382 nai.declaredUnderlyingNetworks = (underlying != null)
3383 ? underlying.toArray(new Network[0]) : null;
3384
3385 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3386 if (DBG) {
3387 log(nai.toShortString() + " changed underlying networks to "
3388 + Arrays.toString(nai.declaredUnderlyingNetworks));
3389 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003390 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003391 notifyIfacesChangedForNetworkStats();
3392 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003393 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003394 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003395 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3396 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3397 nai.teardownDelayMs = msg.arg1;
3398 } else {
3399 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3400 }
Chalard Jean550b5212021-03-05 23:07:53 +09003401 break;
3402 }
3403 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3404 nai.setLingerDuration((int) arg.second);
3405 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003406 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003407 }
3408 }
3409
3410 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3411 switch (msg.what) {
3412 default:
3413 return false;
lucasline117e2e2019-10-22 18:27:33 +08003414 case EVENT_PROBE_STATUS_CHANGED: {
3415 final Integer netId = (Integer) msg.obj;
3416 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3417 if (nai == null) {
3418 break;
3419 }
3420 final boolean probePrivateDnsCompleted =
3421 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3422 final boolean privateDnsBroken =
3423 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3424 if (probePrivateDnsCompleted) {
3425 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3426 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003427 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003428 }
3429 // Only show the notification when the private DNS is broken and the
3430 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003431 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003432 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3433 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003434 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003435 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3436 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3437 // private DNS is broken, it means this network is being reevaluated.
3438 // Either probing private DNS is not necessary any more or it hasn't been
3439 // done yet. In either case, the networkCapabilities should be updated to
3440 // reflect the new status.
3441 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003442 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003443 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003444 }
3445 break;
3446 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003447 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003448 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3449
3450 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003451 if (nai == null) break;
3452
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003453 handleNetworkTested(nai, results.mTestResult,
3454 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003455 break;
3456 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003457 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003458 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003459 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003460 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003461 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003462 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3463 nai.lastCaptivePortalDetected = visible;
3464 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003465 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003466 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3467 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003468 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003469 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003470 teardownUnneededNetwork(nai);
3471 break;
3472 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003473 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003474 }
3475 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003476 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003477 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003478 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3479 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003480 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003481 if (nai == null) {
3482 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3483 break;
3484 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003485 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003486 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003487 (PendingIntent) msg.obj,
3488 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003489 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003490 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003491 break;
3492 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003493 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003494 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003495 if (nai == null) break;
3496
Erik Kline9a62f012018-03-21 07:18:33 -07003497 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003498 break;
3499 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003500 case EVENT_CAPPORT_DATA_CHANGED: {
3501 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3502 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003503 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003504 break;
3505 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003506 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003507 return true;
3508 }
3509
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003510 private void handleNetworkTested(
3511 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3512 final boolean wasPartial = nai.partialConnectivity;
3513 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3514 final boolean partialConnectivityChanged =
3515 (wasPartial != nai.partialConnectivity);
3516
3517 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3518 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003519 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003520
3521 if (DBG) {
3522 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3523 ? " with redirect to " + redirectUrl
3524 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003525 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003526 }
3527 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003528 final int oldScore = nai.getCurrentScore();
3529 nai.lastValidated = valid;
3530 nai.everValidated |= valid;
3531 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003532 if (valid) {
3533 handleFreshlyValidatedNetwork(nai);
3534 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3535 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003536 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003537 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003538 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003539 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003540 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003541 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003542 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003543 NotificationType.PRIVATE_DNS_BROKEN);
3544 // If network becomes valid, the hasShownBroken should be reset for
3545 // that network so that the notification will be fired when the private
3546 // DNS is broken again.
3547 nai.networkAgentConfig.hasShownBroken = false;
3548 }
3549 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003550 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003551 }
3552 updateInetCondition(nai);
3553 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003554 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003555 nai.onValidationStatusChanged(
3556 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3557 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003558
3559 // If NetworkMonitor detects partial connectivity before
3560 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3561 // immediately. Re-notify partial connectivity silently if no internet
3562 // notification already there.
3563 if (!wasPartial && nai.partialConnectivity) {
3564 // Remove delayed message if there is a pending message.
3565 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3566 handlePromptUnvalidated(nai.network);
3567 }
3568
3569 if (wasValidated && !nai.lastValidated) {
3570 handleNetworkUnvalidated(nai);
3571 }
3572 }
3573
Calvin Ondada1452016-10-11 15:10:46 -07003574 private int getCaptivePortalMode() {
3575 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003576 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3577 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003578 }
3579
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003580 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3581 switch (msg.what) {
3582 default:
3583 return false;
3584 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3585 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3586 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3587 handleLingerComplete(nai);
3588 }
3589 break;
3590 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003591 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3592 handleNetworkAgentRegistered(msg);
3593 break;
3594 }
3595 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3596 handleNetworkAgentDisconnected(msg);
3597 break;
3598 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003599 }
3600 return true;
3601 }
3602
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003603 @Override
3604 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003605 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003606 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003607 maybeHandleNetworkAgentMessage(msg);
3608 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003609 }
3610 }
3611
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003612 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003613 private final int mNetId;
3614 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003615
3616 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003617 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003618 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003619 }
3620
3621 @Override
3622 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3623 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003624 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003625 }
3626
3627 @Override
3628 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003629 // Legacy version of notifyNetworkTestedWithExtras.
3630 // Would only be called if the system has a NetworkStack module older than the
3631 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003632 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003633 }
3634
3635 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003636 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003637 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3638 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003639 final Message msg = mTrackerHandler.obtainMessage(
3640 EVENT_NETWORK_TESTED,
3641 new NetworkTestedResults(
3642 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003643 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003644
3645 // Invoke ConnectivityReport generation for this Network test event.
3646 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3647 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003648
Cody Kestingf1120be2020-08-03 18:01:40 -07003649 // NetworkMonitor reports the network validation result as a bitmask while
3650 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3651 // logical value for ConnectivityDiagnostics.
3652 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3653 p.result);
3654
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003655 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003656 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003657 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3658 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3659
Aaron Huang959d3642021-01-21 15:47:41 +08003660 ConnectivityReportEvent reportEvent =
3661 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3662 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3663 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003664 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003665 }
3666
3667 @Override
3668 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3669 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3670 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003671 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003672 }
3673
3674 @Override
lucasline117e2e2019-10-22 18:27:33 +08003675 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3676 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3677 EVENT_PROBE_STATUS_CHANGED,
3678 probesCompleted, probesSucceeded, new Integer(mNetId)));
3679 }
3680
3681 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003682 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3683 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3684 EVENT_CAPPORT_DATA_CHANGED,
3685 0, mNetId, data));
3686 }
3687
3688 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003689 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003690 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003691 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003692
3693 final PendingIntent pendingIntent;
3694 // Only the system server can register notifications with package "android"
3695 final long token = Binder.clearCallingIdentity();
3696 try {
paulhu7746e4e2020-06-09 19:07:03 +08003697 pendingIntent = PendingIntent.getBroadcast(
3698 mContext,
3699 0 /* requestCode */,
3700 intent,
3701 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003702 } finally {
3703 Binder.restoreCallingIdentity(token);
3704 }
3705 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3706 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003707 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003708 }
3709
3710 @Override
3711 public void hideProvisioningNotification() {
3712 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003713 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003714 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003715
3716 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003717 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003718 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003719 }
3720
3721 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003722 public int getInterfaceVersion() {
3723 return this.VERSION;
3724 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003725
3726 @Override
3727 public String getInterfaceHash() {
3728 return this.HASH;
3729 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003730 }
3731
Cody Kestingf1120be2020-08-03 18:01:40 -07003732 /**
3733 * Converts the given NetworkMonitor-specific validation result bitmask to a
3734 * ConnectivityDiagnostics-specific validation result int.
3735 */
3736 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3737 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3738 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3739 }
3740 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3741 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3742 }
3743 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3744 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3745 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3746 }
3747
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003748 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003749 log("Data stall detected with methods: " + p.detectionMethod);
3750
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003751 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003752 int detectionMethod = 0;
3753 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3754 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3755 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3756 }
3757 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3758 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3759 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3760 p.tcpMetricsCollectionPeriodMillis);
3761 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003762 }
3763
Cody Kestingf53a0752020-04-15 12:33:28 -07003764 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003765 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003766 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003767
3768 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3769 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3770 // the cost of going through two handlers.
3771 mConnectivityDiagnosticsHandler.sendMessage(msg);
3772 }
3773
Cody Kestingb37958e2020-05-15 10:36:01 -07003774 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3775 return (p.detectionMethod & detectionMethod) != 0;
3776 }
3777
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003778 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3779 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003780 }
3781
Erik Klinea73af002018-06-26 18:53:43 +09003782 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3783 if (nai == null) return;
3784 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3785 // in order to restart a validation pass from within netd.
3786 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3787 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003788 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003789 }
3790 }
3791
Erik Kline31b4a9e2018-01-11 21:07:29 +09003792 private void handlePrivateDnsSettingsChanged() {
3793 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3794
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003795 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003796 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003797 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003798 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3799 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003800 }
3801 }
3802
Erik Kline9a62f012018-03-21 07:18:33 -07003803 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3804 // Private DNS only ever applies to networks that might provide
3805 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003806 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003807
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003808 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003809 // schedule DNS resolutions. If a DNS resolution is required the
3810 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003811 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003812
3813 // With Private DNS bypass support, we can proceed to update the
3814 // Private DNS config immediately, even if we're in strict mode
3815 // and have not yet resolved the provider name into a set of IPs.
3816 updatePrivateDns(nai, cfg);
3817 }
3818
3819 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3820 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003821 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003822 }
3823
dalyk1720e542018-03-05 12:42:22 -05003824 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3825 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3826 if (nai == null) {
3827 return;
3828 }
3829 mDnsManager.updatePrivateDnsValidation(update);
3830 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3831 }
3832
paulhu7c0a2e62021-01-08 00:51:49 +08003833 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003834 int prefixLength) {
3835 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3836 if (nai == null) return;
3837
paulhu7c0a2e62021-01-08 00:51:49 +08003838 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3839 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003840
3841 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003842 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003843 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003844 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003845 prefixLength);
3846 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003847 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003848 return;
3849 }
3850 }
3851
Lorenzo Colittid523d142020-04-01 20:16:30 +09003852 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003853 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3854 }
3855
Hai Shalome58bdc62021-01-11 18:45:34 -08003856 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003857 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003858 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003859 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3860 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3861 }
3862
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003863 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003864 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003865 * @param nai the agent info to update
3866 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003867 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003868 */
junyulai2b6f0c22021-02-03 20:15:30 +08003869 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3870 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3871 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003872 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003873 // one lingered request, set inactive.
3874 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003875 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003876 if (DBG) log("Unsetting inactive " + nai.toShortString());
3877 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003878 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003879 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003880 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003881 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3882 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003883 }
junyulai2b6f0c22021-02-03 20:15:30 +08003884 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003885 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003886 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003887 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003888 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003889 }
3890
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003891 private void handleNetworkAgentRegistered(Message msg) {
3892 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3893 if (!mNetworkAgentInfos.contains(nai)) {
3894 return;
3895 }
3896
3897 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3898 if (VDBG) log("NetworkAgent registered");
3899 } else {
3900 loge("Error connecting NetworkAgent");
3901 mNetworkAgentInfos.remove(nai);
3902 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003903 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003904 synchronized (mNetworkForNetId) {
3905 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003906 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003907 mNetIdManager.releaseNetId(nai.network.getNetId());
3908 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003909 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003910 }
3911 }
3912 }
Paul Jensend5f53392014-11-25 15:26:53 -05003913
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003914 private void handleNetworkAgentDisconnected(Message msg) {
3915 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003916 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003917 }
3918
Chalard Jeand9fffc32018-05-11 20:19:20 +09003919 // Destroys a network, remove references to it from the internal state managed by
3920 // ConnectivityService, free its interfaces and clean up.
3921 // Must be called on the Handler thread.
3922 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003923 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003924
3925 if (!mNetworkAgentInfos.contains(nai)) return;
3926
Chalard Jeand9fffc32018-05-11 20:19:20 +09003927 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003928 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003929 }
lucaslinb25c9a62019-02-12 15:30:13 +08003930 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003931 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003932 // A network agent has disconnected.
3933 // TODO - if we move the logic to the network agent (have them disconnect
3934 // because they lost all their requests or because their score isn't good)
3935 // then they would disconnect organically, report their new state and then
3936 // disconnect the channel.
3937 if (nai.networkInfo.isConnected()) {
3938 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3939 null, null);
3940 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003941 final boolean wasDefault = isDefaultNetwork(nai);
3942 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003943 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003944 }
3945 notifyIfacesChangedForNetworkStats();
3946 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3947 // by other networks that are already connected. Perhaps that can be done by
3948 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3949 // of rematchAllNetworksAndRequests
3950 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003951 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003952
3953 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003954 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3955 // Disable wakeup packet monitoring for each interface.
3956 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3957 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003958 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003959 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003960 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003961 synchronized (mNetworkForNetId) {
3962 // Remove the NetworkAgent, but don't mark the netId as
3963 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003964 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003965 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003966 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003967 // Remove all previously satisfied requests.
3968 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003969 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09003970 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08003971 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08003972 if (currentNetwork != null
3973 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003974 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09003975 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3976 // rematch not to keep disconnected agents instead of setting it here ; this
3977 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08003978 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09003979 for (final NetworkOfferInfo noi : mNetworkOffers) {
3980 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08003981 }
James Mattise3ef1912020-12-20 11:09:58 -08003982
Chalard Jean5b409c72021-02-04 13:12:59 +09003983 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08003984 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09003985 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08003986 // network, because while incorrect this is the closest to the old (also
3987 // incorrect) behavior.
3988 mNetworkActivityTracker.updateDataActivityTracking(
3989 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08003990 ensureNetworkTransitionWakelock(nai.toShortString());
3991 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09003992 }
3993 }
junyulai2b6f0c22021-02-03 20:15:30 +08003994 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08003995 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09003996 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08003997 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09003998 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09003999 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004000 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004001
4002 // Immediate teardown.
4003 if (nai.teardownDelayMs == 0) {
4004 destroyNetwork(nai);
4005 return;
4006 }
4007
4008 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304009 if (nai.created) {
4010 try {
4011 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4012 } catch (RemoteException e) {
4013 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4014 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004015 }
4016 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4017 }
4018
4019 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004020 if (nai.created) {
4021 // Tell netd to clean up the configuration for this network
4022 // (routing rules, DNS, etc).
4023 // This may be slow as it requires a lot of netd shelling out to ip and
4024 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004025 // after we've rematched networks with requests (which might change the default
4026 // network or service a new request from an app), so network traffic isn't interrupted
4027 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004028 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004029 mDnsManager.removeNetwork(nai.network);
4030 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004031 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004032 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004033 }
4034
Ken Chen6df7a902021-04-09 15:08:42 +08004035 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004036 try {
4037 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004038 final NativeNetworkConfig config;
4039 if (nai.isVPN()) {
4040 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004041 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004042 return false;
4043 }
4044 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4045 INetd.PERMISSION_NONE,
4046 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004047 getVpnType(nai), /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004048 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004049 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4050 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004051 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004052 }
Ken Chen6df7a902021-04-09 15:08:42 +08004053 mNetd.networkCreate(config);
4054 mDnsResolver.createNetworkCache(nai.network.getNetId());
4055 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4056 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004057 return true;
4058 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004059 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004060 return false;
4061 }
4062 }
4063
Ken Chen6df7a902021-04-09 15:08:42 +08004064 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004065 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004066 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004067 } catch (RemoteException | ServiceSpecificException e) {
4068 loge("Exception destroying network(networkDestroy): " + e);
4069 }
4070 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004071 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004072 } catch (RemoteException | ServiceSpecificException e) {
4073 loge("Exception destroying network: " + e);
4074 }
4075 }
4076
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004077 // If this method proves to be too slow then we can maintain a separate
4078 // pendingIntent => NetworkRequestInfo map.
4079 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4080 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004081 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4082 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4083 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004084 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004085 return entry.getValue();
4086 }
4087 }
4088 return null;
4089 }
4090
Chalard Jean524f0b12021-10-25 21:11:56 +09004091 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4092 if (SdkLevel.isAtLeastT()) {
4093 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4094 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4095 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4096 // bug is fixed.
4097 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004098 throw new IllegalStateException("This NRI is already registered. New : " + nri
4099 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004100 }
4101 }
4102 }
4103 }
4104
James Mattisf7027322020-12-13 16:28:14 -08004105 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004106 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004107 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4108 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4109 final NetworkRequestInfo existingRequest =
4110 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004111 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004112 if (DBG) {
4113 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4114 + nri.mRequests.get(0) + " because their intents matched.");
4115 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004116 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004117 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004118 }
Erik Kline05f2b402015-04-30 12:58:40 +09004119 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004120 }
4121
James Mattisf7027322020-12-13 16:28:14 -08004122 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004123 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004124 }
4125
James Mattis3ce3d3c2021-02-09 18:18:28 -08004126 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004127 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004128 for (final NetworkRequestInfo nri : nris) {
4129 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004130 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004131 for (final NetworkRequest req : nri.mRequests) {
4132 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004133 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004134 if (req.isListen()) {
4135 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4136 if (req.networkCapabilities.hasSignalStrength()
4137 && network.satisfiesImmutableCapabilitiesOf(req)) {
4138 updateSignalStrengthThresholds(network, "REGISTER", req);
4139 }
James Mattisf7027322020-12-13 16:28:14 -08004140 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004141 }
4142 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004143 // If this NRI has a satisfier already, it is replacing an older request that
4144 // has been removed. Track it.
4145 final NetworkRequest activeRequest = nri.getActiveRequest();
4146 if (null != activeRequest) {
4147 // If there is an active request, then for sure there is a satisfier.
4148 nri.getSatisfier().addRequest(activeRequest);
4149 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004150 }
James Mattisf7027322020-12-13 16:28:14 -08004151
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004152 if (mFlags.noRematchAllRequestsOnRegister()) {
4153 rematchNetworksAndRequests(nris);
4154 } else {
4155 rematchAllNetworksAndRequests();
4156 }
James Mattis45d81842021-01-10 14:24:24 -08004157
Chalard Jean0354d8c2021-01-12 10:58:56 +09004158 // Requests that have not been matched to a network will not have been sent to the
4159 // providers, because the old satisfier and the new satisfier are the same (null in this
4160 // case). Send these requests to the providers.
4161 for (final NetworkRequestInfo nri : nris) {
4162 for (final NetworkOfferInfo noi : mNetworkOffers) {
4163 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004164 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004165 }
4166 }
4167
James Mattisf7027322020-12-13 16:28:14 -08004168 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4169 final int callingUid) {
4170 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004171 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004172 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4173 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4174 handleReleaseNetworkRequest(
4175 nri.mRequests.get(0),
4176 callingUid,
4177 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004178 }
4179 }
4180
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004181 // Determines whether the network is the best (or could become the best, if it validated), for
4182 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4183 // on the value of reason:
4184 //
4185 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4186 // then it should be torn down.
4187 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4188 // then it should be lingered.
4189 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004190 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004191
4192 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4193 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4194 return false;
4195 }
4196
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004197 final int numRequests;
4198 switch (reason) {
4199 case TEARDOWN:
4200 numRequests = nai.numRequestNetworkRequests();
4201 break;
4202 case LINGER:
4203 numRequests = nai.numForegroundNetworkRequests();
4204 break;
4205 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004206 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004207 return true;
4208 }
4209
Chalard Jean947acd42021-03-08 22:29:27 +09004210 if (numRequests > 0) return false;
4211
Paul Jensende49eb12015-06-25 15:30:08 -04004212 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004213 if (reason == UnneededFor.LINGER
4214 && !nri.isMultilayerRequest()
4215 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004216 // Background requests don't affect lingering.
4217 continue;
4218 }
4219
James Mattis3d229892020-11-16 16:46:28 -08004220 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004221 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004222 }
4223 }
Paul Jensende49eb12015-06-25 15:30:08 -04004224 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004225 }
4226
James Mattis3d229892020-11-16 16:46:28 -08004227 private boolean isNetworkPotentialSatisfier(
4228 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4229 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004230 // request, return immediately. For multilayer requests, check to see if any of the
4231 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004232 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4233 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004234 return false;
4235 }
4236 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004237 // This multilayer listen request is satisfied therefore no further requests need to be
4238 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004239 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004240 return false;
4241 }
James Mattis3d229892020-11-16 16:46:28 -08004242 // As non-multilayer listen requests have already returned, the below would only happen
4243 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004244 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004245 continue;
4246 }
4247 // If this Network is already the highest scoring Network for a request, or if
4248 // there is hope for it to become one if it validated, then it is needed.
4249 if (candidate.satisfies(req)) {
4250 // As soon as a network is found that satisfies a request, return. Specifically for
4251 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4252 // is important so as to not evaluate lower priority requests further in
4253 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004254 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4255 ? nri.getSatisfier() : null;
4256 // Note that this catches two important cases:
4257 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4258 // is currently satisfying the request. This is desirable when
4259 // cellular ends up validating but WiFi does not.
4260 // 2. Unvalidated WiFi will not be reaped when validated cellular
4261 // is currently satisfying the request. This is desirable when
4262 // WiFi ends up validating and out scoring cellular.
4263 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004264 }
4265 }
4266
4267 return false;
4268 }
4269
Erik Kline0c04b742016-07-07 16:50:58 +09004270 private NetworkRequestInfo getNriForAppRequest(
4271 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004272 // Looking up the app passed param request in mRequests isn't possible since it may return
4273 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4274 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004275 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4276 // to avoid potential race conditions when validating a package->uid mapping when sending
4277 // the callback on the very low-chance that an application shuts down prior to the callback
4278 // being sent.
4279 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4280 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004281
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004282 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004283 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004284 log(String.format("UID %d attempted to %s for unowned request %s",
4285 callingUid, requestedOperation, nri));
4286 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004287 }
Erik Kline0c04b742016-07-07 16:50:58 +09004288 }
4289
4290 return nri;
4291 }
4292
James Mattisf7027322020-12-13 16:28:14 -08004293 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4294 final String callingMethod) {
4295 if (nri.isMultilayerRequest()) {
4296 throw new IllegalStateException(
4297 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004298 }
4299 }
4300
James Mattisf7027322020-12-13 16:28:14 -08004301 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004302 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004303 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4304 // single NetworkRequest and thus does not apply to multilayer requests.
4305 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4306 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004307 return;
4308 }
James Mattis2516da32021-01-31 17:06:19 -08004309 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004310 return;
4311 }
James Mattisf7027322020-12-13 16:28:14 -08004312 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4313 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004314 }
4315 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004316 callCallbackForRequest(
4317 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004318 }
4319
James Mattisf7027322020-12-13 16:28:14 -08004320 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4321 final int callingUid,
4322 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004323 final NetworkRequestInfo nri =
4324 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4325 if (nri == null) {
4326 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004327 }
James Mattisf7027322020-12-13 16:28:14 -08004328 if (VDBG || (DBG && request.isRequest())) {
4329 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004330 }
4331 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004332 if (callOnUnavailable) {
4333 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4334 }
Erik Kline155a59a2015-11-25 12:49:38 +09004335 }
Erik Kline0c04b742016-07-07 16:50:58 +09004336
James Mattisa076c532020-12-02 14:12:41 -08004337 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004338 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004339 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004340 if (null == mNetworkRequests.remove(req)) {
4341 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4342 continue;
4343 }
James Mattisa076c532020-12-02 14:12:41 -08004344 if (req.isListen()) {
4345 removeListenRequestFromNetworks(req);
4346 }
4347 }
James Mattis8f036802021-06-20 16:26:01 -07004348 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004349 if (mDefaultNetworkRequests.remove(nri)) {
4350 // If this request was one of the defaults, then the UID rules need to be updated
4351 // WARNING : if the app(s) for which this network request is the default are doing
4352 // traffic, this will kill their connected sockets, even if an equivalent request
4353 // is going to be reinstated right away ; unconnected traffic will go on the default
4354 // until the new default is set, which will happen very soon.
4355 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4356 // remove ranges for those requests that won't have a replacement
4357 final NetworkAgentInfo satisfier = nri.getSatisfier();
4358 if (null != satisfier) {
4359 try {
paulhu0e79d952021-06-09 16:11:35 +08004360 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4361 satisfier.network.getNetId(),
4362 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004363 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004364 } catch (RemoteException e) {
4365 loge("Exception setting network preference default network", e);
4366 }
4367 }
4368 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004369 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004370 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004371 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004372
4373 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004374 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004375 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004376 }
4377 }
4378
Chalard Jean0354d8c2021-01-12 10:58:56 +09004379 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4380 // needed for this offer.
4381 for (final NetworkOfferInfo noi : mNetworkOffers) {
4382 for (final NetworkRequest req : nri.mRequests) {
4383 if (req.isRequest() && noi.offer.neededFor(req)) {
4384 noi.offer.onNetworkUnneeded(req);
4385 }
4386 }
4387 }
James Mattisa076c532020-12-02 14:12:41 -08004388 }
4389
James Mattis3ce3d3c2021-02-09 18:18:28 -08004390 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4391 for (final NetworkRequestInfo nri : nris) {
4392 if (mDefaultRequest == nri) {
4393 // Make sure we never remove the default request.
4394 continue;
4395 }
4396 handleRemoveNetworkRequest(nri);
4397 }
4398 }
4399
James Mattisa076c532020-12-02 14:12:41 -08004400 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4401 // listens don't have a singular affected Network. Check all networks to see
4402 // if this listen request applies and remove it.
4403 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4404 nai.removeRequest(req.requestId);
4405 if (req.networkCapabilities.hasSignalStrength()
4406 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4407 updateSignalStrengthThresholds(nai, "RELEASE", req);
4408 }
4409 }
4410 }
4411
4412 /**
4413 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4414 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4415 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4416 */
4417 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4418 boolean wasKept = false;
4419 final NetworkAgentInfo nai = nri.getSatisfier();
4420 if (nai != null) {
4421 final int requestLegacyType = nri.getActiveRequest().legacyType;
4422 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4423 nai.removeRequest(nri.getActiveRequest().requestId);
4424 if (VDBG || DDBG) {
4425 log(" Removing from current network " + nai.toShortString()
4426 + ", leaving " + nai.numNetworkRequests() + " requests.");
4427 }
4428 // If there are still lingered requests on this network, don't tear it down,
4429 // but resume lingering instead.
4430 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004431 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004432 notifyNetworkLosing(nai, now);
4433 }
4434 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4435 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4436 teardownUnneededNetwork(nai);
4437 } else {
4438 wasKept = true;
4439 }
James Mattisa076c532020-12-02 14:12:41 -08004440 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4441 // Went from foreground to background.
4442 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004443 }
4444
Erik Kline0c04b742016-07-07 16:50:58 +09004445 // Maintain the illusion. When this request arrived, we might have pretended
4446 // that a network connected to serve it, even though the network was already
4447 // connected. Now that this request has gone away, we might have to pretend
4448 // that the network disconnected. LegacyTypeTracker will generate that
4449 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004450 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004451 boolean doRemove = true;
4452 if (wasKept) {
4453 // check if any of the remaining requests for this network are for the
4454 // same legacy type - if so, don't remove the nai
4455 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4456 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004457 if (otherRequest.legacyType == requestLegacyType
4458 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004459 if (DBG) log(" still have other legacy request - leaving");
4460 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004461 }
4462 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004463 }
4464
Erik Kline0c04b742016-07-07 16:50:58 +09004465 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004466 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004467 }
4468 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004469 }
4470 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004471
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004472 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4473 return checkAnyPermissionOf(
4474 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4475 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4476 }
4477
Lorenzo Colittid6459092016-07-04 12:55:44 +09004478 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004479 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004480 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004481 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004482 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004483 }
4484
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004485 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004486 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4487 enforceNetworkStackSettingsOrSetup();
4488 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4489 encodeBool(accept), encodeBool(always), network));
4490 }
4491
4492 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004493 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004494 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004495 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4496 }
4497
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004498 @Override
4499 public void setTestAllowBadWifiUntil(long timeMs) {
4500 enforceSettingsPermission();
4501 if (!Build.isDebuggable()) {
4502 throw new IllegalStateException("Does not support in non-debuggable build");
4503 }
4504
4505 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4506 throw new IllegalArgumentException("It should not exceed "
4507 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4508 }
4509
4510 mHandler.sendMessage(
4511 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4512 }
4513
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004514 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4515 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4516 " accept=" + accept + " always=" + always);
4517
4518 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4519 if (nai == null) {
4520 // Nothing to do.
4521 return;
4522 }
4523
4524 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004525 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004526 return;
4527 }
4528
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004529 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004530 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004531 }
4532
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004533 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4534 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004535 // If network becomes partial connectivity and user already accepted to use this
4536 // network, we should respect the user's option and don't need to popup the
4537 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004538 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004539 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004540 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004541 }
4542
4543 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004544 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004545 }
4546
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004547 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004548 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004549 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004550 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004551 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004552 }
4553
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004554 }
4555
lucaslin2240ef62019-03-12 13:08:03 +08004556 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4557 boolean always) {
4558 if (DBG) {
4559 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4560 + " always=" + always);
4561 }
4562
4563 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4564 if (nai == null) {
4565 // Nothing to do.
4566 return;
4567 }
4568
4569 if (nai.lastValidated) {
4570 // The network validated while the dialog box was up. Take no action.
4571 return;
4572 }
4573
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004574 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4575 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004576 }
4577
4578 // TODO: Use the current design or save the user choice into IpMemoryStore.
4579 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004580 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004581 }
4582
4583 if (!accept) {
4584 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004585 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004586 // Tear down the network.
4587 teardownUnneededNetwork(nai);
4588 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004589 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4590 // result in a partial connectivity result which will be processed by
4591 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004592 //
4593 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4594 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004595 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004596 }
4597 }
4598
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004599 private void handleSetAvoidUnvalidated(Network network) {
4600 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4601 if (nai == null || nai.lastValidated) {
4602 // Nothing to do. The network either disconnected or revalidated.
4603 return;
4604 }
4605 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004606 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004607 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004608 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004609 }
4610 }
4611
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004612 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004613 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004614 mHandler.sendMessageDelayed(
4615 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4616 PROMPT_UNVALIDATED_DELAY_MS);
4617 }
4618
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004619 @Override
4620 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004621 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004622 mHandler.post(() -> {
4623 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4624 if (nai == null) return;
4625 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004626 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004627 });
4628 }
4629
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004630 /**
4631 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4632 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004633 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004634 * @param appExtras Bundle to use as intent extras for the captive portal application.
4635 * Must be treated as opaque to avoid preventing the captive portal app to
4636 * update its arguments.
4637 */
4638 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004639 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004640 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4641 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004642
4643 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4644 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004645 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4646 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004647 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4648
lucaslin75ff7022020-12-17 04:14:35 +08004649 final long token = Binder.clearCallingIdentity();
4650 try {
4651 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4652 } finally {
4653 Binder.restoreCallingIdentity(token);
4654 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004655 }
4656
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004657 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4658 private final Network mNetwork;
4659
4660 private CaptivePortalImpl(Network network) {
4661 mNetwork = network;
4662 }
4663
4664 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004665 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004666 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4667 enforceSettingsPermission();
4668 }
4669
Chiachang Wang938bfba2020-01-09 13:50:55 +08004670 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004671 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004672 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004673 }
4674
4675 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004676 public void appRequest(final int request) {
4677 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4678 if (nm == null) return;
4679
4680 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004681 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004682 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004683 }
4684 }
4685
4686 @Nullable
4687 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4688 // getNetworkAgentInfoForNetwork is thread-safe
4689 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4690 if (nai == null) return null;
4691
4692 // nai.networkMonitor() is thread-safe
4693 return nai.networkMonitor();
4694 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004695 }
4696
Hugo Benichic9048bc2016-09-14 23:23:08 +00004697 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004698 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004699 }
4700
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004701 /**
4702 * Return whether the device should maintain continuous, working connectivity by switching away
4703 * from WiFi networks having no connectivity.
4704 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4705 */
4706 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004707 if (!checkNetworkStackPermission()) {
4708 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4709 }
4710 return avoidBadWifi();
4711 }
4712
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004713 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004714 ensureRunningOnConnectivityServiceThread();
4715 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004716 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004717 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004718 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004719 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4720 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4721 for (final NetworkOfferInfo noi : offersToUpdate) {
4722 updateOfferScore(noi.offer);
4723 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004724 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004725 }
4726
Erik Kline95ecfee2016-10-02 18:02:14 +09004727 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004728 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004729 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004730 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004731 if (!configRestrict) {
4732 pw.println("Bad Wi-Fi avoidance: unrestricted");
4733 return;
4734 }
4735
4736 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4737 pw.increaseIndent();
4738 pw.println("Config restrict: " + configRestrict);
4739
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004740 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004741 String description;
4742 // Can't use a switch statement because strings are legal case labels, but null is not.
4743 if ("0".equals(value)) {
4744 description = "get stuck";
4745 } else if (value == null) {
4746 description = "prompt";
4747 } else if ("1".equals(value)) {
4748 description = "avoid";
4749 } else {
4750 description = value + " (?)";
4751 }
4752 pw.println("User setting: " + description);
4753 pw.println("Network overrides:");
4754 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004755 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004756 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004757 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004758 }
4759 }
4760 pw.decreaseIndent();
4761 pw.decreaseIndent();
4762 }
4763
paulhu7746e4e2020-06-09 19:07:03 +08004764 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4765 // unify the method.
4766 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4767 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4768 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4769 return settingsComponent != null
4770 ? settingsComponent.getPackageName() : "com.android.settings";
4771 }
4772
lucaslinb1e8e382019-01-24 15:55:30 +08004773 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004774 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004775 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004776 switch (type) {
4777 case NO_INTERNET:
4778 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004779 // High priority because it is only displayed for explicitly selected networks.
4780 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004781 break;
lucasline117e2e2019-10-22 18:27:33 +08004782 case PRIVATE_DNS_BROKEN:
4783 action = Settings.ACTION_WIRELESS_SETTINGS;
4784 // High priority because we should let user know why there is no internet.
4785 highPriority = true;
4786 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004787 case LOST_INTERNET:
4788 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004789 // High priority because it could help the user avoid unexpected data usage.
4790 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004791 break;
lucaslin2240ef62019-03-12 13:08:03 +08004792 case PARTIAL_CONNECTIVITY:
4793 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004794 // Don't bother the user with a high-priority notification if the network was not
4795 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004796 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004797 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004798 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004799 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004800 return;
4801 }
4802
4803 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004804 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004805 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004806 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004807 // Some OEMs have their own Settings package. Thus, need to get the current using
4808 // Settings package name instead of just use default name "com.android.settings".
4809 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4810 intent.setClassName(settingsPkgName,
4811 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004812 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004813
paulhu2af50222020-10-11 22:52:27 +08004814 PendingIntent pendingIntent = PendingIntent.getActivity(
4815 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004816 0 /* requestCode */,
4817 intent,
paulhu2af50222020-10-11 22:52:27 +08004818 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004819
Serik Beketayevec8ad212020-12-07 22:43:07 -08004820 mNotifier.showNotification(
4821 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004822 }
4823
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004824 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4825 // Don't prompt if the network is validated, and don't prompt on captive portals
4826 // because we're already prompting the user to sign in.
4827 if (nai.everValidated || nai.everCaptivePortalDetected) {
4828 return false;
4829 }
4830
4831 // If a network has partial connectivity, always prompt unless the user has already accepted
4832 // partial connectivity and selected don't ask again. This ensures that if the device
4833 // automatically connects to a network that has partial Internet access, the user will
4834 // always be able to use it, either because they've already chosen "don't ask again" or
4835 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004836 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004837 return true;
4838 }
4839
4840 // If a network has no Internet access, only prompt if the network was explicitly selected
4841 // and if the user has not already told us to use the network regardless of whether it
4842 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004843 if (nai.networkAgentConfig.explicitlySelected
4844 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004845 return true;
4846 }
4847
4848 return false;
4849 }
4850
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004851 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004852 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004853 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4854
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004855 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004856 return;
4857 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004858
4859 // Stop automatically reconnecting to this network in the future. Automatically connecting
4860 // to a network that provides no or limited connectivity is not useful, because the user
4861 // cannot use that network except through the notification shown by this method, and the
4862 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004863 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004864
lucaslin2240ef62019-03-12 13:08:03 +08004865 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4866 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4867 // popup the notification immediately when the network is partial connectivity.
4868 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004869 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004870 } else {
4871 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4872 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004873 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004874
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004875 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4876 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004877 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004878
lucaslin2240ef62019-03-12 13:08:03 +08004879 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4880 return;
4881 }
4882
4883 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004884 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004885 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004886 }
4887
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004888 @Override
4889 public int getMultipathPreference(Network network) {
4890 enforceAccessPermission();
4891
4892 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004893 if (nai != null && nai.networkCapabilities
4894 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004895 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4896 }
4897
Aaron Huang9a57acf2020-12-08 10:03:29 +08004898 final NetworkPolicyManager netPolicyManager =
4899 mContext.getSystemService(NetworkPolicyManager.class);
4900
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004901 final long token = Binder.clearCallingIdentity();
4902 final int networkPreference;
4903 try {
4904 networkPreference = netPolicyManager.getMultipathPreference(network);
4905 } finally {
4906 Binder.restoreCallingIdentity(token);
4907 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004908 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004909 return networkPreference;
4910 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004911 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4912 }
4913
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004914 @Override
4915 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004916 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004917 }
4918
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004919 private class InternalHandler extends Handler {
4920 public InternalHandler(Looper looper) {
4921 super(looper);
4922 }
4923
4924 @Override
4925 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004926 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004927 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004928 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004929 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004930 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004931 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004932 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004933 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004934 break;
4935 }
Jason Monka69f1b02013-10-10 14:02:51 -04004936 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004937 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4938 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004939 break;
4940 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004941 case EVENT_REGISTER_NETWORK_PROVIDER: {
4942 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004943 break;
4944 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004945 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4946 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004947 break;
4948 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004949 case EVENT_REGISTER_NETWORK_OFFER: {
4950 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4951 break;
4952 }
4953 case EVENT_UNREGISTER_NETWORK_OFFER: {
4954 final NetworkOfferInfo offer =
4955 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4956 if (null != offer) {
4957 handleUnregisterNetworkOffer(offer);
4958 }
4959 break;
4960 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004961 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004962 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4963 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4964 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004965 break;
4966 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004967 case EVENT_REGISTER_NETWORK_REQUEST:
4968 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09004969 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004970 break;
4971 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004972 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4973 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004974 handleRegisterNetworkRequestWithIntent(msg);
4975 break;
4976 }
Erik Kline155a59a2015-11-25 12:49:38 +09004977 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4978 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4979 handleTimedOutNetworkRequest(nri);
4980 break;
4981 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004982 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4983 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4984 break;
4985 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004986 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08004987 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4988 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004989 break;
4990 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004991 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09004992 Network network = (Network) msg.obj;
4993 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004994 break;
4995 }
lucaslin2240ef62019-03-12 13:08:03 +08004996 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4997 Network network = (Network) msg.obj;
4998 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4999 toBool(msg.arg2));
5000 break;
5001 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005002 case EVENT_SET_AVOID_UNVALIDATED: {
5003 handleSetAvoidUnvalidated((Network) msg.obj);
5004 break;
5005 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005006 case EVENT_PROMPT_UNVALIDATED: {
5007 handlePromptUnvalidated((Network) msg.obj);
5008 break;
5009 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005010 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5011 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005012 break;
5013 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005014 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005015 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005016 mKeepaliveTracker.handleStartKeepalive(msg);
5017 break;
5018 }
5019 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005020 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005021 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5022 int slot = msg.arg1;
5023 int reason = msg.arg2;
5024 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5025 break;
5026 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005027 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5028 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5029 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005030 break;
5031 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005032 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5033 handlePrivateDnsSettingsChanged();
5034 break;
dalyk1720e542018-03-05 12:42:22 -05005035 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5036 handlePrivateDnsValidationUpdate(
5037 (PrivateDnsValidationUpdate) msg.obj);
5038 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005039 case EVENT_UID_BLOCKED_REASON_CHANGED:
5040 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005041 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005042 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5043 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5044 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005045 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005046 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5047 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005048 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005049 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005050 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005051 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005052 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5053 IOnCompleteListener> arg =
5054 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5055 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005056 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005057 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005058 }
lucaslin1193a5d2021-01-21 02:04:15 +08005059 case EVENT_REPORT_NETWORK_ACTIVITY:
5060 mNetworkActivityTracker.handleReportNetworkActivity();
5061 break;
paulhu51f77dc2021-06-07 02:34:20 +00005062 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5063 handleMobileDataPreferredUidsChanged();
5064 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005065 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5066 final long timeMs = ((Long) msg.obj).longValue();
5067 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5068 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005069 }
5070 }
5071 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005072
Lorenzo Colittid6459092016-07-04 12:55:44 +09005073 @Override
markchien5776f962019-12-16 20:15:20 +08005074 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005075 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005076 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5077 Context.TETHERING_SERVICE);
5078 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005079 }
5080
Lorenzo Colittid6459092016-07-04 12:55:44 +09005081 @Override
markchien5776f962019-12-16 20:15:20 +08005082 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005083 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005084 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5085 Context.TETHERING_SERVICE);
5086 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005087 }
5088
Lorenzo Colittid6459092016-07-04 12:55:44 +09005089 @Override
markchien5776f962019-12-16 20:15:20 +08005090 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005091 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005092 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5093 Context.TETHERING_SERVICE);
5094 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005095 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005096
markchien5776f962019-12-16 20:15:20 +08005097
Lorenzo Colittid6459092016-07-04 12:55:44 +09005098 @Override
markchien5776f962019-12-16 20:15:20 +08005099 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005100 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005101 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5102 Context.TETHERING_SERVICE);
5103
5104 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005105 }
5106
Lorenzo Colittid6459092016-07-04 12:55:44 +09005107 @Override
markchien5776f962019-12-16 20:15:20 +08005108 @Deprecated
5109 public String[] getTetherableUsbRegexs() {
5110 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5111 Context.TETHERING_SERVICE);
5112
5113 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005114 }
5115
Udam Saini8f7d6a72017-06-07 12:06:28 -07005116 @Override
markchien5776f962019-12-16 20:15:20 +08005117 @Deprecated
5118 public String[] getTetherableWifiRegexs() {
5119 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5120 Context.TETHERING_SERVICE);
5121 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005122 }
5123
Robert Greenwalte0b00512014-07-02 09:59:16 -07005124 // Called when we lose the default network and have no replacement yet.
5125 // This will automatically be cleared after X seconds or a new default network
5126 // becomes CONNECTED, whichever happens first. The timer is started by the
5127 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005128 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005129 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005130 if (mNetTransitionWakeLock.isHeld()) {
5131 return;
5132 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005133 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005134 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5135 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005136 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005137 mWakelockLogs.log("ACQUIRE for " + forWhom);
5138 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005139 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005140 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005141 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005142 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005143
Hugo Benichi471b62a2017-03-30 23:18:10 +09005144 // Called when we gain a new default network to release the network transition wakelock in a
5145 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5146 // message is cancelled.
5147 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005148 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005149 if (!mNetTransitionWakeLock.isHeld()) {
5150 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005151 }
5152 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005153 // Cancel self timeout on wakelock hold.
5154 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5155 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5156 mHandler.sendMessageDelayed(msg, 1000);
5157 }
5158
5159 // Called when either message of ensureNetworkTransitionWakelock or
5160 // scheduleReleaseNetworkTransitionWakelock is processed.
5161 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5162 String event = eventName(eventId);
5163 synchronized (this) {
5164 if (!mNetTransitionWakeLock.isHeld()) {
5165 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005166 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005167 return;
5168 }
5169 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005170 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5171 mTotalWakelockDurationMs += lockDuration;
5172 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5173 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005174 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005175 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005176 }
5177
Robert Greenwalt986c7412010-09-08 15:24:47 -07005178 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005179 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005180 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005181 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005182 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005183 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005184 }
5185
Lorenzo Colittid6459092016-07-04 12:55:44 +09005186 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005187 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005188 enforceAccessPermission();
5189 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005190 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005191 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005192
5193 final NetworkAgentInfo nai;
5194 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005195 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005196 } else {
5197 nai = getNetworkAgentInfoForNetwork(network);
5198 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005199
5200 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005201 mHandler.obtainMessage(
5202 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005203 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005204
Hugo Benichid6b510a2017-04-06 17:22:18 +09005205 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005206 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005207 if (nai == null
5208 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005209 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005210 return;
5211 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005212 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005213 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005214 mConnectivityDiagnosticsHandler.sendMessage(
5215 mConnectivityDiagnosticsHandler.obtainMessage(
5216 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5217 new ReportedNetworkConnectivityInfo(
5218 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005219 return;
5220 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005221 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005222 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005223 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005224 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005225 // Validating a network that has not yet connected could result in a call to
5226 // rematchNetworkAndRequests() which is not meant to work on such networks.
5227 if (!nai.everConnected) {
5228 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005229 }
paulhu7aeba372020-12-30 00:42:19 +08005230 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5231 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005232 return;
5233 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005234
5235 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5236 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5237 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5238 // completed.
5239 mConnectivityDiagnosticsHandler.sendMessage(
5240 mConnectivityDiagnosticsHandler.obtainMessage(
5241 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5242 new ReportedNetworkConnectivityInfo(
5243 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005244 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005245 }
5246
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005247 // TODO: call into netd.
5248 private boolean queryUserAccess(int uid, Network network) {
5249 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5250 if (nai == null) return false;
5251
5252 // Any UID can use its default network.
5253 if (nai == getDefaultNetworkForUid(uid)) return true;
5254
5255 // Privileged apps can use any network.
5256 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5257 return true;
5258 }
5259
5260 // An unprivileged UID can use a VPN iff the VPN applies to it.
5261 if (nai.isVPN()) {
5262 return nai.networkCapabilities.appliesToUid(uid);
5263 }
5264
5265 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5266 // sockets, i.e., if it is the owner.
5267 final NetworkAgentInfo vpn = getVpnForUid(uid);
5268 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5269 && uid != vpn.networkCapabilities.getOwnerUid()) {
5270 return false;
5271 }
5272
5273 // The UID's permission must be at least sufficient for the network. Since the restricted
5274 // permission was already checked above, that just leaves background networks.
5275 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5276 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5277 }
5278
5279 // Unrestricted network. Anyone gets to use it.
5280 return true;
5281 }
5282
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005283 /**
5284 * Returns information about the proxy a certain network is using. If given a null network, it
5285 * it will return the proxy for the bound network for the caller app or the default proxy if
5286 * none.
5287 *
5288 * @param network the network we want to get the proxy information for.
5289 * @return Proxy information if a network has a proxy configured, or otherwise null.
5290 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005291 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005292 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005293 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005294 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005295 if (network == null) {
5296 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005297 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005298 true);
5299 if (activeNetwork == null) {
5300 return null;
5301 }
5302 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005303 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005304 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5305 // caller may not have.
5306 return getLinkPropertiesProxyInfo(network);
5307 }
5308 // No proxy info available if the calling UID does not have network access.
5309 return null;
5310 }
5311
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005312
5313 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005314 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5315 if (nai == null) return null;
5316 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005317 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5318 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005319 }
5320 }
5321
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005322 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005323 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005324 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005325 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005326 }
5327
Chalard Jean777e2e52018-06-07 18:02:37 +09005328 @Override
5329 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005330 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005331 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005332 }
5333
Jason Monk4d5e20f2014-04-25 15:00:09 -04005334 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005335 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005336 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005337 proxy = null;
5338 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005339 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005340 }
5341
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005342 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5343 // when any network changes proxy.
5344 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5345 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005346 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005347 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5348 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5349
Chalard Jean7d97afc2018-06-07 17:41:29 +09005350 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005351 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005352 }
5353 }
5354
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005355 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005356 final private HashMap<Uri, Integer> mUriEventMap;
5357 final private Context mContext;
5358 final private Handler mHandler;
5359
5360 SettingsObserver(Context context, Handler handler) {
5361 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005362 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005363 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005364 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005365 }
5366
Erik Kline05f2b402015-04-30 12:58:40 +09005367 void observe(Uri uri, int what) {
5368 mUriEventMap.put(uri, what);
5369 final ContentResolver resolver = mContext.getContentResolver();
5370 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005371 }
5372
5373 @Override
5374 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005375 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005376 }
5377
5378 @Override
5379 public void onChange(boolean selfChange, Uri uri) {
5380 final Integer what = mUriEventMap.get(uri);
5381 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005382 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005383 } else {
5384 loge("No matching event to send for URI=" + uri);
5385 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005386 }
5387 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005388
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005389 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005390 Log.d(TAG, s);
5391 }
5392
5393 private static void logw(String s) {
5394 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005395 }
5396
Daniel Brightf9e945b2020-06-15 16:10:01 -07005397 private static void logwtf(String s) {
5398 Log.wtf(TAG, s);
5399 }
5400
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005401 private static void logwtf(String s, Throwable t) {
5402 Log.wtf(TAG, s, t);
5403 }
5404
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005405 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005406 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005407 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005408
Hugo Benichi39621362017-02-11 17:04:43 +09005409 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005410 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005411 }
5412
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005413 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005414 * Return the information of all ongoing VPNs.
5415 *
5416 * <p>This method is used to update NetworkStatsService.
5417 *
5418 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005419 */
junyulai2050bed2021-01-23 09:46:34 +08005420 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005421 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005422 if (mLockdownEnabled) {
5423 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005424 }
junyulai2050bed2021-01-23 09:46:34 +08005425 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005426 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005427 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005428 if (info != null) {
5429 infoList.add(info);
5430 }
5431 }
junyulai2050bed2021-01-23 09:46:34 +08005432 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005433 }
5434
5435 /**
5436 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005437 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005438 */
junyulai2050bed2021-01-23 09:46:34 +08005439 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005440 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005441 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5442 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005443 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5444 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5445 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005446 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5447 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005448 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005449 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005450 }
5451 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005452
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005453 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005454
5455 List<String> interfaces = new ArrayList<>();
5456 for (Network network : underlyingNetworks) {
5457 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5458 if (underlyingNai == null) continue;
5459 LinkProperties lp = underlyingNai.linkProperties;
5460 for (String iface : lp.getAllInterfaceNames()) {
5461 if (!TextUtils.isEmpty(iface)) {
5462 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005463 }
5464 }
Benedict Wong34857f82019-06-12 17:46:15 +00005465 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005466
5467 if (interfaces.isEmpty()) return null;
5468
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005469 // Must be non-null or NetworkStatsService will crash.
5470 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5471 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005472 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005473 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005474
junyulai2050bed2021-01-23 09:46:34 +08005475 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5476 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005477 }
5478
James Mattisd31bdfa2020-12-23 16:37:26 -08005479 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005480 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5481 Network[] underlyingNetworks) {
5482 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005483 if (underlyingNetworks == null && defaultNetwork != null) {
5484 // null underlying networks means to track the default.
5485 underlyingNetworks = new Network[] { defaultNetwork };
5486 }
5487 return underlyingNetworks;
5488 }
5489
5490 // Returns true iff |network| is an underlying network of |nai|.
5491 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5492 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5493 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005494 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005495 final Network[] underlying = underlyingNetworksOrDefault(
5496 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005497 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005498 }
5499
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005500 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005501 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005502 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005503 * When underlying networks change, such networks may have to update capabilities to reflect
5504 * things like the metered bit, their transports, and so on. The capabilities are calculated
5505 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005506 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005507 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005508 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005509 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005510 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005511 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005512 }
5513 }
5514 }
5515
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005516 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5517 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5518 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5519 // a VPN is not up.
5520 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5521 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5522 for (UidRange range : blockedUidRanges) {
5523 if (range.contains(uid)) return true;
5524 }
5525 return false;
5526 }
5527
5528 @Override
5529 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005530 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5532 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5533 }
5534
5535 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5536 if (DBG) {
5537 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5538 + Arrays.toString(ranges));
5539 }
5540 // Cannot use a Set since the list of UID ranges might contain duplicates.
5541 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5542 for (int i = 0; i < ranges.length; i++) {
5543 if (requireVpn) {
5544 newVpnBlockedUidRanges.add(ranges[i]);
5545 } else {
5546 newVpnBlockedUidRanges.remove(ranges[i]);
5547 }
5548 }
5549
5550 try {
5551 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5552 } catch (RemoteException | ServiceSpecificException e) {
5553 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5554 + Arrays.toString(ranges) + "): netd command failed: " + e);
5555 }
5556
5557 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5558 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005559 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5560 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005561 }
5562
5563 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5564 }
5565
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005566 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005567 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005568 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005569 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005570 }
5571
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005572 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5573 return mLockdownEnabled
5574 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5575 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005576 }
5577
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005578 private NetworkAgentInfo getLegacyLockdownNai() {
5579 if (!mLockdownEnabled) {
5580 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005581 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005582 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005583 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5584 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005585
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005586 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005587 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5588 // a local variable. There is no need to make a copy because its contents cannot change.
5589 final Network[] underlying = nai.declaredUnderlyingNetworks;
5590 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005591 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005592 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005593
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005594 // The legacy lockdown VPN always uses the default network.
5595 // If the VPN's underlying network is no longer the current default network, it means that
5596 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005597 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5598 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005599 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005600 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005601 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005602 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005603
5604 return nai;
5605 };
5606
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005607 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5608 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5609 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005610 private DetailedState getLegacyLockdownState(DetailedState origState) {
5611 if (origState != DetailedState.CONNECTED) {
5612 return origState;
5613 }
5614 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5615 ? DetailedState.CONNECTING
5616 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005617 }
5618
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005619 private void filterForLegacyLockdown(NetworkInfo ni) {
5620 if (!mLockdownEnabled || !ni.isConnected()) return;
5621 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5622 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5623 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5624 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5625 // network, this time with a state of CONNECTED.
5626 //
5627 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5628 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5629 // is not too far off the truth, since an always-on VPN, when not connected, is always
5630 // trying to reconnect.
5631 if (getLegacyLockdownNai() == null) {
5632 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5633 }
5634 }
5635
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005636 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005637 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005638 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005639 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005640 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5641 return;
5642 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005643 final long ident = Binder.clearCallingIdentity();
5644 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005645 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005646 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005647 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005648 } finally {
5649 Binder.restoreCallingIdentity(ident);
5650 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005651 }
Wink Savillecb117d32013-08-29 14:57:08 -07005652
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005653 @Override
5654 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005655 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005656 final long ident = Binder.clearCallingIdentity();
5657 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005658 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005659 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005660 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5661 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005662 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005663 } finally {
5664 Binder.restoreCallingIdentity(ident);
5665 }
5666 }
5667
James Mattis02220e22021-03-13 19:27:21 -08005668 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005669 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005670 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5671 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5672 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005673 }
5674
James Mattis02220e22021-03-13 19:27:21 -08005675 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005676 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005677 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005678 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005679 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005680 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005681 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5682 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5683 }
junyulaid91e7052020-08-28 13:44:33 +08005684 }
5685
James Mattis02220e22021-03-13 19:27:21 -08005686 private void onPackageChanged(@NonNull final String packageName) {
5687 // This is necessary in case a package is added or removed, but also when it's replaced to
5688 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5689 // as one in the preferences, then it should follow the same routing as that other package,
5690 // which means updating the rules is never to be needed in this case (whether it joins or
5691 // leaves a UID with a preference).
5692 if (isMappedInOemNetworkPreference(packageName)) {
5693 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5694 }
5695 }
5696
5697 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005698 @Override
5699 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005700 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005701 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005702 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005703
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005704 // User should be filled for below intents, check the existence.
5705 if (user == null) {
5706 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5707 return;
5708 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005709
Lorenzo Colitticd675292021-02-04 17:32:07 +09005710 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005711 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005712 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005713 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005714 } else {
junyulaid91e7052020-08-28 13:44:33 +08005715 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005716 }
5717 }
5718 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005719
James Mattis02220e22021-03-13 19:27:21 -08005720 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5721 @Override
5722 public void onReceive(Context context, Intent intent) {
5723 ensureRunningOnConnectivityServiceThread();
5724 switch (intent.getAction()) {
5725 case Intent.ACTION_PACKAGE_ADDED:
5726 case Intent.ACTION_PACKAGE_REMOVED:
5727 case Intent.ACTION_PACKAGE_REPLACED:
5728 onPackageChanged(intent.getData().getSchemeSpecificPart());
5729 break;
5730 default:
5731 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5732 }
5733 }
5734 };
5735
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005736 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005737 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005738
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005739 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005740 public final String name;
5741 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005742 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005743 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005744
lifraf3a3492021-03-10 13:58:14 +08005745 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5746 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005747 this.name = name;
5748 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005749 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005750 mDeathRecipient = deathRecipient;
5751
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005752 if (mDeathRecipient == null) {
5753 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005754 }
5755 }
5756
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005757 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005758 try {
5759 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5760 } catch (RemoteException e) {
5761 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005762 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005763 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005764 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005765
James Mattis4fce5d12020-11-12 15:53:42 -08005766 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5767 for (int i = 0; i < requests.size(); i++) {
5768 ensureNetworkRequestHasType(requests.get(i));
5769 }
5770 }
5771
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005772 private void ensureNetworkRequestHasType(NetworkRequest request) {
5773 if (request.type == NetworkRequest.Type.NONE) {
5774 throw new IllegalArgumentException(
5775 "All NetworkRequests in ConnectivityService must have a type");
5776 }
5777 }
5778
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005779 /**
5780 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005781 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005782 */
James Mattis258ea3c2020-11-15 15:04:40 -08005783 @VisibleForTesting
5784 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005785 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5786 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005787 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005788
James Mattisa076c532020-12-02 14:12:41 -08005789 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5790 void setSatisfier(
5791 @Nullable final NetworkAgentInfo satisfier,
5792 @Nullable final NetworkRequest activeRequest) {
5793 mSatisfier = satisfier;
5794 mActiveRequest = activeRequest;
5795 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005796
James Mattisd31bdfa2020-12-23 16:37:26 -08005797 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005798 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005799 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005800 private NetworkAgentInfo mSatisfier;
5801 NetworkAgentInfo getSatisfier() {
5802 return mSatisfier;
5803 }
5804
5805 // The request in mRequests assigned to a network agent. This is null if none of the
5806 // requests in mRequests can be satisfied. This member has the constraint of only being
5807 // accessible on the handler thread.
5808 @Nullable
5809 private NetworkRequest mActiveRequest;
5810 NetworkRequest getActiveRequest() {
5811 return mActiveRequest;
5812 }
5813
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005814 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005815 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005816 @Nullable
5817 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005818
5819 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005820 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005821 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005822 final int mPid;
5823 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005824 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005825 @Nullable
5826 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005827
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005828 // Counter keeping track of this NRI.
5829 final PerUidCounter mPerUidCounter;
5830
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005831 // Effective UID of this request. This is different from mUid when a privileged process
5832 // files a request on behalf of another UID. This UID is used to determine blocked status,
5833 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5834 // maximum limit of registered callbacks per UID.
5835 final int mAsUid;
5836
paulhu48291862021-07-14 14:53:57 +08005837 // Preference order of this request.
5838 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005839
James Mattis3ce3d3c2021-02-09 18:18:28 -08005840 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5841 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5842 // maintained for keying off of. This is only a concern when the original nri
5843 // mNetworkRequests changes which happens currently for apps that register callbacks to
5844 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5845 // that match the per-app default nri that currently tracks the calling app's uid so that
5846 // callbacks are fired at the appropriate time. When the callbacks fire,
5847 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5848 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5849 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5850 @NonNull
5851 private final NetworkRequest mNetworkRequestForCallback;
5852 NetworkRequest getNetworkRequestForCallback() {
5853 return mNetworkRequestForCallback;
5854 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005855
James Mattisd31bdfa2020-12-23 16:37:26 -08005856 /**
5857 * Get the list of UIDs this nri applies to.
5858 */
5859 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005860 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005861 // networkCapabilities.getUids() returns a defensive copy.
5862 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005863 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5864 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005865 }
5866
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005867 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5868 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005869 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005870 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005871 }
5872
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005873 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005874 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005875 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005876 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005877 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005878 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005879 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005880 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005881 mBinder = null;
5882 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005883 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005884 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005885 mPerUidCounter = getRequestCounter(this);
5886 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005887 /**
5888 * Location sensitive data not included in pending intent. Only included in
5889 * {@link NetworkCallback}.
5890 */
5891 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005892 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005893 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005894 }
5895
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005896 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005897 @Nullable final IBinder binder,
5898 @NetworkCallback.Flag int callbackFlags,
5899 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005900 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5901 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005902 }
5903
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005904 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005905 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005906 @Nullable final IBinder binder,
5907 @NetworkCallback.Flag int callbackFlags,
5908 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005909 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005910 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005911 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005912 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005913 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005914 mBinder = binder;
5915 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005916 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005917 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005918 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005919 mPerUidCounter = getRequestCounter(this);
5920 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005921 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005922 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005923 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005924 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005925 }
5926
James Mattis3ce3d3c2021-02-09 18:18:28 -08005927 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5928 @NonNull final List<NetworkRequest> r) {
5929 super();
5930 ensureAllNetworkRequestsHaveType(r);
5931 mRequests = initializeRequests(r);
5932 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005933 final NetworkAgentInfo satisfier = nri.getSatisfier();
5934 if (null != satisfier) {
5935 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5936 // The active request is necessary to figure out what callbacks to send, in
5937 // particular then a network updates its capabilities.
5938 // As this code creates a new NRI with a new set of requests, figure out which of
5939 // the list of requests should be the active request. It is always the first
5940 // request of the list that can be satisfied by the satisfier since the order of
5941 // requests is a priority order.
5942 // Note even in the presence of a satisfier there may not be an active request,
5943 // when the satisfier is the no-service network.
5944 NetworkRequest activeRequest = null;
5945 for (final NetworkRequest candidate : r) {
5946 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5947 activeRequest = candidate;
5948 break;
5949 }
5950 }
5951 setSatisfier(satisfier, activeRequest);
5952 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005953 mMessenger = nri.mMessenger;
5954 mBinder = nri.mBinder;
5955 mPid = nri.mPid;
5956 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005957 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005958 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09005959 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005960 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005961 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005962 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005963 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005964 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005965 }
5966
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005967 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08005968 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005969 }
5970
paulhue9913722021-05-26 15:19:20 +08005971 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08005972 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08005973 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08005974 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08005975 }
5976
James Mattis2516da32021-01-31 17:06:19 -08005977 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5978 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5979 // false.
5980 boolean isBeingSatisfied() {
5981 return (null != mSatisfier && null != mActiveRequest);
5982 }
5983
James Mattis3d229892020-11-16 16:46:28 -08005984 boolean isMultilayerRequest() {
5985 return mRequests.size() > 1;
5986 }
5987
James Mattis45d81842021-01-10 14:24:24 -08005988 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5989 // Creating a defensive copy to prevent the sender from modifying the list being
5990 // reflected in the return value of this method.
5991 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08005992 return Collections.unmodifiableList(tempRequests);
5993 }
5994
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005995 void decrementRequestCount() {
5996 mPerUidCounter.decrementCount(mUid);
5997 }
5998
James Mattisb1392002021-03-31 13:57:52 -07005999 void linkDeathRecipient() {
6000 if (null != mBinder) {
6001 try {
6002 mBinder.linkToDeath(this, 0);
6003 } catch (RemoteException e) {
6004 binderDied();
6005 }
6006 }
6007 }
6008
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006009 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006010 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006011 try {
6012 mBinder.unlinkToDeath(this, 0);
6013 } catch (NoSuchElementException e) {
6014 // Temporary workaround for b/194394697 pending analysis of additional logs
6015 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6016 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006017 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006018 }
6019
paulhu48291862021-07-14 14:53:57 +08006020 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6021 // Compare two preference orders.
6022 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006023 }
6024
paulhu48291862021-07-14 14:53:57 +08006025 int getPreferenceOrderForNetd() {
6026 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6027 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6028 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006029 }
paulhu48291862021-07-14 14:53:57 +08006030 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006031 }
6032
James Mattis4fce5d12020-11-12 15:53:42 -08006033 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006034 public void binderDied() {
6035 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006036 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006037 // As an immutable collection, mRequests cannot change by the time the
6038 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6039 // is acceptable. Use handleReleaseNetworkRequest and not directly
6040 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6041 // the app already unregistered the request.
6042 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6043 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006044 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006045
James Mattis4fce5d12020-11-12 15:53:42 -08006046 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006047 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006048 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6049 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006050 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006051 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006052 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006053 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006054 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006055 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006056 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006057 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006058 }
6059
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006060 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
6061 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
6062 if (badCapability != null) {
6063 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04006064 }
6065 }
6066
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006067 // This checks that the passed capabilities either do not request a
6068 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006069 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006070 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006071 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006072 throw new SecurityException("Insufficient permissions to request a specific SSID");
6073 }
paulhu1a407652019-03-22 16:35:06 +08006074
6075 if (nc.hasSignalStrength()
6076 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6077 throw new SecurityException(
6078 "Insufficient permissions to request a specific signal strength");
6079 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006080 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006081
junyulai2217bec2021-04-14 23:33:31 +08006082 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006083 enforceNetworkFactoryPermission();
6084 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006085 }
6086
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006087 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006088 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006089 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006090 // mNetworkRequests may contain the same value multiple times in case of
6091 // multilayer requests. It won't matter in this case because the thresholds
6092 // will then be the same and be deduplicated as they enter the `thresholds` set.
6093 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006094 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6095 for (final NetworkRequest req : nri.mRequests) {
6096 if (req.networkCapabilities.hasSignalStrength()
6097 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6098 thresholds.add(req.networkCapabilities.getSignalStrength());
6099 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006100 }
6101 }
6102 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006103 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006104 }
6105
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006106 private void updateSignalStrengthThresholds(
6107 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006108 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006109
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006110 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006111 String detail;
6112 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6113 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6114 } else {
6115 detail = reason;
6116 }
6117 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006118 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006119 }
6120
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006121 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006122 }
6123
Etan Cohen1b6d4182017-04-03 17:42:34 -07006124 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6125 if (nc == null) {
6126 return;
6127 }
6128 NetworkSpecifier ns = nc.getNetworkSpecifier();
6129 if (ns == null) {
6130 return;
6131 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006132 if (ns instanceof MatchAllNetworkSpecifier) {
6133 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6134 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006135 }
6136
lucasline117e2e2019-10-22 18:27:33 +08006137 private void ensureValid(NetworkCapabilities nc) {
6138 ensureValidNetworkSpecifier(nc);
6139 if (nc.isPrivateDnsBroken()) {
6140 throw new IllegalArgumentException("Can't request broken private DNS");
6141 }
6142 }
6143
Chiachang Wang3bc52762021-11-25 14:17:57 +08006144 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6145 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006146 private boolean isTargetSdkAtleast(int version, int callingUid,
6147 @NonNull String callingPackageName) {
6148 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006149 final PackageManager pm =
6150 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006151 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006152 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006153 if (callingVersion < version) return false;
6154 } catch (PackageManager.NameNotFoundException e) { }
6155 return true;
6156 }
6157
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006158 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006159 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006160 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006161 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006162 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006163 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006164 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6165 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006166 throw new SecurityException("Insufficient permissions to specify legacy type");
6167 }
markchienfac84a22020-03-18 21:16:15 +08006168 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006169 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006170 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006171 // Privileged callers can track the default network of another UID by passing in a UID.
6172 if (asUid != Process.INVALID_UID) {
6173 enforceSettingsPermission();
6174 } else {
6175 asUid = callingUid;
6176 }
junyulaiad010792021-01-11 16:53:38 +08006177 final NetworkRequest.Type reqType;
6178 try {
6179 reqType = NetworkRequest.Type.values()[reqTypeInt];
6180 } catch (ArrayIndexOutOfBoundsException e) {
6181 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6182 }
6183 switch (reqType) {
6184 case TRACK_DEFAULT:
6185 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006186 // is unused and will be replaced by ones appropriate for the UID (usually, the
6187 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006188 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006189 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006190 enforceAccessPermission();
6191 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006192 case TRACK_SYSTEM_DEFAULT:
6193 enforceSettingsPermission();
6194 networkCapabilities = new NetworkCapabilities(defaultNc);
6195 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006196 case BACKGROUND_REQUEST:
6197 enforceNetworkStackOrSettingsPermission();
6198 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006199 case REQUEST:
6200 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6201 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6202 callingAttributionTag);
6203 // TODO: this is incorrect. We mark the request as metered or not depending on
6204 // the state of the app when the request is filed, but we never change the
6205 // request if the app changes network state. http://b/29964605
6206 enforceMeteredApnPolicy(networkCapabilities);
6207 break;
junyulai1b1c8742021-03-12 20:05:08 +08006208 case LISTEN_FOR_BEST:
6209 enforceAccessPermission();
6210 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6211 break;
junyulaiad010792021-01-11 16:53:38 +08006212 default:
6213 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006214 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006215 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006216 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006217 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006218
junyulai1b1c8742021-03-12 20:05:08 +08006219 // Enforce FOREGROUND if the caller does not have permission to use background network.
6220 if (reqType == LISTEN_FOR_BEST) {
6221 restrictBackgroundRequestForCaller(networkCapabilities);
6222 }
6223
6224 // Set the UID range for this request to the single UID of the requester, unless the
6225 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006226 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6227 // are no visible methods to set the UIDs, an app could use reflection to try and get
6228 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006229 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006230 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6231 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006232
Etan Cohen85000162017-02-05 10:42:27 -08006233 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006234 throw new IllegalArgumentException("Bad timeout specified");
6235 }
lucasline117e2e2019-10-22 18:27:33 +08006236 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006237
James Mattis3ce3d3c2021-02-09 18:18:28 -08006238 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006239 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006240 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006241 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006242 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006243 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006244
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006245 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6246 // copied from the default request above. (This is necessary to ensure, for example, that
6247 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6248 // changes don't alter request matching.
6249 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6250 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006251 throw new IllegalStateException(
6252 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006253 + networkCapabilities + " vs. " + defaultNc);
6254 }
6255
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006256 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006257 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006258 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006259 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006260 }
6261 return networkRequest;
6262 }
6263
James Mattis3ce3d3c2021-02-09 18:18:28 -08006264 /**
6265 * Return the nri to be used when registering a network request. Specifically, this is used with
6266 * requests registered to track the default request. If there is currently a per-app default
6267 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6268 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006269 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6270 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006271 * @param nr the network request for the nri.
6272 * @param msgr the messenger for the nri.
6273 * @param binder the binder for the nri.
6274 * @param callingAttributionTag the calling attribution tag for the nri.
6275 * @return the nri to register.
6276 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006277 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006278 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006279 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006280 @Nullable String callingAttributionTag) {
6281 final List<NetworkRequest> requests;
6282 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6283 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006284 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006285 } else {
6286 requests = Collections.singletonList(nr);
6287 }
Roshan Pius951c0032020-12-22 15:10:42 -08006288 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006289 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006290 }
6291
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006292 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6293 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006294 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006295 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006296 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006297 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006298 }
6299 }
6300
fenglu3f357402015-03-20 11:29:56 -07006301 @Override
fenglub00f4882015-04-21 17:12:05 -07006302 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006303 enforceAccessPermission();
6304 NetworkAgentInfo nai = null;
6305 if (network == null) {
6306 return false;
6307 }
6308 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006309 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006310 }
6311 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006312 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006313 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006314 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006315 Integer uidReqs = mBandwidthRequests.get(uid);
6316 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006317 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006318 }
6319 mBandwidthRequests.put(uid, ++uidReqs);
6320 }
fenglu3f357402015-03-20 11:29:56 -07006321 return true;
6322 }
6323 return false;
6324 }
6325
Felipe Leme0a5ae422016-06-20 16:36:29 -07006326 private boolean isSystem(int uid) {
6327 return uid < Process.FIRST_APPLICATION_UID;
6328 }
fenglu3f357402015-03-20 11:29:56 -07006329
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006330 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006331 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006332 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006333 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006334 return;
6335 }
Hugo Benichi39621362017-02-11 17:04:43 +09006336 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6337 // Policy already enforced.
6338 return;
6339 }
paulhuaf50d7d2020-12-24 19:47:34 +08006340 final long ident = Binder.clearCallingIdentity();
6341 try {
6342 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6343 // If UID is restricted, don't allow them to bring up metered APNs.
6344 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6345 }
6346 } finally {
6347 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006348 }
6349 }
6350
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006351 @Override
6352 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006353 PendingIntent operation, @NonNull String callingPackageName,
6354 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006355 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006356 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006357 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006358 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6359 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006360 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006361 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006362 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006363 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006364 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006365 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6366 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006367
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006368 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006369 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006370 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6371 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006372 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006373 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6374 nri));
6375 return networkRequest;
6376 }
6377
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006378 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6379 mHandler.sendMessageDelayed(
6380 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006381 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006382 }
6383
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006384 @Override
6385 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006386 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006387 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006388 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006389 }
6390
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006391 // In order to implement the compatibility measure for pre-M apps that call
6392 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6393 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6394 // This ensures it has permission to do so.
6395 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6396 if (nc == null) {
6397 return false;
6398 }
6399 int[] transportTypes = nc.getTransportTypes();
6400 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6401 return false;
6402 }
6403 try {
6404 mContext.enforceCallingOrSelfPermission(
6405 android.Manifest.permission.ACCESS_WIFI_STATE,
6406 "ConnectivityService");
6407 } catch (SecurityException e) {
6408 return false;
6409 }
6410 return true;
6411 }
6412
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006413 @Override
6414 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006415 Messenger messenger, IBinder binder,
6416 @NetworkCallback.Flag int callbackFlags,
6417 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006418 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006419 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6420 enforceAccessPermission();
6421 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006422
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006423 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006424 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006425 Binder.getCallingPid(), callingUid, callingPackageName);
6426 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006427 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6428 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6429 // onLost and onAvailable callbacks when networks move in and out of the background.
6430 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6431 // can't request networks.
6432 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006433 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006434
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006435 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006436 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006437 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006438 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006439 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006440 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006441
6442 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6443 return networkRequest;
6444 }
6445
6446 @Override
6447 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006448 PendingIntent operation, @NonNull String callingPackageName,
6449 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006450 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006451 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006452 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6453 enforceAccessPermission();
6454 }
lucasline117e2e2019-10-22 18:27:33 +08006455 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006456 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006457 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006458 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006459 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006460
6461 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006462 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006463 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6464 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006465 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006466
WeiZhang1cc3f172021-06-03 19:02:04 -05006467 mHandler.sendMessage(mHandler.obtainMessage(
6468 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006469 }
6470
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006471 /** Returns the next Network provider ID. */
6472 public final int nextNetworkProviderId() {
6473 return mNextNetworkProviderId.getAndIncrement();
6474 }
6475
Erik Kline0c04b742016-07-07 16:50:58 +09006476 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006477 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006478 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006479 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006480 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006481 }
6482
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006483 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6484 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006485 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6486 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6487 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006488 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006489 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006490 return;
6491 }
6492
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006493 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6494 mNetworkProviderInfos.put(npi.messenger, npi);
6495 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006496 }
6497
6498 @Override
6499 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006500 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006501 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006502 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006503 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006504 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6505 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006506 }
6507
6508 @Override
6509 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006510 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006511 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006512 }
6513
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006514 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006515 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006516 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6517 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006518 Objects.requireNonNull(score);
6519 Objects.requireNonNull(caps);
6520 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006521 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006522 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006523 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6524 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006525 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6526 }
6527
Chalard Jeanbb902a52021-08-18 01:35:19 +09006528 private void updateOfferScore(final NetworkOffer offer) {
6529 final boolean yieldToBadWiFi =
6530 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6531 final NetworkOffer newOffer = new NetworkOffer(
6532 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6533 offer.caps, offer.callback, offer.providerId);
6534 if (offer.equals(newOffer)) return;
6535 handleRegisterNetworkOffer(newOffer);
6536 }
6537
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006538 @Override
6539 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6541 }
6542
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006543 private void handleUnregisterNetworkProvider(Messenger messenger) {
6544 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6545 if (npi == null) {
6546 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006547 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006548 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006549 // Unregister all the offers from this provider
6550 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6551 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006552 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006553 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6554 toRemove.add(noi);
6555 }
6556 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006557 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006558 handleUnregisterNetworkOffer(noi);
6559 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006560 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006561 }
6562
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006563 @Override
James Mattisf7027322020-12-13 16:28:14 -08006564 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006565 if (request.hasTransport(TRANSPORT_TEST)) {
6566 enforceNetworkFactoryOrTestNetworksPermission();
6567 } else {
6568 enforceNetworkFactoryPermission();
6569 }
James Mattisf7027322020-12-13 16:28:14 -08006570 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6571 if (nri != null) {
6572 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6573 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6574 mHandler.post(() -> handleReleaseNetworkRequest(
6575 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6576 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006577 }
6578
Paul Jensen1f567382015-02-13 14:18:39 -05006579 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6580 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006581 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006582 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006583 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006584 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006585 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006586
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006587 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006588 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006589 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006590
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006591 // UID ranges for users that are currently blocked by VPNs.
6592 // This array is accessed and iterated on multiple threads without holding locks, so its
6593 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6594 // (on the handler thread).
6595 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6596
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006597 // Must only be accessed on the handler thread
6598 @NonNull
6599 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6600
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006601 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006602 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006603
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006604 // Current OEM network preferences. This object must only be written to on the handler thread.
6605 // Since it is immutable and always non-null, other threads may read it if they only care
6606 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006607 @NonNull
6608 private OemNetworkPreferences mOemNetworkPreferences =
6609 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006610 // Current per-profile network preferences. This object follows the same threading rules as
6611 // the OEM network preferences above.
6612 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006613 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6614 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006615
paulhu51f77dc2021-06-07 02:34:20 +00006616 // A set of UIDs that should use mobile data preferentially if available. This object follows
6617 // the same threading rules as the OEM network preferences above.
6618 @NonNull
6619 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6620
James Mattiscb1e0362021-04-06 17:07:42 -07006621 // OemNetworkPreferences activity String log entries.
6622 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6623 @NonNull
6624 private final LocalLog mOemNetworkPreferencesLogs =
6625 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6626
James Mattis02220e22021-03-13 19:27:21 -08006627 /**
6628 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6629 * @param packageName the package name to check existence of a mapping for.
6630 * @return true if a mapping exists, false otherwise
6631 */
6632 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6633 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6634 }
6635
James Mattise3ef1912020-12-20 11:09:58 -08006636 // The always-on request for an Internet-capable network that apps without a specific default
6637 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006638 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006639 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006640 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006641 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006642 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006643 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006644 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006645
James Mattisd31bdfa2020-12-23 16:37:26 -08006646 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6647 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6648 }
6649
6650 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006651 * Return the default network request currently tracking the given uid.
6652 * @param uid the uid to check.
6653 * @return the NetworkRequestInfo tracking the given uid.
6654 */
6655 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006656 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006657 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006658 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006659 // Checking the first request is sufficient as only multilayer requests will have more
6660 // than one request and for multilayer, all requests will track the same uids.
6661 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006662 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006663 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006664 highestPriorityNri = nri;
6665 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006666 }
6667 }
paulhuaa0743d2021-05-26 21:56:03 +08006668 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006669 }
6670
6671 /**
6672 * Get a copy of the network requests of the default request that is currently tracking the
6673 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006674 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6675 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006676 * @param requestorUid the uid to check the default for.
6677 * @param requestorPackageName the requestor's package name.
6678 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6679 */
6680 @NonNull
6681 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006682 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006683 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006684 getDefaultRequestTrackingUid(asUid).mRequests,
6685 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006686 }
6687
6688 /**
6689 * Copy the given nri's NetworkRequest collection.
6690 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006691 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6692 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006693 * @param requestorUid the uid to set on the copied collection.
6694 * @param requestorPackageName the package name to set on the copied collection.
6695 * @return the copied NetworkRequest collection.
6696 */
6697 @NonNull
6698 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006699 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6700 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006701 final List<NetworkRequest> requests = new ArrayList<>();
6702 for (final NetworkRequest nr : requestsToCopy) {
6703 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006704 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006705 nr.legacyType, nextNetworkRequestId(), nr.type));
6706 }
6707 return requests;
6708 }
6709
6710 @NonNull
6711 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006712 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6713 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006714 // These capabilities are for a TRACK_DEFAULT callback, so:
6715 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6716 // mDefaultRequest and a per-UID default request.
6717 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006718 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006719 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006720 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6721 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006722 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006723 restrictRequestUidsForCallerAndSetRequestorInfo(
6724 netCap, requestorUid, requestorPackageName);
6725 return netCap;
6726 }
6727
6728 /**
6729 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6730 * @param nr the network request to check for equality against.
6731 * @return the nri if one exists, null otherwise.
6732 */
6733 @Nullable
6734 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6735 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6736 if (nri.getNetworkRequestForCallback().equals(nr)) {
6737 return nri;
6738 }
6739 }
6740 return null;
6741 }
6742
6743 /**
6744 * Check if an nri is currently being managed by per-app default networking.
6745 * @param nri the nri to check.
6746 * @return true if this nri is currently being managed by per-app default networking.
6747 */
6748 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6749 // nri.mRequests.get(0) is only different from the original request filed in
6750 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6751 // functionality therefore if these two don't match, it means this particular nri is
6752 // currently being managed by a per-app default.
6753 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6754 }
6755
6756 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006757 * Determine if an nri is a managed default request that disallows default networking.
6758 * @param nri the request to evaluate
6759 * @return true if device-default networking is disallowed
6760 */
6761 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6762 // Check if this nri is a managed default that supports the default network at its
6763 // lowest priority request.
6764 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6765 final NetworkCapabilities lowestPriorityNetCap =
6766 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6767 return isPerAppDefaultRequest(nri)
6768 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6769 lowestPriorityNetCap));
6770 }
6771
Erik Kline05f2b402015-04-30 12:58:40 +09006772 // Request used to optionally keep mobile data active even when higher
6773 // priority networks like Wi-Fi are active.
6774 private final NetworkRequest mDefaultMobileDataRequest;
6775
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006776 // Request used to optionally keep wifi data active even when higher
6777 // priority networks like ethernet are active.
6778 private final NetworkRequest mDefaultWifiRequest;
6779
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006780 // Request used to optionally keep vehicle internal network always active
6781 private final NetworkRequest mDefaultVehicleRequest;
6782
James Mattisd31bdfa2020-12-23 16:37:26 -08006783 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6784 // network with no service. This NAI should never be matched against, nor should any public API
6785 // ever return the associated network. For this reason, this NAI is not in the list of available
6786 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6787 // default requests that don't support using the device default network which will ultimately
6788 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6789 @VisibleForTesting
6790 final NetworkAgentInfo mNoServiceNetwork;
6791
Chalard Jean5b409c72021-02-04 13:12:59 +09006792 // The NetworkAgentInfo currently satisfying the default request, if any.
6793 private NetworkAgentInfo getDefaultNetwork() {
6794 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006795 }
6796
James Mattis2516da32021-01-31 17:06:19 -08006797 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006798 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006799 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6800 // Currently, all network requests will have the same uids therefore checking the first
6801 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006802 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006803 if (null == uids) {
6804 continue;
6805 }
6806 for (final UidRange range : uids) {
6807 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006808 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006809 highestPriorityNri = nri;
6810 }
James Mattis2516da32021-01-31 17:06:19 -08006811 }
6812 }
6813 }
paulhuaa0743d2021-05-26 21:56:03 +08006814 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006815 }
6816
Varun Ananddf569952019-02-06 10:13:38 -08006817 @Nullable
6818 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6819 return nai != null ? nai.network : null;
6820 }
6821
6822 private void ensureRunningOnConnectivityServiceThread() {
6823 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6824 throw new IllegalStateException(
6825 "Not running on ConnectivityService thread: "
6826 + Thread.currentThread().getName());
6827 }
6828 }
6829
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006830 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006831 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6832 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006833 }
6834
Chalard Jean29d06db2018-05-02 21:14:54 +09006835 /**
6836 * Register a new agent with ConnectivityService to handle a network.
6837 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006838 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006839 * @param networkInfo the initial info associated with this network. It can be updated later :
6840 * see {@link #updateNetworkInfo}.
6841 * @param linkProperties the initial link properties of this network. They can be updated
6842 * later : see {@link #updateLinkProperties}.
6843 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006844 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006845 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006846 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006847 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006848 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006849 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006850 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006851 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006852 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006853 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6854 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006855 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6856 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6857 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006858 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006859 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006860 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6861 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006862 } else {
6863 enforceNetworkFactoryPermission();
6864 }
6865
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006866 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006867 final long token = Binder.clearCallingIdentity();
6868 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006869 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006870 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006871 } finally {
6872 Binder.restoreCallingIdentity(token);
6873 }
6874 }
6875
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006876 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006877 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006878 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6879 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006880 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006881 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6882 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6883 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6884 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08006885 networkCapabilities.restrictCapabilitiesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006886 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006887
Rubin Xuffd77d82017-09-05 18:40:49 +01006888 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006889
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006890 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006891 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006892 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006893 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006894 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6895 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006896
6897 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006898 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006899 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006900 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6901
Chalard Jeanf2da1772018-04-26 16:16:10 +09006902 final String extraInfo = networkInfo.getExtraInfo();
6903 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006904 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006905 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006906 mDeps.getNetworkStack().makeNetworkMonitor(
6907 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006908 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6909 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006910 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006911 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006912 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006913 }
6914
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006915 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6916 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006917 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006918 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006919 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006920 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006921 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006922
6923 try {
6924 networkMonitor.start();
6925 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006926 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006927 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006928 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006929 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006930 updateNetworkInfo(nai, networkInfo);
6931 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006932 }
6933
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006934 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6935 @NonNull public final NetworkOffer offer;
6936
6937 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6938 this.offer = offer;
6939 }
6940
6941 @Override
6942 public void binderDied() {
6943 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6944 }
6945 }
6946
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006947 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6948 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6949 if (npi.providerId == providerId) return true;
6950 }
6951 return false;
6952 }
6953
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006954 /**
6955 * Register or update a network offer.
6956 * @param newOffer The new offer. If the callback member is the same as an existing
6957 * offer, it is an update of that offer.
6958 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09006959 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006960 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6961 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006962 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006963 // This may actually happen if a provider updates its score or registers and then
6964 // immediately unregisters. The offer would still be in the handler queue, but the
6965 // provider would have been removed.
6966 if (DBG) log("Received offer from an unregistered provider");
6967 return;
6968 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006969 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6970 if (null != existingOffer) {
6971 handleUnregisterNetworkOffer(existingOffer);
6972 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006973 if (DBG) {
6974 // handleUnregisterNetworkOffer has already logged the old offer
6975 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
6976 }
6977 } else {
6978 if (DBG) {
6979 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
6980 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006981 }
6982 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6983 try {
Chalard Jean30689b82021-03-22 22:44:02 +09006984 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006985 } catch (RemoteException e) {
6986 noi.binderDied();
6987 return;
6988 }
6989 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09006990 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006991 }
6992
6993 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6994 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09006995 if (DBG) {
6996 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
6997 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07006998
6999 // If the provider removes the offer and dies immediately afterwards this
7000 // function may be called twice in a row, but the array will no longer contain
7001 // the offer.
7002 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007003 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007004 }
7005
7006 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7007 @NonNull final INetworkOfferCallback callback) {
7008 ensureRunningOnConnectivityServiceThread();
7009 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007010 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007011 }
7012 return null;
7013 }
7014
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007015 /**
7016 * Called when receiving LinkProperties directly from a NetworkAgent.
7017 * Stores into |nai| any data coming from the agent that might also be written to the network's
7018 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7019 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007020 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007021 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007022 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7023 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007024 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007025 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007026 }
7027
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007028 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007029 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007030 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007031
Lorenzo Colittid523d142020-04-01 20:16:30 +09007032 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7033 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7034 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007035 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007036
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007037 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007038
7039 // update filtering rules, need to happen after the interface update so netd knows about the
7040 // new interface (the interface name -> index map becomes initialized)
7041 updateVpnFiltering(newLp, oldLp, networkAgent);
7042
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007043 updateMtu(newLp, oldLp);
7044 // TODO - figure out what to do for clat
7045// for (LinkProperties lp : newLp.getStackedLinks()) {
7046// updateMtu(lp, null);
7047// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007048 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007049 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7050 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007051
Erik Klineb9888902016-04-05 13:30:49 +09007052 updateRoutes(newLp, oldLp, netId);
7053 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007054 // Make sure LinkProperties represents the latest private DNS status.
7055 // This does not need to be done before updateDnses because the
7056 // LinkProperties are not the source of the private DNS configuration.
7057 // updateDnses will fetch the private DNS configuration from DnsManager.
7058 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007059
Chalard Jean5b409c72021-02-04 13:12:59 +09007060 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007061 handleApplyDefaultProxy(newLp.getHttpProxy());
7062 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007063 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007064 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007065
7066 updateWakeOnLan(newLp);
7067
Hai Shalome58bdc62021-01-11 18:45:34 -08007068 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7069 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7070 // does, it needs to be merged here.
7071 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7072 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007073
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007074 // TODO - move this check to cover the whole function
7075 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007076 synchronized (networkAgent) {
7077 networkAgent.linkProperties = newLp;
7078 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007079 // Start or stop DNS64 detection and 464xlat according to network state.
7080 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007081 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007082 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7083 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007084 if (networkAgent.everConnected) {
7085 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7086 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007087 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007088
7089 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007090 }
7091
Hai Shalome58bdc62021-01-11 18:45:34 -08007092 /**
7093 * @param naData captive portal data from NetworkAgent
7094 * @param apiData captive portal data from capport API
7095 */
7096 @Nullable
7097 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7098 CaptivePortalData apiData) {
7099 if (naData == null || apiData == null) {
7100 return naData == null ? apiData : naData;
7101 }
7102 final CaptivePortalData.Builder captivePortalBuilder =
7103 new CaptivePortalData.Builder(naData);
7104
7105 if (apiData.isCaptive()) {
7106 captivePortalBuilder.setCaptive(true);
7107 }
7108 if (apiData.isSessionExtendable()) {
7109 captivePortalBuilder.setSessionExtendable(true);
7110 }
7111 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7112 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7113 // otherwise data would be inconsistent. Prefer the capport API info if present,
7114 // as it can generally be refreshed more often.
7115 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7116 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7117 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7118 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7119 // No source has time / bytes remaining information: surface the newest refresh time
7120 // for other fields
7121 captivePortalBuilder.setRefreshTime(
7122 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7123 }
7124
Hai Shalom7c6ab402021-02-04 19:34:06 -08007125 // Prioritize the user portal URL from the network agent if the source is authenticated.
7126 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7127 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7128 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7129 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007130 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007131 // Prioritize the venue information URL from the network agent if the source is
7132 // authenticated.
7133 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7134 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7135 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7136 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007137 }
7138 return captivePortalBuilder.build();
7139 }
7140
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007141 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007142 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007143 // marks on unsupported interfaces is harmless.
7144 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7145 return;
7146 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007147
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007148 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7149 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7150
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007151 // Mask/mark of zero will not detect anything interesting.
7152 // Don't install rules unless both values are nonzero.
7153 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007154 return;
7155 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007156
7157 final String prefix = "iface:" + iface;
7158 try {
7159 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007160 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007161 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007162 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007163 }
7164 } catch (Exception e) {
7165 loge("Exception modifying wakeup packet monitoring: " + e);
7166 }
7167
Joel Scherpelza235a812017-05-22 13:47:41 +09007168 }
7169
Chalard Jean9589e722019-11-19 19:03:53 +09007170 private void updateInterfaces(final @Nullable LinkProperties newLp,
7171 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007172 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007173 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007174 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7175 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007176 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007177 for (final String iface : interfaceDiff.added) {
7178 try {
7179 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007180 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007181 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007182 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7183 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007184 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007185 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007186 }
Paul Jensenbff73492014-04-28 10:33:11 -04007187 }
7188 }
Chalard Jean9589e722019-11-19 19:03:53 +09007189 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007190 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007191 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007192 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007193 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007194 } catch (Exception e) {
7195 loge("Exception removing interface: " + e);
7196 }
7197 }
7198 }
7199
Tyler Weare4314862019-12-05 14:55:30 -08007200 // TODO: move to frameworks/libs/net.
7201 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7202 final String nextHop;
7203
7204 switch (route.getType()) {
7205 case RouteInfo.RTN_UNICAST:
7206 if (route.hasGateway()) {
7207 nextHop = route.getGateway().getHostAddress();
7208 } else {
7209 nextHop = INetd.NEXTHOP_NONE;
7210 }
7211 break;
7212 case RouteInfo.RTN_UNREACHABLE:
7213 nextHop = INetd.NEXTHOP_UNREACHABLE;
7214 break;
7215 case RouteInfo.RTN_THROW:
7216 nextHop = INetd.NEXTHOP_THROW;
7217 break;
7218 default:
7219 nextHop = INetd.NEXTHOP_NONE;
7220 break;
7221 }
7222
7223 final RouteInfoParcel rip = new RouteInfoParcel();
7224 rip.ifName = route.getInterface();
7225 rip.destination = route.getDestination().toString();
7226 rip.nextHop = nextHop;
7227 rip.mtu = route.getMtu();
7228
7229 return rip;
7230 }
7231
Paul Jensene0fd4a82014-08-06 15:51:33 -04007232 /**
7233 * Have netd update routes from oldLp to newLp.
7234 * @return true if routes changed between oldLp and newLp
7235 */
7236 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007237 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007238 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7239 new CompareOrUpdateResult<>(
7240 oldLp != null ? oldLp.getAllRoutes() : null,
7241 newLp != null ? newLp.getAllRoutes() : null,
7242 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007243
7244 // add routes before removing old in case it helps with continuous connectivity
7245
Chalard Jean9dd11612018-06-04 16:52:49 +09007246 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007247 for (RouteInfo route : routeDiff.added) {
7248 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007249 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007250 try {
Tyler Weare4314862019-12-05 14:55:30 -08007251 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007252 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007253 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007254 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007255 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007256 }
7257 }
7258 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007259 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007260 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007261 try {
Tyler Weare4314862019-12-05 14:55:30 -08007262 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007263 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007264 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007265 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007266 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007267 }
7268 }
7269
7270 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007271 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007272 try {
Tyler Weare4314862019-12-05 14:55:30 -08007273 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007274 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007275 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007276 }
7277 }
Tyler Weare4314862019-12-05 14:55:30 -08007278
7279 for (RouteInfo route : routeDiff.updated) {
7280 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7281 try {
7282 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7283 } catch (Exception e) {
7284 loge("Exception in networkUpdateRouteParcel: " + e);
7285 }
7286 }
7287 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7288 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007289 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007290
Erik Klineb9888902016-04-05 13:30:49 +09007291 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7292 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7293 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007294 }
Erik Klineb9888902016-04-05 13:30:49 +09007295
Erik Kline31b4a9e2018-01-11 21:07:29 +09007296 if (DBG) {
7297 final Collection<InetAddress> dnses = newLp.getDnsServers();
7298 log("Setting DNS servers for network " + netId + " to " + dnses);
7299 }
Erik Klineb9888902016-04-05 13:30:49 +09007300 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007301 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007302 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007303 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007304 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007305 }
Erik Kline54e35c02017-04-07 15:29:29 +09007306 }
7307
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007308 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7309 NetworkAgentInfo nai) {
7310 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7311 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7312 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7313 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7314
7315 if (!wasFiltering && !needsFiltering) {
7316 // Nothing to do.
7317 return;
7318 }
7319
7320 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7321 // Nothing changed.
7322 return;
7323 }
7324
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007325 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007326 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007327 // TODO: this create a window of opportunity for apps to receive traffic between the time
7328 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007329 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007330 // old rules are being removed.
7331 if (wasFiltering) {
7332 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7333 }
7334 if (needsFiltering) {
7335 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7336 }
7337 }
7338
Valentin Iftime9fa35092019-09-24 13:32:13 +02007339 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007340 if (mWolSupportedInterfaces == null) {
7341 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007342 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007343 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007344 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7345 }
7346
Luke Huangb913c812018-08-24 20:33:16 +08007347 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007348 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007349 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007350 }
7351 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007352 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007353 }
Luke Huangb913c812018-08-24 20:33:16 +08007354 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007355 }
7356
Chalard Jean62edfd82019-12-02 18:39:29 +09007357 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7358 @NonNull final NetworkCapabilities newNc) {
7359 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7360 final int newPermission = getNetworkPermission(newNc);
7361 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7362 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007363 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007364 } catch (RemoteException | ServiceSpecificException e) {
7365 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007366 }
7367 }
7368 }
7369
Paul Jensen53f08952015-06-16 14:27:36 -04007370 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007371 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7372 * Stores into |nai| any data coming from the agent that might also be written to the network's
7373 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7374 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007375 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007376 */
7377 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007378 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7379 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7380 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7381 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007382 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7383 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7384 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7385 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7386 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007387 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007388 }
7389
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007390 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007391 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007392 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007393 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007394 underlyingNetworks = underlyingNetworksOrDefault(
7395 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007396 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007397 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7398 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007399 // metered if any underlying is metered, or originally declared metered by the agent.
7400 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007401 boolean roaming = false; // roaming if any underlying is roaming
7402 boolean congested = false; // congested if any underlying is congested
7403 boolean suspended = true; // suspended if all underlying are suspended
7404
7405 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007406 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007407 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007408 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007409 for (Network underlyingNetwork : underlyingNetworks) {
7410 final NetworkAgentInfo underlying =
7411 getNetworkAgentInfoForNetwork(underlyingNetwork);
7412 if (underlying == null) continue;
7413
7414 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7415 hadUnderlyingNetworks = true;
7416 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007417 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007418 }
7419
7420 // Merge capabilities of this underlying network. For bandwidth, assume the
7421 // worst case.
7422 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7423 underlyingCaps.getLinkDownstreamBandwidthKbps());
7424 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7425 underlyingCaps.getLinkUpstreamBandwidthKbps());
7426 // If this underlying network is metered, the VPN is metered (it may cost money
7427 // to send packets on this network).
7428 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7429 // If this underlying network is roaming, the VPN is roaming (the billing structure
7430 // is different than the usual, local one).
7431 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7432 // If this underlying network is congested, the VPN is congested (the current
7433 // condition of the network affects the performance of this network).
7434 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7435 // If this network is not suspended, the VPN is not suspended (the VPN
7436 // is able to transfer some data).
7437 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007438 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007439 }
7440 }
7441 if (!hadUnderlyingNetworks) {
7442 // No idea what the underlying networks are; assume reasonable defaults
7443 metered = true;
7444 roaming = false;
7445 congested = false;
7446 suspended = false;
7447 }
7448
lifrade6c2a2021-03-04 14:08:08 +08007449 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007450 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7451 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7452 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7453 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7454 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7455 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007456 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007457 }
7458
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007459 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007460 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7461 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7462 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007463 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007464 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007465 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007466 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007467 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7468 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007469 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007470 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007471 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007472 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007473 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7474 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007475 // does not cause any request (that is not a listen) currently matching that agent to
7476 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007477 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007478 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007479 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007480 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007481 }
7482
Paul Jensen53f08952015-06-16 14:27:36 -04007483 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007484 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007485 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007486 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007487 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007488 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007489 }
Paul Jensende49eb12015-06-25 15:30:08 -04007490 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007491 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007492 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007493 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007494 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007495 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007496 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007497 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007498 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007499 }
lucaslin2240ef62019-03-12 13:08:03 +08007500 if (nai.partialConnectivity) {
7501 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7502 } else {
7503 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7504 }
lucasline117e2e2019-10-22 18:27:33 +08007505 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007506
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007507 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007508 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7509 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007510 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007511 }
7512
Lorenzo Colittibd079452021-07-02 11:47:57 +09007513 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007514 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7515 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007516 }
7517
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007518 return newNc;
7519 }
7520
Lorenzo Colitti44840702021-01-11 22:27:57 +09007521 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7522 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7523 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7524 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7525 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7526 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7527 if (prevSuspended != suspended) {
7528 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7529 // onResumed have been removed.
7530 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7531 : ConnectivityManager.CALLBACK_RESUMED);
7532 }
7533 if (prevSuspended != suspended || prevRoaming != roaming) {
7534 // updateNetworkInfo will mix in the suspended info from the capabilities and
7535 // take appropriate action for the network having possibly changed state.
7536 updateNetworkInfo(nai, nai.networkInfo);
7537 }
7538 }
7539
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007540 /**
7541 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7542 *
7543 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7544 * capabilities we manage and store in {@code nai}, such as validated status and captive
7545 * portal status)
7546 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7547 * potentially triggers rematches.
7548 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7549 * change.)
7550 *
7551 * @param oldScore score of the network before any of the changes that prompted us
7552 * to call this function.
7553 * @param nai the network having its capabilities updated.
7554 * @param nc the new network capabilities.
7555 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007556 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7557 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007558 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007559 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007560 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007561 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007562
Chalard Jeanb2a49912018-01-16 18:43:05 +09007563 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007564 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007565
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007566 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007567 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7568 // the change we're processing can't affect any requests, it can only affect the listens
7569 // on this network. We might have been called by rematchNetworkAndRequests when a
7570 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007571 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007572 } else {
7573 // If the requestable capabilities have changed or the score changed, we can't have been
7574 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007575 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007576 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007577 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007578 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007579
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007580 final boolean oldMetered = prevNc.isMetered();
7581 final boolean newMetered = newNc.isMetered();
7582 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007583
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007584 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007585 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7586 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007587 }
junyulaif2c67e42018-08-07 19:50:45 +08007588
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007589 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7590 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007591
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007592 // Report changes that are interesting for network statistics tracking.
7593 if (meteredChanged || roamingChanged) {
7594 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007595 }
7596
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007597 // This network might have been underlying another network. Propagate its capabilities.
7598 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007599
7600 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007601 mDnsManager.updateTransportsForNetwork(
7602 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007603 }
lucaslin53e8a262021-06-08 01:43:59 +08007604
7605 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007606 }
7607
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007608 /** Convenience method to update the capabilities for a given network. */
7609 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7610 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7611 }
7612
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007613 /**
7614 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7615 * network.
7616 *
7617 * Ingress interface filtering enforces that all apps under the given network can only receive
7618 * packets from the network's interface (and loopback). This is important for VPNs because
7619 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7620 * non-VPN interfaces.
7621 *
7622 * As a result, this method should return true iff
7623 * 1. the network is an app VPN (not legacy VPN)
7624 * 2. the VPN does not allow bypass
7625 * 3. the VPN is fully-routed
7626 * 4. the VPN interface is non-null
7627 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007628 * @see INetd#firewallAddUidInterfaceRules
7629 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007630 */
7631 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7632 LinkProperties lp) {
7633 if (nc == null || lp == null) return false;
7634 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007635 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007636 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007637 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007638 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7639 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007640 }
7641
Chiachang Wang28afaff2020-12-10 22:24:47 +08007642 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7643 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7644 int index = 0;
7645 for (UidRange range : ranges) {
7646 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7647 index++;
7648 }
7649 return stableRanges;
7650 }
7651
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007652 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7653 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7654 for (int i = 0; i < ranges.length; i++) {
7655 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7656 }
7657 return stableRanges;
7658 }
7659
Ken Chen5e65a852020-12-24 12:59:10 +08007660 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7661 int[] exemptUids) {
7662 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7663 try {
7664 mNetd.socketDestroy(ranges, exemptUids);
7665 } catch (Exception e) {
7666 loge("Exception in socket destroy: ", e);
7667 }
7668 }
7669 }
7670
paulhuaa0743d2021-05-26 21:56:03 +08007671 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007672 int[] exemptUids = new int[2];
7673 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7674 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7675 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7676 exemptUids[0] = VPN_UID;
7677 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7678 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7679
7680 maybeCloseSockets(nai, ranges, exemptUids);
7681 try {
7682 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007683 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007684 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007685 } else {
paulhu0e79d952021-06-09 16:11:35 +08007686 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007687 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007688 }
7689 } catch (Exception e) {
7690 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7691 " on netId " + nai.network.netId + ". " + e);
7692 }
7693 maybeCloseSockets(nai, ranges, exemptUids);
7694 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007695
lucaslin53e8a262021-06-08 01:43:59 +08007696 private boolean isProxySetOnAnyDefaultNetwork() {
7697 ensureRunningOnConnectivityServiceThread();
7698 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7699 final NetworkAgentInfo nai = nri.getSatisfier();
7700 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7701 return true;
7702 }
7703 }
7704 return false;
7705 }
7706
7707 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7708 NetworkCapabilities newNc) {
7709 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7710 // the proxy might be changed since the default network satisfied by the apps might also
7711 // changed.
7712 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7713 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007714 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7715 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7716 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007717 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7718 mProxyTracker.sendProxyBroadcast();
7719 }
7720 }
7721
Chalard Jeanb2a49912018-01-16 18:43:05 +09007722 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7723 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007724 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7725 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007726 if (null == prevRanges) prevRanges = new ArraySet<>();
7727 if (null == newRanges) newRanges = new ArraySet<>();
7728 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7729
7730 prevRanges.removeAll(newRanges);
7731 newRanges.removeAll(prevRangesCopy);
7732
7733 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007734 // When updating the VPN uid routing rules, add the new range first then remove the old
7735 // range. If old range were removed first, there would be a window between the old
7736 // range being removed and the new range being added, during which UIDs contained
7737 // in both ranges are not subject to any VPN routing rules. Adding new range before
7738 // removing old range works because, unlike the filtering rules below, it's possible to
7739 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007740 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7741 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7742 // [1-5] & [1-2],[4-5] == [3]
7743 // Then we can do:
7744 // maybeCloseSockets([3])
7745 // mNetd.networkAddUidRanges([1-2],[4-5])
7746 // mNetd.networkRemoveUidRanges([1-5])
7747 // maybeCloseSockets([3])
7748 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7749 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007750 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007751 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007752 }
7753 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007754 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007755 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007756 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7757 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7758 final String iface = nai.linkProperties.getInterfaceName();
7759 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007760 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007761 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7762 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7763 // were added first and then newRanges got removed later, there would be only one uid
7764 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7765 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7766 // Note that this is in contrast with the (more robust) update of VPN routing rules
7767 // above, where the addition of new ranges happens before the removal of old ranges.
7768 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7769 // to be removed will never overlap with the new range to be added.
7770 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007771 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007772 }
7773 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007774 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007775 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007776 } catch (Exception e) {
7777 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007778 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007779 }
7780 }
7781
Hugo Benichi9d35b752017-09-01 01:23:32 +00007782 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007783 ensureRunningOnConnectivityServiceThread();
7784
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007785 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007786 // Ignore updates for disconnected networks
7787 return;
7788 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007789 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007790 log("Update of LinkProperties for " + nai.toShortString()
7791 + "; created=" + nai.created
7792 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007793 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007794 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7795 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007796 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007797 }
7798
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007799 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7800 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007801 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007802 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007803 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007804 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7805 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7806 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007807 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7808 // need to be sent as a separate extra.
7809 final NetworkRequest req = nri.isMultilayerRequest()
7810 ? nri.getActiveRequest()
7811 // Non-multilayer listen requests do not have an active request
7812 : nri.mRequests.get(0);
7813 if (req == null) {
7814 Log.wtf(TAG, "No request in NRI " + nri);
7815 }
7816 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007817 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007818 sendIntent(nri.mPendingIntent, intent);
7819 }
7820 // else not handled
7821 }
7822
7823 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7824 mPendingIntentWakeLock.acquire();
7825 try {
7826 if (DBG) log("Sending " + pendingIntent);
7827 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7828 } catch (PendingIntent.CanceledException e) {
7829 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7830 mPendingIntentWakeLock.release();
7831 releasePendingNetworkRequest(pendingIntent);
7832 }
7833 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7834 }
7835
7836 @Override
7837 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7838 String resultData, Bundle resultExtras) {
7839 if (DBG) log("Finished sending " + pendingIntent);
7840 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007841 // Release with a delay so the receiving client has an opportunity to put in its
7842 // own request.
7843 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007844 }
7845
James Mattis212df9e2020-12-03 19:57:41 -08007846 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7847 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7848 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007849 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007850 // Default request has no msgr. Also prevents callbacks from being invoked for
7851 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7852 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7853 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007854 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007855 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007856 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007857 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007858 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007859 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007860 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007861 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7862 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007863 }
Roshan Pius951c0032020-12-22 15:10:42 -08007864 final boolean includeLocationSensitiveInfo =
7865 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007866 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007867 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007868 final NetworkCapabilities nc =
7869 networkCapabilitiesRestrictedForCallerPermissions(
7870 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7871 putParcelable(
7872 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007873 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007874 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007875 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007876 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007877 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7878 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007879 // For this notification, arg1 contains the blocked status.
7880 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007881 break;
7882 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007883 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007884 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007885 break;
7886 }
7887 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007888 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007889 final NetworkCapabilities netCap =
7890 networkCapabilitiesRestrictedForCallerPermissions(
7891 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7892 putParcelable(
7893 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007894 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007895 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007896 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007897 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007898 break;
7899 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007900 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007901 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7902 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007903 break;
7904 }
junyulaif2c67e42018-08-07 19:50:45 +08007905 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007906 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007907 msg.arg1 = arg1;
7908 break;
7909 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007910 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007911 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007912 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007913 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007914 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007915 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007916 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007917 }
James Mattis45d81842021-01-10 14:24:24 -08007918 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007919 } catch (RemoteException e) {
7920 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007921 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007922 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007923 }
7924
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007925 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7926 bundle.putParcelable(t.getClass().getSimpleName(), t);
7927 }
7928
Chalard Jean0702f982021-09-16 21:50:07 +09007929 /**
7930 * Returns whether reassigning a request from an NAI to another can be done gracefully.
7931 *
7932 * When a request should be assigned to a new network, it is normally lingered to give
7933 * time for apps to gracefully migrate their connections. When both networks are on the same
7934 * radio, but that radio can't do time-sharing efficiently, this may end up being
7935 * counter-productive because any traffic on the old network may drastically reduce the
7936 * performance of the new network.
7937 * The stack supports a configuration to let modem vendors state that their radio can't
7938 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
7939 * from one cell network to another can't be done gracefully.
7940 *
7941 * @param oldNai the old network serving the request
7942 * @param newNai the new network serving the request
7943 * @return whether the switch can be graceful
7944 */
7945 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
7946 @NonNull final NetworkAgentInfo newSatisfier) {
7947 if (mCellularRadioTimesharingCapable) return true;
7948 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7949 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7950 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
7951 }
7952
Paul Jensenaf94b982014-09-30 15:37:41 -04007953 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007954 if (nai.numRequestNetworkRequests() != 0) {
7955 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7956 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007957 // Ignore listening and track default requests.
7958 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007959 loge("Dead network still had at least " + nr);
7960 break;
7961 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007962 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007963 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007964 }
7965
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007966 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7967 if (oldNetwork == null) {
7968 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7969 return;
7970 }
Chalard Jean49707572019-12-10 21:07:02 +09007971 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007972
7973 // If we get here it means that the last linger timeout for this network expired. So there
7974 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08007975 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007976
Lorenzo Colitti2666be82016-09-09 18:48:56 +09007977 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007978 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007979 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007980 } else {
junyulai0ac374f2020-12-14 18:41:52 +08007981 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007982 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007983 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007984 }
7985
James Mattise3ef1912020-12-20 11:09:58 -08007986 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7987 boolean isDefaultChanged = false;
7988 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7989 final NetworkReassignment.RequestReassignment reassignment =
7990 changes.getReassignment(defaultRequestInfo);
7991 if (null == reassignment) {
7992 continue;
7993 }
7994 // reassignment only contains those instances where the satisfying network changed.
7995 isDefaultChanged = true;
7996 // Notify system services of the new default.
7997 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7998 }
Chiachang Wang087fd272018-09-28 22:42:48 +08007999
James Mattise3ef1912020-12-20 11:09:58 -08008000 if (isDefaultChanged) {
8001 // Hold a wakelock for a short time to help apps in migrating to a new default.
8002 scheduleReleaseNetworkTransitionWakelock();
8003 }
8004 }
8005
8006 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8007 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8008 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8009 if (DBG) {
8010 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8011 }
Chalard Jean8e382112019-12-03 20:45:30 +09008012
James Mattisd31bdfa2020-12-23 16:37:26 -08008013 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8014 if (newDefaultNetwork != null) {
8015 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008016 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008017
James Mattisd31bdfa2020-12-23 16:37:26 -08008018 // Set an app level managed default and return since further processing only applies to the
8019 // default network.
8020 if (mDefaultRequest != nri) {
8021 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8022 return;
8023 }
8024
8025 makeDefaultNetwork(newDefaultNetwork);
8026
James Mattise3ef1912020-12-20 11:09:58 -08008027 if (oldDefaultNetwork != null) {
8028 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8029 }
8030 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008031 handleApplyDefaultProxy(null != newDefaultNetwork
8032 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8033 updateTcpBufferSizes(null != newDefaultNetwork
8034 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008035 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008036 }
8037
James Mattisd31bdfa2020-12-23 16:37:26 -08008038 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8039 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8040 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8041 try {
8042 if (VDBG) {
8043 log("Setting default network for " + nri
8044 + " using UIDs " + nri.getUids()
8045 + " with old network " + (oldDefaultNetwork != null
8046 ? oldDefaultNetwork.network().getNetId() : "null")
8047 + " and new network " + (newDefaultNetwork != null
8048 ? newDefaultNetwork.network().getNetId() : "null"));
8049 }
8050 if (nri.getUids().isEmpty()) {
8051 throw new IllegalStateException("makeDefaultForApps called without specifying"
8052 + " any applications to set as the default." + nri);
8053 }
8054 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008055 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008056 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008057 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008058 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008059 }
8060 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008061 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008062 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008063 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008064 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008065 }
8066 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008067 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008068 }
8069 }
8070
8071 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8072 try {
8073 if (null != newDefaultNetwork) {
8074 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8075 } else {
8076 mNetd.networkClearDefault();
8077 }
8078 } catch (RemoteException | ServiceSpecificException e) {
8079 loge("Exception setting default network :" + e);
8080 }
8081 }
8082
Chalard Jean05cbe972019-12-09 11:50:38 +09008083 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008084 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008085 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008086 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008087 processNewlySatisfiedListenRequests(nai);
8088 }
8089
8090 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008091 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8092 if (nri.isMultilayerRequest()) {
8093 continue;
8094 }
8095 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008096 if (!nr.isListen()) continue;
8097 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008098 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008099 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8100 }
8101 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008102 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008103
Chalard Jeancd397a22019-11-22 22:33:33 +09008104 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008105 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8106 if (nri.isMultilayerRequest()) {
8107 continue;
8108 }
8109 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008110 if (!nr.isListen()) continue;
8111 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8112 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008113 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008114 }
8115 }
8116 }
8117
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008118 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008119 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008120 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008121 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008122 @Nullable public final NetworkRequest mOldNetworkRequest;
8123 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008124 @Nullable public final NetworkAgentInfo mOldNetwork;
8125 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008126 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008127 @Nullable final NetworkRequest oldNetworkRequest,
8128 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008129 @Nullable final NetworkAgentInfo oldNetwork,
8130 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008131 mNetworkRequestInfo = networkRequestInfo;
8132 mOldNetworkRequest = oldNetworkRequest;
8133 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008134 mOldNetwork = oldNetwork;
8135 mNewNetwork = newNetwork;
8136 }
Chalard Jean49707572019-12-10 21:07:02 +09008137
8138 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008139 final NetworkRequest requestToShow = null != mNewNetworkRequest
8140 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8141 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008142 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8143 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008144 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008145 }
8146
Chalard Jean46a62372019-12-10 21:25:24 +09008147 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008148
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008149 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008150 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008151 }
8152
8153 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008154 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008155 // The code is never supposed to add two reassignments of the same request. Make
8156 // sure this stays true, but without imposing this expensive check on all
8157 // reassignments on all user devices.
8158 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008159 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008160 throw new IllegalStateException("Trying to reassign ["
8161 + reassignment + "] but already have ["
8162 + existing + "]");
8163 }
8164 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008165 }
Chalard Jean46a62372019-12-10 21:25:24 +09008166 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008167 }
8168
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008169 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008170 // the passed request.
8171 @Nullable
8172 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008173 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008174 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008175 }
8176 return null;
8177 }
Chalard Jean49707572019-12-10 21:07:02 +09008178
8179 public String toString() {
8180 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8181 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008182 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008183 for (final RequestReassignment rr : getRequestReassignments()) {
8184 sj.add(rr.toString());
8185 }
8186 return sj.toString();
8187 }
8188
8189 public String debugString() {
8190 final StringBuilder sb = new StringBuilder();
8191 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008192 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008193 for (final RequestReassignment rr : getRequestReassignments()) {
8194 sb.append("\n ").append(rr);
8195 }
8196 return sb.append("\n").toString();
8197 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008198 }
8199
Chalard Jean24344d72019-12-04 13:32:31 +09008200 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008201 @Nullable final NetworkRequest previousRequest,
8202 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008203 @Nullable final NetworkAgentInfo previousSatisfier,
8204 @Nullable final NetworkAgentInfo newSatisfier,
8205 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008206 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008207 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008208 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008209 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008210 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008211 }
James Mattisa076c532020-12-02 14:12:41 -08008212 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008213 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8214 // If this network switch can't be supported gracefully, the request is not
8215 // lingered. This allows letting go of the network sooner to reclaim some
8216 // performance on the new network, since the radio can't do both at the same
8217 // time while preserving good performance.
8218 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8219 }
Chalard Jean24344d72019-12-04 13:32:31 +09008220 } else {
8221 if (VDBG || DDBG) log(" accepting network in place of null");
8222 }
junyulai0ac374f2020-12-14 18:41:52 +08008223
8224 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8225 // and immediately satisfies a request then remove the timer. This will happen for
8226 // all networks except in the case of an underlying network for a VCN.
8227 if (newSatisfier.isNascent()) {
8228 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008229 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008230 }
8231
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008232 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008233 newSatisfier.unlingerRequest(newRequest.requestId);
8234 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008235 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008236 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008237 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008238 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008239 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008240 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008241 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008242 }
James Mattisa076c532020-12-02 14:12:41 -08008243 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008244 }
James Mattisa076c532020-12-02 14:12:41 -08008245 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008246 }
8247
James Mattisa076c532020-12-02 14:12:41 -08008248 /**
8249 * This function is triggered when something can affect what network should satisfy what
8250 * request, and it computes the network reassignment from the passed collection of requests to
8251 * network match to the one that the system should now have. That data is encoded in an
8252 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8253 * satisfier.
8254 *
8255 * After the reassignment is computed, it is applied to the state objects.
8256 *
8257 * @param networkRequests the nri objects to evaluate for possible network reassignment
8258 * @return NetworkReassignment listing of proposed network assignment changes
8259 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008260 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008261 private NetworkReassignment computeNetworkReassignment(
8262 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008263 final NetworkReassignment changes = new NetworkReassignment();
8264
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008265 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008266 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008267 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008268 if (!nai.everConnected) {
8269 continue;
8270 }
Chalard Jean857a1712019-12-10 21:08:07 +09008271 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008272 }
Chalard Jean857a1712019-12-10 21:08:07 +09008273
James Mattisa076c532020-12-02 14:12:41 -08008274 for (final NetworkRequestInfo nri : networkRequests) {
8275 // Non-multilayer listen requests can be ignored.
8276 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8277 continue;
8278 }
8279 NetworkAgentInfo bestNetwork = null;
8280 NetworkRequest bestRequest = null;
8281 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008282 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008283 // Stop evaluating as the highest possible priority request is satisfied.
8284 if (null != bestNetwork) {
8285 bestRequest = req;
8286 break;
8287 }
8288 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008289 if (null == bestNetwork && isDefaultBlocked(nri)) {
8290 // Remove default networking if disallowed for managed default requests.
8291 bestNetwork = mNoServiceNetwork;
8292 }
8293 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008294 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008295 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008296 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008297 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008298 }
8299 return changes;
8300 }
8301
James Mattisa076c532020-12-02 14:12:41 -08008302 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8303 return new HashSet<>(mNetworkRequests.values());
8304 }
8305
Paul Jensenc88b39b2015-06-16 14:27:36 -04008306 /**
James Mattisa076c532020-12-02 14:12:41 -08008307 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008308 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008309 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008310 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008311 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8312 }
8313
8314 /**
8315 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8316 * being disconnected.
8317 */
8318 private void rematchNetworksAndRequests(
8319 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8320 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008321 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008322 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008323 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008324 if (VDBG || DDBG) {
8325 log(changes.debugString());
8326 } else if (DBG) {
8327 log(changes.toString()); // Shorter form, only one line of log
8328 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008329 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008330 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008331 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008332
Chalard Jeand7f762d2019-12-10 19:01:29 +09008333 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008334 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008335 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008336
8337 // Since most of the time there are only 0 or 1 background networks, it would probably
8338 // be more efficient to just use an ArrayList here. TODO : measure performance
8339 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8340 for (final NetworkAgentInfo nai : nais) {
8341 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8342 }
8343
Chalard Jeand7f762d2019-12-10 19:01:29 +09008344 // First, update the lists of satisfied requests in the network agents. This is necessary
8345 // because some code later depends on this state to be correct, most prominently computing
8346 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008347 for (final NetworkReassignment.RequestReassignment event :
8348 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008349 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8350 event.mOldNetworkRequest, event.mNewNetworkRequest,
8351 event.mOldNetwork, event.mNewNetwork,
8352 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008353 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008354
James Mattise3ef1912020-12-20 11:09:58 -08008355 // Process default network changes if applicable.
8356 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008357
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008358 // Notify requested networks are available after the default net is switched, but
8359 // before LegacyTypeTracker sends legacy broadcasts
8360 for (final NetworkReassignment.RequestReassignment event :
8361 changes.getRequestReassignments()) {
8362 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008363 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008364 } else {
James Mattisa076c532020-12-02 14:12:41 -08008365 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008366 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008367 }
8368 }
8369
junyulai0ac374f2020-12-14 18:41:52 +08008370 // Update the inactivity state before processing listen callbacks, because the background
8371 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008372 // just yet though, because they have to be sent after the listens are processed to keep
8373 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008374 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008375 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008376 // Rematching may have altered the inactivity state of some networks, so update all
8377 // inactivity timers. updateInactivityState reads the state from the network agent
8378 // and does nothing if the state has not changed : the source of truth is controlled
8379 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8380 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008381 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008382 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008383 }
8384 }
8385
Chalard Jeanb10ab412019-12-11 14:12:30 +09008386 for (final NetworkAgentInfo nai : nais) {
8387 if (!nai.everConnected) continue;
8388 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008389 // Process listen requests and update capabilities if the background state has
8390 // changed for this network. For consistency with previous behavior, send onLost
8391 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008392 processNewlyLostListenRequests(nai);
8393 if (oldBackground != nai.isBackgroundNetwork()) {
8394 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008395 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008396 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008397 }
8398
junyulai0ac374f2020-12-14 18:41:52 +08008399 for (final NetworkAgentInfo nai : inactiveNetworks) {
8400 // For nascent networks, if connecting with no foreground request, skip broadcasting
8401 // LOSING for backward compatibility. This is typical when mobile data connected while
8402 // wifi connected with mobile data always-on enabled.
8403 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008404 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008405 }
8406
James Mattise3ef1912020-12-20 11:09:58 -08008407 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008408
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008409 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008410 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008411 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008412 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008413 // This network has active linger timers and no requests, but is not
8414 // lingering. Linger it.
8415 //
8416 // One way (the only way?) this can happen if this network is unvalidated
8417 // and became unneeded due to another network improving its score to the
8418 // point where this network will no longer be able to satisfy any requests
8419 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008420 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008421 notifyNetworkLosing(nai, now);
8422 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008423 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008424 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008425 teardownUnneededNetwork(nai);
8426 }
8427 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008428 }
8429 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008430
Chalard Jean62edfd82019-12-02 18:39:29 +09008431 /**
8432 * Apply a change in background state resulting from rematching networks with requests.
8433 *
8434 * During rematch, a network may change background states by starting to satisfy or stopping
8435 * to satisfy a foreground request. Listens don't count for this. When a network changes
8436 * background states, its capabilities need to be updated and callbacks fired for the
8437 * capability change.
8438 *
8439 * @param nai The network that changed background states
8440 */
8441 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8442 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8443 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8444 updateNetworkPermissions(nai, newNc);
8445 nai.getAndSetNetworkCapabilities(newNc);
8446 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8447 }
8448
Chalard Jeanf0344532019-11-19 19:23:38 +09008449 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008450 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008451 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008452 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8453 changes.getReassignment(mDefaultRequest);
8454 final NetworkAgentInfo oldDefaultNetwork =
8455 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8456 final NetworkAgentInfo newDefaultNetwork =
8457 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008458
Chalard Jean5b409c72021-02-04 13:12:59 +09008459 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008460 // Maintain the illusion : since the legacy API only understands one network at a time,
8461 // if the default network changed, apps should see a disconnected broadcast for the
8462 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008463 if (oldDefaultNetwork != null) {
8464 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8465 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008466 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008467 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008468 // The new default network can be newly null if and only if the old default
8469 // network doesn't satisfy the default request any more because it lost a
8470 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008471 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008472 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008473 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008474 }
8475 }
8476
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008477 // Now that all the callbacks have been sent, send the legacy network broadcasts
8478 // as needed. This is necessary so that legacy requests correctly bind dns
8479 // requests to this network. The legacy users are listening for this broadcast
8480 // and will generally do a dns request so they can ensureRouteToHost and if
8481 // they do that before the callbacks happen they'll use the default network.
8482 //
8483 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8484 // callbacks, but if apps can receive the broadcast before the callback, they still might
8485 // have an inconsistent view of networking.
8486 //
8487 // This *does* introduce a race where if the user uses the new api
8488 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8489 // they may get old info. Reverse this after the old startUsing api is removed.
8490 // This is on top of the multiple intent sequencing referenced in the todo above.
8491 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008492 if (nai.everConnected) {
8493 addNetworkToLegacyTypeTracker(nai);
8494 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008495 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008496 }
8497
Chalard Jean0354d8c2021-01-12 10:58:56 +09008498 private void issueNetworkNeeds() {
8499 ensureRunningOnConnectivityServiceThread();
8500 for (final NetworkOfferInfo noi : mNetworkOffers) {
8501 issueNetworkNeeds(noi);
8502 }
8503 }
8504
8505 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8506 ensureRunningOnConnectivityServiceThread();
8507 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8508 informOffer(nri, noi.offer, mNetworkRanker);
8509 }
8510 }
8511
8512 /**
8513 * Inform a NetworkOffer about any new situation of a request.
8514 *
8515 * This function handles updates to offers. A number of events may happen that require
8516 * updating the registrant for this offer about the situation :
8517 * • The offer itself was updated. This may lead the offer to no longer being able
8518 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8519 * or conversely being strengthened enough to beat the satisfier (and therefore
8520 * start being needed)
8521 * • The network satisfying a request changed (including cases where the request
8522 * starts or stops being satisfied). The new network may be a stronger or weaker
8523 * match than the old one, possibly affecting whether the offer is needed.
8524 * • The network satisfying a request updated their score. This may lead the offer
8525 * to no longer be able to beat it if the current satisfier got better, or
8526 * conversely start being a good choice if the current satisfier got weaker.
8527 *
8528 * @param nri The request
8529 * @param offer The offer. This may be an updated offer.
8530 */
8531 private static void informOffer(@NonNull NetworkRequestInfo nri,
8532 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8533 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8534 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008535
8536 // Multi-layer requests have a currently active request, the one being satisfied.
8537 // Since the system will try to bring up a better network than is currently satisfying
8538 // the request, NetworkProviders need to be told the offers matching the requests *above*
8539 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8540 // not needed, and the offer is needed for the active request iff the offer can beat
8541 // the satisfier.
8542 // For non-multilayer requests, the logic above gracefully degenerates to only the
8543 // last case.
8544 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8545 // providers that the offer is needed for this request, until the active request is found.
8546 // In a second phase, deal with the currently active request. In a third phase, inform
8547 // the providers that offer is unneeded for the remaining requests.
8548
8549 // First phase : inform providers of all requests above the active request.
8550 int i;
8551 for (i = 0; nri.mRequests.size() > i; ++i) {
8552 final NetworkRequest request = nri.mRequests.get(i);
8553 if (activeRequest == request) break; // Found the active request : go to phase 2
8554 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8555 // Since this request is higher-priority than the one currently satisfied, if the
8556 // offer can satisfy it, the provider should try and bring up the network for sure ;
8557 // no need to even ask the ranker – an offer that can satisfy is always better than
8558 // no network. Hence tell the provider so unless it already knew.
8559 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8560 offer.onNetworkNeeded(request);
8561 }
8562 }
8563
8564 // Second phase : deal with the active request (if any)
8565 if (null != activeRequest && activeRequest.isRequest()) {
8566 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008567 // If an offer can satisfy the request, it is considered needed if it is currently
8568 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008569 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008570 && satisfier.factorySerialNumber == offer.providerId
8571 && activeRequest.canBeSatisfiedBy(offer.caps);
8572 final boolean newNeeded = currentlyServing
8573 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008574 if (newNeeded != oldNeeded) {
8575 if (newNeeded) {
8576 offer.onNetworkNeeded(activeRequest);
8577 } else {
8578 // The offer used to be able to beat the satisfier. Now it can't.
8579 offer.onNetworkUnneeded(activeRequest);
8580 }
8581 }
8582 }
8583
8584 // Third phase : inform the providers that the offer isn't needed for any request
8585 // below the active one.
8586 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8587 final NetworkRequest request = nri.mRequests.get(i);
8588 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8589 // Since this request is lower-priority than the one currently satisfied, if the
8590 // offer can satisfy it, the provider should not try and bring up the network.
8591 // Hence tell the provider so unless it already knew.
8592 if (offer.neededFor(request)) {
8593 offer.onNetworkUnneeded(request);
8594 }
8595 }
8596 }
8597
Chalard Jean61c79252019-11-07 23:07:32 +09008598 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8599 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8600 NetworkRequest nr = nai.requestAt(i);
8601 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8602 // legacy type tracker filters out repeat adds
8603 mLegacyTypeTracker.add(nr.legacyType, nai);
8604 }
8605 }
8606
8607 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008608 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008609 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8610 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8611 if (nai.isVPN()) {
8612 mLegacyTypeTracker.add(TYPE_VPN, nai);
8613 }
8614 }
8615
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008616 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008617 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008618 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008619 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008620 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008621 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008622
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008623 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008624 // Don't repeat publish.
8625 if (newInetCondition == mDefaultInetConditionPublished) return;
8626
8627 mDefaultInetConditionPublished = newInetCondition;
8628 sendInetConditionBroadcast(nai.networkInfo);
8629 }
8630
Chalard Jeand61375d2020-01-14 22:46:36 +09008631 @NonNull
8632 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8633 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008634 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008635 final boolean suspended =
8636 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8637 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8638 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8639 // state. This is because the network could have been suspended before connecting,
8640 // or it could be disconnecting while being suspended, and in both these cases
8641 // the state should not be overridden. Note that the only detailed state that
8642 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8643 // worry about multiple different substates of CONNECTED.
8644 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8645 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008646 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8647 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8648 // network agent is created, then goes to suspended, then goes out of suspended without
8649 // ever setting connected. Check if network agent is ever connected to update the state.
8650 newInfo.setDetailedState(nai.everConnected
8651 ? NetworkInfo.DetailedState.CONNECTED
8652 : NetworkInfo.DetailedState.CONNECTING,
8653 info.getReason(),
8654 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008655 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008656 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008657 return newInfo;
8658 }
8659
8660 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8661 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8662
Erik Kline99f301b2017-02-15 19:59:17 +09008663 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008664 NetworkInfo oldInfo = null;
8665 synchronized (networkAgent) {
8666 oldInfo = networkAgent.networkInfo;
8667 networkAgent.networkInfo = newInfo;
8668 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008669
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008670 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008671 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8672 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008673 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008674
Robin Leea8c0b6e2016-05-01 23:00:00 +01008675 if (!networkAgent.created
8676 && (state == NetworkInfo.State.CONNECTED
8677 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008678
8679 // A network that has just connected has zero requests and is thus a foreground network.
8680 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8681
Luke Huangfdd11f82019-04-09 18:41:49 +08008682 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008683 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008684 // Initialize the network's capabilities to their starting values according to the
8685 // underlying networks. This ensures that the capabilities are correct before
8686 // anything happens to the network.
8687 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008688 }
Paul Jensen74940202014-08-04 12:21:19 -04008689 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008690 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008691 }
8692
8693 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8694 networkAgent.everConnected = true;
8695
lucaslin45e639b2019-04-03 17:09:28 +08008696 // NetworkCapabilities need to be set before sending the private DNS config to
8697 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008698 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8699
Erik Kline9a62f012018-03-21 07:18:33 -07008700 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008701 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8702 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008703
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008704 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8705 // command must be sent after updating LinkProperties to maximize chances of
8706 // NetworkMonitor seeing the correct LinkProperties when starting.
8707 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008708 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008709 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008710 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008711 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008712 new LinkProperties(networkAgent.linkProperties,
8713 true /* parcelSensitiveFields */),
8714 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008715 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008716
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008717 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8718 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8719 // capabilities, so it only needs to be done once on initial connect, not every time the
8720 // network's capabilities change. Note that we do this before rematching the network,
8721 // so we could decide to tear it down immediately afterwards. That's fine though - on
8722 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8723 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008724 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008725
junyulai0ac374f2020-12-14 18:41:52 +08008726 // Before first rematching networks, put an inactivity timer without any request, this
8727 // allows {@code updateInactivityState} to update the state accordingly and prevent
8728 // tearing down for any {@code unneeded} evaluation in this period.
8729 // Note that the timer will not be rescheduled since the expiry time is
8730 // fixed after connection regardless of the network satisfying other requests or not.
8731 // But it will be removed as soon as the network satisfies a request for the first time.
8732 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8733 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008734 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008735
Paul Jensen05e85ee2014-09-11 11:00:39 -04008736 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008737 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008738
8739 // This has to happen after matching the requests, because callbacks are just requests.
8740 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008741 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008742 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008743 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008744 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008745 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008746 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008747 if (networkAgent.isVPN()) {
8748 // As the active or bound network changes for apps, broadcast the default proxy, as
8749 // apps may need to update their proxy data. This is called after disconnecting from
8750 // VPN to make sure we do not broadcast the old proxy data.
8751 // TODO(b/122649188): send the broadcast only to VPN users.
8752 mProxyTracker.sendProxyBroadcast();
8753 }
Yintang Gu5014b522019-06-18 14:24:32 +08008754 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8755 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008756 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008757 }
8758 }
8759
Chalard Jean28018572020-12-21 18:36:52 +09008760 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008761 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8762 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008763 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008764 }
8765
Erik Kline99f301b2017-02-15 19:59:17 +09008766 // Notify only this one new request of the current state. Transfer all the
8767 // current state by calling NetworkCapabilities and LinkProperties callbacks
8768 // so that callers can be guaranteed to have as close to atomicity in state
8769 // transfer as can be supported by this current API.
8770 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008771 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008772 if (nri.mPendingIntent != null) {
8773 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8774 // Attempt no subsequent state pushes where intents are involved.
8775 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008776 }
Erik Kline99f301b2017-02-15 19:59:17 +09008777
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008778 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008779 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008780 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8781 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8782 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008783 }
8784
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008785 // Notify the requests on this NAI that the network is now lingered.
8786 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008787 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008788 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8789 }
8790
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008791 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8792 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8793 return vpnBlocked
8794 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8795 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8796 }
8797
8798 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8799 if (blockedReasons == BLOCKED_REASON_NONE) {
8800 mUidBlockedReasons.delete(uid);
8801 } else {
8802 mUidBlockedReasons.put(uid, blockedReasons);
8803 }
8804 }
8805
junyulaif2c67e42018-08-07 19:50:45 +08008806 /**
8807 * Notify of the blocked state apps with a registered callback matching a given NAI.
8808 *
8809 * Unlike other callbacks, blocked status is different between each individual uid. So for
8810 * any given nai, all requests need to be considered according to the uid who filed it.
8811 *
8812 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008813 * @param oldMetered True if the previous network capabilities were metered.
8814 * @param newMetered True if the current network capabilities are metered.
8815 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8816 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008817 */
8818 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008819 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8820 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008821
8822 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8823 NetworkRequest nr = nai.requestAt(i);
8824 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008825
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008826 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8827 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8828 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008829 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008830 : oldVpnBlocked;
8831
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008832 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8833 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8834 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008835 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008836 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008837 }
8838 }
8839 }
8840
8841 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008842 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008843 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008844 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008845 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008846 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008847 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008848 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008849 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008850
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008851 final int oldBlockedState = getBlockedState(
8852 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8853 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8854 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008855 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008856 }
junyulaif2c67e42018-08-07 19:50:45 +08008857 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8858 NetworkRequest nr = nai.requestAt(i);
8859 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008860 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008861 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8862 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008863 }
8864 }
8865 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008866 }
8867
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008868 @VisibleForTesting
8869 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008870 // The NetworkInfo we actually send out has no bearing on the real
8871 // state of affairs. For example, if the default connection is mobile,
8872 // and a request for HIPRI has just gone away, we need to pretend that
8873 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8874 // the state to DISCONNECTED, even though the network is of type MOBILE
8875 // and is still connected.
8876 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8877 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008878 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008879 if (state != DetailedState.DISCONNECTED) {
8880 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008881 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008882 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008883 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008884 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8885 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8886 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8887 if (info.isFailover()) {
8888 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8889 nai.networkInfo.setFailover(false);
8890 }
8891 if (info.getReason() != null) {
8892 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8893 }
8894 if (info.getExtraInfo() != null) {
8895 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8896 }
8897 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008898 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008899 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008900 if (newDefaultAgent != null) {
8901 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8902 newDefaultAgent.networkInfo);
8903 } else {
8904 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8905 }
8906 }
8907 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8908 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008909 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008910 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008911 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008912 }
8913 }
8914 }
8915
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008916 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008917 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008918 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008919 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008920 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008921 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8922 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008923 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8924 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008925 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008926 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008927 } else {
8928 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8929 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008930 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008931 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008932
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008933 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8934 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8935 }
8936
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008937 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008938 * Returns the list of all interfaces that could be used by network traffic that does not
8939 * explicitly specify a network. This includes the default network, but also all VPNs that are
8940 * currently connected.
8941 *
8942 * Must be called on the handler thread.
8943 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008944 @NonNull
8945 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008946 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008947 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008948 final Set<Integer> activeNetIds = new ArraySet<>();
8949 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8950 if (nri.isBeingSatisfied()) {
8951 activeNetIds.add(nri.getSatisfier().network().netId);
8952 }
8953 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008954 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008955 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008956 defaultNetworks.add(nai.network);
8957 }
8958 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008959 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008960 }
8961
8962 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008963 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8964 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008965 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008966 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008967 ensureRunningOnConnectivityServiceThread();
8968 String activeIface = null;
8969 LinkProperties activeLinkProperties = getActiveLinkProperties();
8970 if (activeLinkProperties != null) {
8971 activeIface = activeLinkProperties.getInterfaceName();
8972 }
Benedict Wong9308cd32019-06-12 17:46:31 +00008973
junyulai2050bed2021-01-23 09:46:34 +08008974 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008975 try {
junyulaide41fc22021-01-22 22:46:01 +08008976 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08008977 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08008978 snapshots.add(snapshot);
8979 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008980 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8981 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008982 } catch (Exception ignored) {
8983 }
8984 }
8985
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07008986 @Override
Udam Sainicd645462016-01-04 12:16:14 -08008987 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08008988 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008989 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008990 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008991
8992 if (!TextUtils.isEmpty(settingUrl)) {
8993 return settingUrl;
8994 }
8995
8996 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08008997 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008998 if (!TextUtils.isEmpty(settingUrl)) {
8999 return settingUrl;
9000 }
9001
9002 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009003 }
9004
9005 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009006 public void startNattKeepalive(Network network, int intervalSeconds,
9007 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009008 enforceKeepalivePermission();
9009 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009010 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009011 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009012 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009013 }
9014
9015 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009016 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009017 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009018 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009019 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009020 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009021 mKeepaliveTracker.startNattKeepalive(
9022 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9023 intervalSeconds, cb,
9024 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9025 } finally {
9026 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9027 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009028 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9029 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009030 }
9031 }
junyulaid05a1922019-01-15 11:32:44 +08009032 }
9033
9034 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009035 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009036 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009037 try {
9038 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009039 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009040 mKeepaliveTracker.startTcpKeepalive(
9041 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9042 } finally {
9043 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9044 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009045 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9046 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009047 }
9048 }
junyulai0835a1e2019-01-08 20:04:33 +08009049 }
9050
9051 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009052 public void stopKeepalive(Network network, int slot) {
9053 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009054 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009055 }
9056
9057 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009058 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009059 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009060
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009061 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009062 final long token = Binder.clearCallingIdentity();
9063 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009064 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9065 UserHandle.getUserHandleForUid(uid))) {
9066 return;
9067 }
9068
Heemin Seogdb8489d2019-06-12 09:21:44 -07009069 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9070 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009071
9072 // Turn airplane mode off
9073 setAirplaneMode(false);
9074
9075 // restore private DNS settings to default mode (opportunistic)
9076 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9077 UserHandle.getUserHandleForUid(uid))) {
9078 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9079 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9080 }
9081
9082 Settings.Global.putString(mContext.getContentResolver(),
9083 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009084 } finally {
9085 Binder.restoreCallingIdentity(token);
9086 }
Stuart Scottd5463642015-04-02 18:00:02 -07009087 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009088
Ricky Wai7097cc92018-01-23 04:09:45 +00009089 @Override
9090 public byte[] getNetworkWatchlistConfigHash() {
9091 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9092 if (nwm == null) {
9093 loge("Unable to get NetworkWatchlistManager");
9094 return null;
9095 }
9096 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9097 return nwm.getWatchlistConfigHash();
9098 }
9099
Hugo Benichibe0c7652016-05-31 16:28:06 +09009100 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009101 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009102 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009103 }
Hugo Benichif4210292017-04-21 15:07:12 +09009104
9105 private static boolean toBool(int encodedBoolean) {
9106 return encodedBoolean != 0; // Only 0 means false.
9107 }
9108
9109 private static int encodeBool(boolean b) {
9110 return b ? 1 : 0;
9111 }
mswest4632928412018-03-12 10:34:34 -07009112
9113 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009114 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9115 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9116 @NonNull String[] args) {
9117 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9118 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009119 }
9120
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009121 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009122 @Override
9123 public int onCommand(String cmd) {
9124 if (cmd == null) {
9125 return handleDefaultCommands(cmd);
9126 }
9127 final PrintWriter pw = getOutPrintWriter();
9128 try {
9129 switch (cmd) {
9130 case "airplane-mode":
9131 final String action = getNextArg();
9132 if ("enable".equals(action)) {
9133 setAirplaneMode(true);
9134 return 0;
9135 } else if ("disable".equals(action)) {
9136 setAirplaneMode(false);
9137 return 0;
9138 } else if (action == null) {
9139 final ContentResolver cr = mContext.getContentResolver();
9140 final int enabled = Settings.Global.getInt(cr,
9141 Settings.Global.AIRPLANE_MODE_ON);
9142 pw.println(enabled == 0 ? "disabled" : "enabled");
9143 return 0;
9144 } else {
9145 onHelp();
9146 return -1;
9147 }
9148 default:
9149 return handleDefaultCommands(cmd);
9150 }
9151 } catch (Exception e) {
9152 pw.println(e);
9153 }
9154 return -1;
9155 }
9156
9157 @Override
9158 public void onHelp() {
9159 PrintWriter pw = getOutPrintWriter();
9160 pw.println("Connectivity service commands:");
9161 pw.println(" help");
9162 pw.println(" Print this help text.");
9163 pw.println(" airplane-mode [enable|disable]");
9164 pw.println(" Turn airplane mode on or off.");
9165 pw.println(" airplane-mode");
9166 pw.println(" Get airplane mode.");
9167 }
9168 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009169
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009170 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009171 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9172 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9173 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009174 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009175 }
9176
9177 /**
9178 * @param connectionInfo the connection to resolve.
9179 * @return {@code uid} if the connection is found and the app has permission to observe it
9180 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9181 * connection is not found.
9182 */
9183 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009184 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9185 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9186 }
9187
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009188 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009189 connectionInfo.local, connectionInfo.remote);
9190
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009191 if (uid == INVALID_UID) return uid; // Not found.
9192
9193 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9194 // VPN, if any, that applies to the UID that owns the connection.
9195 if (checkNetworkStackPermission()) return uid;
9196
9197 final NetworkAgentInfo vpn = getVpnForUid(uid);
9198 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009199 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009200 return INVALID_UID;
9201 }
9202
9203 return uid;
9204 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009205
Benedict Wong493e04b2018-11-09 14:45:34 -08009206 /**
9207 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9208 *
9209 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9210 */
9211 @Override
9212 public IBinder startOrGetTestNetworkService() {
9213 synchronized (mTNSLock) {
9214 TestNetworkService.enforceTestNetworkPermissions(mContext);
9215
9216 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009217 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009218 }
9219
9220 return mTNS;
9221 }
9222 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009223
Cody Kesting73708bf2019-12-18 10:57:50 -08009224 /**
9225 * Handler used for managing all Connectivity Diagnostics related functions.
9226 *
9227 * @see android.net.ConnectivityDiagnosticsManager
9228 *
9229 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9230 */
9231 @VisibleForTesting
9232 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009233 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9234
Cody Kesting73708bf2019-12-18 10:57:50 -08009235 /**
9236 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9237 * android.net.ConnectivityDiagnosticsManager}.
9238 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9239 * NetworkRequestInfo to be registered
9240 */
9241 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9242
9243 /**
9244 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9245 * android.net.ConnectivityDiagnosticsManager}.
9246 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9247 * arg1 = the uid of the caller
9248 */
9249 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9250
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009251 /**
9252 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9253 * after processing {@link #EVENT_NETWORK_TESTED} events.
9254 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9255 * NetworkMonitor.
9256 * data = PersistableBundle of extras passed from NetworkMonitor.
9257 *
9258 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9259 */
9260 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9261
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009262 /**
9263 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9264 * been detected on the network.
9265 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9266 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9267 * arg2 = NetID.
9268 * data = PersistableBundle of extras passed from NetworkMonitor.
9269 */
9270 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9271
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009272 /**
9273 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9274 * the platform. This event will invoke {@link
9275 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9276 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009277 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009278 */
9279 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9280
Cody Kesting73708bf2019-12-18 10:57:50 -08009281 private ConnectivityDiagnosticsHandler(Looper looper) {
9282 super(looper);
9283 }
9284
9285 @Override
9286 public void handleMessage(Message msg) {
9287 switch (msg.what) {
9288 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9289 handleRegisterConnectivityDiagnosticsCallback(
9290 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9291 break;
9292 }
9293 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9294 handleUnregisterConnectivityDiagnosticsCallback(
9295 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9296 break;
9297 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009298 case EVENT_NETWORK_TESTED: {
9299 final ConnectivityReportEvent reportEvent =
9300 (ConnectivityReportEvent) msg.obj;
9301
Aaron Huang959d3642021-01-21 15:47:41 +08009302 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009303 break;
9304 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009305 case EVENT_DATA_STALL_SUSPECTED: {
9306 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009307 final Pair<Long, PersistableBundle> arg =
9308 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009309 if (nai == null) break;
9310
Aaron Huang959d3642021-01-21 15:47:41 +08009311 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009312 break;
9313 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009314 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009315 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009316 break;
9317 }
9318 default: {
9319 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9320 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009321 }
9322 }
9323 }
9324
9325 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9326 @VisibleForTesting
9327 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9328 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9329 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009330 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009331
9332 @VisibleForTesting
9333 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009334 @NonNull IConnectivityDiagnosticsCallback cb,
9335 @NonNull NetworkRequestInfo nri,
9336 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009337 mCb = cb;
9338 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009339 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009340 }
9341
9342 @Override
9343 public void binderDied() {
9344 log("ConnectivityDiagnosticsCallback IBinder died.");
9345 unregisterConnectivityDiagnosticsCallback(mCb);
9346 }
9347 }
9348
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009349 /**
9350 * Class used for sending information from {@link
9351 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9352 */
9353 private static class NetworkTestedResults {
9354 private final int mNetId;
9355 private final int mTestResult;
9356 private final long mTimestampMillis;
9357 @Nullable private final String mRedirectUrl;
9358
9359 private NetworkTestedResults(
9360 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9361 mNetId = netId;
9362 mTestResult = testResult;
9363 mTimestampMillis = timestampMillis;
9364 mRedirectUrl = redirectUrl;
9365 }
9366 }
9367
9368 /**
9369 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9370 * ConnectivityDiagnosticsHandler}.
9371 */
9372 private static class ConnectivityReportEvent {
9373 private final long mTimestampMillis;
9374 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009375 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009376
Aaron Huang959d3642021-01-21 15:47:41 +08009377 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9378 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009379 mTimestampMillis = timestampMillis;
9380 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009381 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009382 }
9383 }
9384
Cody Kestingf1120be2020-08-03 18:01:40 -07009385 /**
9386 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9387 * ConnectivityDiagnosticsHandler}.
9388 */
9389 private static class ReportedNetworkConnectivityInfo {
9390 public final boolean hasConnectivity;
9391 public final boolean isNetworkRevalidating;
9392 public final int reporterUid;
9393 @NonNull public final NetworkAgentInfo nai;
9394
9395 private ReportedNetworkConnectivityInfo(
9396 boolean hasConnectivity,
9397 boolean isNetworkRevalidating,
9398 int reporterUid,
9399 @NonNull NetworkAgentInfo nai) {
9400 this.hasConnectivity = hasConnectivity;
9401 this.isNetworkRevalidating = isNetworkRevalidating;
9402 this.reporterUid = reporterUid;
9403 this.nai = nai;
9404 }
9405 }
9406
Cody Kesting73708bf2019-12-18 10:57:50 -08009407 private void handleRegisterConnectivityDiagnosticsCallback(
9408 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9409 ensureRunningOnConnectivityServiceThread();
9410
9411 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009412 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009413 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9414
James Mattis64b8b0f2020-11-24 17:40:49 -08009415 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9416 // confusing for these networks to change when an NRI is satisfied in another layer.
9417 if (nri.isMultilayerRequest()) {
9418 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9419 + "network requests.");
9420 }
9421
Cody Kesting73708bf2019-12-18 10:57:50 -08009422 // This means that the client registered the same callback multiple times. Do
9423 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009424 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009425 if (VDBG) log("Diagnostics callback is already registered");
9426
9427 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9428 // incremented when the NetworkRequestInfo is created as part of
9429 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009430 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009431 return;
9432 }
9433
Cody Kesting31f1ff62020-03-05 10:46:02 -08009434 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009435
9436 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009437 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009438 } catch (RemoteException e) {
9439 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009440 return;
9441 }
9442
9443 // Once registered, provide ConnectivityReports for matching Networks
9444 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9445 synchronized (mNetworkForNetId) {
9446 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9447 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009448 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9449 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009450 matchingNetworks.add(nai);
9451 }
9452 }
9453 }
9454 for (final NetworkAgentInfo nai : matchingNetworks) {
9455 final ConnectivityReport report = nai.getConnectivityReport();
9456 if (report == null) {
9457 continue;
9458 }
9459 if (!checkConnectivityDiagnosticsPermissions(
9460 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9461 continue;
9462 }
9463
9464 try {
9465 cb.onConnectivityReportAvailable(report);
9466 } catch (RemoteException e) {
9467 // Exception while sending the ConnectivityReport. Move on to the next network.
9468 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009469 }
9470 }
9471
9472 private void handleUnregisterConnectivityDiagnosticsCallback(
9473 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9474 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009475 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009476
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009477 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9478 mConnectivityDiagnosticsCallbacks.remove(iCb);
9479 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009480 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9481 return;
9482 }
9483
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009484 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009485
Cody Kesting70fa2b22020-12-02 12:16:56 -08009486 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9487 // (if the Binder died)
9488 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9489 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009490 return;
9491 }
9492
Cody Kesting46cb1672020-03-04 13:35:20 -08009493 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9494 // incremented when the NetworkRequestInfo is created as part of
9495 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009496 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009497
Cody Kesting31f1ff62020-03-05 10:46:02 -08009498 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009499 }
9500
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009501 private void handleNetworkTestedWithExtras(
9502 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9503 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009504 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009505 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009506 final ConnectivityReport report =
9507 new ConnectivityReport(
9508 reportEvent.mNai.network,
9509 reportEvent.mTimestampMillis,
9510 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009511 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009512 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009513 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009514
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009515 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009516 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009517 for (final IConnectivityDiagnosticsCallback cb : results) {
9518 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009519 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009520 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009521 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009522 }
9523 }
9524 }
9525
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009526 private void handleDataStallSuspected(
9527 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9528 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009529 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009530 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009531 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009532 new DataStallReport(
9533 nai.network,
9534 timestampMillis,
9535 detectionMethod,
9536 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009537 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009538 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009539 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009540 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009541 for (final IConnectivityDiagnosticsCallback cb : results) {
9542 try {
9543 cb.onDataStallSuspected(report);
9544 } catch (RemoteException ex) {
9545 loge("Error invoking onDataStallSuspected", ex);
9546 }
9547 }
9548 }
9549
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009550 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009551 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9552 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9553 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9554
9555 // If the Network is being re-validated as a result of this call to
9556 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9557 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009558 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009559 getMatchingPermissionedCallbacks(
9560 nai,
9561 reportedNetworkConnectivityInfo.isNetworkRevalidating
9562 ? Process.INVALID_UID
9563 : reportedNetworkConnectivityInfo.reporterUid);
9564
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009565 for (final IConnectivityDiagnosticsCallback cb : results) {
9566 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009567 cb.onNetworkConnectivityReported(
9568 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009569 } catch (RemoteException ex) {
9570 loge("Error invoking onNetworkConnectivityReported", ex);
9571 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009572
9573 // If the Network isn't re-validating, also provide the cached report. If there is no
9574 // cached report, the Network is still being validated and a report will be sent once
9575 // validation is complete. Note that networks which never undergo validation will still
9576 // have a cached ConnectivityReport with RESULT_SKIPPED.
9577 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9578 try {
9579 cb.onConnectivityReportAvailable(cachedReport);
9580 } catch (RemoteException ex) {
9581 loge("Error invoking onConnectivityReportAvailable", ex);
9582 }
9583 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009584 }
9585 }
9586
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009587 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009588 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9589 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009590 sanitized.setUids(null);
9591 sanitized.setAdministratorUids(new int[0]);
9592 sanitized.setOwnerUid(Process.INVALID_UID);
9593 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009594 }
9595
Cody Kestingf1120be2020-08-03 18:01:40 -07009596 /**
9597 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9598 *
9599 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9600 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009601 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009602 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009603 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009604 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009605 mConnectivityDiagnosticsCallbacks.entrySet()) {
9606 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9607 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009608
James Mattis64b8b0f2020-11-24 17:40:49 -08009609 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009610 if (!nai.satisfies(nri.mRequests.get(0))) {
9611 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009612 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009613
9614 // UID for this callback must either be:
9615 // - INVALID_UID (which sends callbacks to all UIDs), or
9616 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9617 // notified as a result)
9618 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9619 continue;
9620 }
9621
9622 if (!checkConnectivityDiagnosticsPermissions(
9623 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9624 continue;
9625 }
9626
9627 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009628 }
9629 return results;
9630 }
9631
Cody Kesting7474f672021-05-11 14:22:40 -07009632 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9633 @NonNull NetworkAgentInfo nai) {
9634 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9635 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9636 }
9637
Cody Kesting160ef392021-05-05 13:17:22 -07009638 private boolean hasLocationPermission(String packageName, int uid) {
9639 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9640 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9641 // call in a try-catch.
9642 try {
9643 if (!mLocationPermissionChecker.checkLocationPermission(
9644 packageName, null /* featureId */, uid, null /* message */)) {
9645 return false;
9646 }
9647 } catch (SecurityException e) {
9648 return false;
9649 }
9650
9651 return true;
9652 }
9653
9654 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9655 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009656 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009657 && virtual.networkCapabilities.getOwnerUid() == uid
9658 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9659 return true;
9660 }
9661 }
9662
9663 return false;
9664 }
9665
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009666 @VisibleForTesting
9667 boolean checkConnectivityDiagnosticsPermissions(
9668 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9669 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9670 return true;
9671 }
9672
Cody Kesting160ef392021-05-05 13:17:22 -07009673 // Administrator UIDs also contains the Owner UID
9674 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9675 if (!CollectionUtils.contains(administratorUids, callbackUid)
9676 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009677 return false;
9678 }
9679
Cody Kesting7474f672021-05-11 14:22:40 -07009680 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9681 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009682 }
9683
Cody Kestingd199a9d2019-12-17 12:55:28 -08009684 @Override
9685 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009686 @NonNull IConnectivityDiagnosticsCallback callback,
9687 @NonNull NetworkRequest request,
9688 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009689 Objects.requireNonNull(callback, "callback must not be null");
9690 Objects.requireNonNull(request, "request must not be null");
9691 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9692
Cody Kesting73708bf2019-12-18 10:57:50 -08009693 if (request.legacyType != TYPE_NONE) {
9694 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9695 + " Please use NetworkCapabilities instead.");
9696 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009697 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009698 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009699
9700 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9701 // and administrator uids to be safe.
9702 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009703 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009704
9705 final NetworkRequest requestWithId =
9706 new NetworkRequest(
9707 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9708
9709 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9710 //
9711 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9712 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9713 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009714 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009715 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009716 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009717
9718 mConnectivityDiagnosticsHandler.sendMessage(
9719 mConnectivityDiagnosticsHandler.obtainMessage(
9720 ConnectivityDiagnosticsHandler
9721 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9722 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009723 }
9724
9725 @Override
9726 public void unregisterConnectivityDiagnosticsCallback(
9727 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009728 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009729 mConnectivityDiagnosticsHandler.sendMessage(
9730 mConnectivityDiagnosticsHandler.obtainMessage(
9731 ConnectivityDiagnosticsHandler
9732 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009733 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009734 0,
9735 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009736 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009737
9738 @Override
9739 public void simulateDataStall(int detectionMethod, long timestampMillis,
9740 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009741 Objects.requireNonNull(network, "network must not be null");
9742 Objects.requireNonNull(extras, "extras must not be null");
9743
Cody Kestingf53a0752020-04-15 12:33:28 -07009744 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9745 android.Manifest.permission.NETWORK_STACK);
9746 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9747 if (!nc.hasTransport(TRANSPORT_TEST)) {
9748 throw new SecurityException("Data Stall simluation is only possible for test networks");
9749 }
9750
9751 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009752 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009753 throw new SecurityException("Data Stall simulation is only possible for network "
9754 + "creators");
9755 }
9756
Cody Kesting652e3ec2020-05-21 12:08:21 -07009757 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9758 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9759 // Data Stall information as a DataStallReportParcelable and passing to
9760 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9761 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009762 final DataStallReportParcelable p = new DataStallReportParcelable();
9763 p.timestampMillis = timestampMillis;
9764 p.detectionMethod = detectionMethod;
9765
9766 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9767 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9768 }
9769 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9770 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9771 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9772 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9773 }
9774
Serik Beketayevec8ad212020-12-07 22:43:07 -08009775 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009776 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009777
lucaslin66f44212021-02-23 01:12:55 +08009778 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9779 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009780 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009781 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009782 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009783 }
lucaslin37a16d92021-01-21 19:48:09 +08009784
9785 @Override
9786 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009787 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009788 nai.clatd.interfaceLinkStateChanged(iface, up);
9789 }
9790 }
9791
9792 @Override
9793 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009794 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009795 nai.clatd.interfaceRemoved(iface);
9796 }
lucaslin66f44212021-02-23 01:12:55 +08009797 }
9798 }
9799
lucaslin1a8b4c62021-01-21 02:02:55 +08009800 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9801
9802 /**
9803 * Class used for updating network activity tracking with netd and notify network activity
9804 * changes.
9805 */
9806 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009807 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009808 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009809 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009810 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9811 new RemoteCallbackList<>();
9812 // Indicate the current system default network activity is active or not.
9813 @GuardedBy("mActiveIdleTimers")
9814 private boolean mNetworkActive;
9815 @GuardedBy("mActiveIdleTimers")
9816 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9817 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009818
lucaslin1193a5d2021-01-21 02:04:15 +08009819 private class IdleTimerParams {
9820 public final int timeout;
9821 public final int transportType;
9822
9823 IdleTimerParams(int timeout, int transport) {
9824 this.timeout = timeout;
9825 this.transportType = transport;
9826 }
9827 }
9828
9829 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009830 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009831 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009832 mNetd = netd;
9833 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009834 }
9835
lucaslin66f44212021-02-23 01:12:55 +08009836 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9837 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9838 synchronized (mActiveIdleTimers) {
9839 mNetworkActive = active;
9840 // If there are no idle timers, it means that system is not monitoring
9841 // activity, so the system default network for those default network
9842 // unspecified apps is always considered active.
9843 //
9844 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9845 // any network activity change event. Whenever this event is received,
9846 // the mActiveIdleTimers should be always not empty. The legacy behavior
9847 // is no-op. Remove to refer to mNetworkActive only.
9848 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9849 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9850 }
9851 }
9852 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009853
lucaslin1193a5d2021-01-21 02:04:15 +08009854 // The network activity should only be updated from ConnectivityService handler thread
9855 // when mActiveIdleTimers lock is held.
9856 @GuardedBy("mActiveIdleTimers")
9857 private void reportNetworkActive() {
9858 final int length = mNetworkActivityListeners.beginBroadcast();
9859 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9860 try {
9861 for (int i = 0; i < length; i++) {
9862 try {
9863 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9864 } catch (RemoteException | RuntimeException e) {
9865 loge("Fail to send network activie to listener " + e);
9866 }
9867 }
9868 } finally {
9869 mNetworkActivityListeners.finishBroadcast();
9870 }
9871 }
9872
9873 @GuardedBy("mActiveIdleTimers")
9874 public void handleReportNetworkActivity() {
9875 synchronized (mActiveIdleTimers) {
9876 reportNetworkActive();
9877 }
9878 }
9879
lucaslin1a8b4c62021-01-21 02:02:55 +08009880 // This is deprecated and only to support legacy use cases.
9881 private int transportTypeToLegacyType(int type) {
9882 switch (type) {
9883 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009884 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009885 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009886 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009887 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009888 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009889 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009890 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009891 default:
9892 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9893 }
9894 return ConnectivityManager.TYPE_NONE;
9895 }
9896
9897 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9898 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9899 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9900 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9901 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9902 final long ident = Binder.clearCallingIdentity();
9903 try {
9904 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9905 RECEIVE_DATA_ACTIVITY_CHANGE,
9906 null /* resultReceiver */,
9907 null /* scheduler */,
9908 0 /* initialCode */,
9909 null /* initialData */,
9910 null /* initialExtra */);
9911 } finally {
9912 Binder.restoreCallingIdentity(ident);
9913 }
9914 }
9915
9916 /**
9917 * Setup data activity tracking for the given network.
9918 *
9919 * Every {@code setupDataActivityTracking} should be paired with a
9920 * {@link #removeDataActivityTracking} for cleanup.
9921 */
9922 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9923 final String iface = networkAgent.linkProperties.getInterfaceName();
9924
9925 final int timeout;
9926 final int type;
9927
9928 if (networkAgent.networkCapabilities.hasTransport(
9929 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9930 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009931 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009932 10);
9933 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9934 } else if (networkAgent.networkCapabilities.hasTransport(
9935 NetworkCapabilities.TRANSPORT_WIFI)) {
9936 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009937 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009938 15);
9939 type = NetworkCapabilities.TRANSPORT_WIFI;
9940 } else {
9941 return; // do not track any other networks
9942 }
9943
lucaslinb961efc2021-01-21 02:03:17 +08009944 updateRadioPowerState(true /* isActive */, type);
9945
lucaslin1a8b4c62021-01-21 02:02:55 +08009946 if (timeout > 0 && iface != null) {
9947 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009948 synchronized (mActiveIdleTimers) {
9949 // Networks start up.
9950 mNetworkActive = true;
9951 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9952 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9953 reportNetworkActive();
9954 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009955 } catch (Exception e) {
9956 // You shall not crash!
9957 loge("Exception in setupDataActivityTracking " + e);
9958 }
9959 }
9960 }
9961
9962 /**
9963 * Remove data activity tracking when network disconnects.
9964 */
9965 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9966 final String iface = networkAgent.linkProperties.getInterfaceName();
9967 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9968
lucaslinb961efc2021-01-21 02:03:17 +08009969 if (iface == null) return;
9970
9971 final int type;
9972 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9973 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9974 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9975 type = NetworkCapabilities.TRANSPORT_WIFI;
9976 } else {
9977 return; // do not track any other networks
9978 }
9979
9980 try {
9981 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +08009982 synchronized (mActiveIdleTimers) {
9983 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9984 // The call fails silently if no idle timer setup for this interface
9985 mNetd.idletimerRemoveInterface(iface, params.timeout,
9986 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +08009987 }
lucaslinb961efc2021-01-21 02:03:17 +08009988 } catch (Exception e) {
9989 // You shall not crash!
9990 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +08009991 }
9992 }
9993
9994 /**
9995 * Update data activity tracking when network state is updated.
9996 */
9997 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9998 NetworkAgentInfo oldNetwork) {
9999 if (newNetwork != null) {
10000 setupDataActivityTracking(newNetwork);
10001 }
10002 if (oldNetwork != null) {
10003 removeDataActivityTracking(oldNetwork);
10004 }
10005 }
lucaslinb961efc2021-01-21 02:03:17 +080010006
10007 private void updateRadioPowerState(boolean isActive, int transportType) {
10008 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10009 switch (transportType) {
10010 case NetworkCapabilities.TRANSPORT_CELLULAR:
10011 bs.reportMobileRadioPowerState(isActive, NO_UID);
10012 break;
10013 case NetworkCapabilities.TRANSPORT_WIFI:
10014 bs.reportWifiRadioPowerState(isActive, NO_UID);
10015 break;
10016 default:
10017 logw("Untracked transport type:" + transportType);
10018 }
10019 }
lucaslin1193a5d2021-01-21 02:04:15 +080010020
10021 public boolean isDefaultNetworkActive() {
10022 synchronized (mActiveIdleTimers) {
10023 // If there are no idle timers, it means that system is not monitoring activity,
10024 // so the default network is always considered active.
10025 //
10026 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10027 // tracking is disabled (negative idle timer value configured), or no active default
10028 // network. In the latter case, this reports active but it should report inactive.
10029 return mNetworkActive || mActiveIdleTimers.isEmpty();
10030 }
10031 }
10032
10033 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10034 mNetworkActivityListeners.register(l);
10035 }
10036
10037 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10038 mNetworkActivityListeners.unregister(l);
10039 }
lucaslin012f7a12021-01-21 02:04:35 +080010040
10041 public void dump(IndentingPrintWriter pw) {
10042 synchronized (mActiveIdleTimers) {
10043 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10044 pw.println("Idle timers:");
10045 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10046 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10047 final IdleTimerParams params = ent.getValue();
10048 pw.print(" timeout="); pw.print(params.timeout);
10049 pw.print(" type="); pw.println(params.transportType);
10050 }
10051 }
10052 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010053 }
James Mattis47db0582021-01-01 14:13:35 -080010054
Daniel Brightf9e945b2020-06-15 16:10:01 -070010055 /**
10056 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10057 *
10058 * @param socketInfo the socket information
10059 * @param callback the callback to register
10060 */
10061 @Override
10062 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10063 @NonNull final IQosCallback callback) {
10064 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10065 if (nai == null || nai.networkCapabilities == null) {
10066 try {
10067 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10068 } catch (final RemoteException ex) {
10069 loge("registerQosCallbackInternal: RemoteException", ex);
10070 }
10071 return;
10072 }
10073 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10074 }
10075
10076 /**
10077 * Register a {@link IQosCallback} with base {@link QosFilter}.
10078 *
10079 * @param filter the filter to register
10080 * @param callback the callback to register
10081 * @param nai the agent information related to the filter's network
10082 */
10083 @VisibleForTesting
10084 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10085 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10086 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10087 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10088
10089 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10090 enforceConnectivityRestrictedNetworksPermission();
10091 }
10092 mQosCallbackTracker.registerCallback(callback, filter, nai);
10093 }
10094
10095 /**
10096 * Unregisters the given callback.
10097 *
10098 * @param callback the callback to unregister
10099 */
10100 @Override
10101 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010102 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010103 mQosCallbackTracker.unregisterCallback(callback);
10104 }
James Mattis47db0582021-01-01 14:13:35 -080010105
James Mattis45d81842021-01-10 14:24:24 -080010106 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010107 * Request that a user profile is put by default on a network matching a given preference.
10108 *
10109 * See the documentation for the individual preferences for a description of the supported
10110 * behaviors.
10111 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010112 * @param profile the user profile for whih the preference is being set.
10113 * @param preferences the list of profile network preferences for the
10114 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010115 * @param listener an optional listener to listen for completion of the operation.
10116 */
10117 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010118 public void setProfileNetworkPreferences(
10119 @NonNull final UserHandle profile,
10120 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010121 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010122 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010123 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010124
10125 if (preferences.size() == 0) {
10126 preferences.add((new ProfileNetworkPreference.Builder()).build());
10127 }
10128
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010129 PermissionUtils.enforceNetworkStackPermission(mContext);
10130 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010131 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010132 }
10133 if (profile.getIdentifier() < 0) {
10134 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10135 + "UserHandle.CURRENT not supported)");
10136 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010137 final UserManager um = mContext.getSystemService(UserManager.class);
10138 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010139 throw new IllegalArgumentException("Profile must be a managed profile");
10140 }
paulhuaa0743d2021-05-26 21:56:03 +080010141
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010142 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10143 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010144 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010145 for (final ProfileNetworkPreference preference : preferences) {
10146 final NetworkCapabilities nc;
10147 switch (preference.getPreference()) {
10148 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10149 nc = null;
10150 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010151 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10152 allowFallback = false;
10153 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010154 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010155 final Set<UidRange> uidRangeSet =
10156 getUidListToBeAppliedForNetworkPreference(profile, preference);
10157 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10158 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10159 } else {
10160 throw new IllegalArgumentException(
10161 "Overlapping uid range in setProfileNetworkPreferences");
10162 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010163 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
10164 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10165 break;
10166 default:
10167 throw new IllegalArgumentException(
10168 "Invalid preference in setProfileNetworkPreferences");
10169 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010170 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10171 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010172 }
10173 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010174 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010175 }
10176
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010177 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10178 @NonNull final UserHandle profile,
10179 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10180 final UidRange profileUids = UidRange.createForUser(profile);
10181 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10182 profileNetworkPreference.getIncludedUids());
10183 if (uidRangeSet.size() > 0) {
10184 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10185 throw new IllegalArgumentException(
10186 "Allow uid range is outside the uid range of profile.");
10187 }
10188 } else {
10189 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10190 profileNetworkPreference.getExcludedUids());
10191 if (disallowUidRangeSet.size() > 0) {
10192 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10193 throw new IllegalArgumentException(
10194 "disallow uid range is outside the uid range of profile.");
10195 }
10196 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10197 disallowUidRangeSet);
10198 } else {
10199 uidRangeSet = new ArraySet<UidRange>();
10200 uidRangeSet.add(profileUids);
10201 }
10202 }
10203 return uidRangeSet;
10204 }
10205
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010206 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10207 @Nullable final NetworkCapabilities nc) {
10208 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10209 ensureRequestableCapabilities(nc);
10210 }
10211
10212 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010213 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010214 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010215 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010216 // The NRI for a user should contain the request for capabilities.
10217 // If fallback to default network is needed then NRI should include
10218 // the request for the default network. Create an image of it to
10219 // have the correct UIDs in it (also a request can only be part of one NRI, because
10220 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010221 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10222 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010223 if (pref.allowFallback) {
10224 nrs.add(createDefaultInternetRequestForTransport(
10225 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10226 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010227 if (VDBG) {
10228 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10229 pref.capabilities.getUids()));
10230 }
10231
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010232 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010233 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010234 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010235 result.add(nri);
10236 }
10237 return result;
10238 }
10239
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010240 /**
10241 * Compare if the given UID range sets have the same UIDs.
10242 *
10243 */
10244 private boolean isRangeAlreadyInPreferenceList(
10245 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10246 @NonNull Set<UidRange> uidRangeSet) {
10247 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10248 return false;
10249 }
10250 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10251 if (UidRangeUtils.doesRangeSetOverlap(
10252 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10253 return true;
10254 }
10255 }
10256 return false;
10257 }
10258
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010259 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010260 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010261 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010262 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10263 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10264 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10265 }
paulhu74128522021-09-28 02:29:03 +000010266 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10267 addPerAppDefaultNetworkRequests(
10268 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010269 // Finally, rematch.
10270 rematchAllNetworksAndRequests();
10271
10272 if (null != listener) {
10273 try {
10274 listener.onComplete();
10275 } catch (RemoteException e) {
10276 loge("Listener for setProfileNetworkPreference has died");
10277 }
10278 }
10279 }
10280
paulhu51f77dc2021-06-07 02:34:20 +000010281 @VisibleForTesting
10282 @NonNull
10283 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10284 @NonNull final Set<Integer> uids) {
10285 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10286 if (uids.size() == 0) {
10287 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10288 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10289 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10290 return nris;
10291 }
10292
10293 final List<NetworkRequest> requests = new ArrayList<>();
10294 // The NRI should be comprised of two layers:
10295 // - The request for the mobile network preferred.
10296 // - The request for the default network, for fallback.
10297 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010298 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010299 requests.add(createDefaultInternetRequestForTransport(
10300 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10301 final Set<UidRange> ranges = new ArraySet<>();
10302 for (final int uid : uids) {
10303 ranges.add(new UidRange(uid, uid));
10304 }
10305 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010306 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010307 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010308 return nris;
10309 }
10310
10311 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010312 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010313 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10314 addPerAppDefaultNetworkRequests(
10315 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010316 // Finally, rematch.
10317 rematchAllNetworksAndRequests();
10318 }
10319
James Mattis45d81842021-01-10 14:24:24 -080010320 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010321 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10322 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010323 }
10324
10325 /**
10326 * Used by automotive devices to set the network preferences used to direct traffic at an
10327 * application level as per the given OemNetworkPreferences. An example use-case would be an
10328 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10329 * vehicle via a particular network.
10330 *
10331 * Calling this will overwrite the existing preference.
10332 *
James Mattisda32cfe2021-01-26 16:23:52 -080010333 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010334 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010335 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010336 */
James Mattis47db0582021-01-01 14:13:35 -080010337 @Override
James Mattis45d81842021-01-10 14:24:24 -080010338 public void setOemNetworkPreference(
10339 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010340 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010341
James Mattisfa270db2021-05-31 17:11:10 -070010342 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10343 // Only bypass the permission/device checks if this is a valid test request.
10344 if (isValidTestOemNetworkPreference(preference)) {
10345 enforceManageTestNetworksPermission();
10346 } else {
10347 enforceAutomotiveDevice();
10348 enforceOemNetworkPreferencesPermission();
10349 validateOemNetworkPreferences(preference);
10350 }
James Mattis45d81842021-01-10 14:24:24 -080010351
James Mattis45d81842021-01-10 14:24:24 -080010352 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10353 new Pair<>(preference, listener)));
10354 }
10355
James Mattisfa270db2021-05-31 17:11:10 -070010356 /**
10357 * Check the validity of an OEM network preference to be used for testing purposes.
10358 * @param preference the preference to validate
10359 * @return true if this is a valid OEM network preference test request.
10360 */
10361 private boolean isValidTestOemNetworkPreference(
10362 @NonNull final OemNetworkPreferences preference) {
10363 // Allow for clearing of an existing OemNetworkPreference used for testing.
10364 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10365 // changes after this check is complete. This is an unlikely scenario as calling of this API
10366 // is controlled by the OEM therefore the added complexity is not worth adding given those
10367 // circumstances. That said, it is an edge case to be aware of hence this comment.
10368 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10369 && isTestOemNetworkPreference(mOemNetworkPreferences);
10370 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10371 }
10372
10373 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10374 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10375 return prefMap.size() == 1
10376 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10377 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10378 }
10379
James Mattis45d81842021-01-10 14:24:24 -080010380 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10381 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10382 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010383 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10384 throw new IllegalArgumentException(
10385 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10386 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010387 }
10388 }
10389 }
10390
10391 private void handleSetOemNetworkPreference(
10392 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010393 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010394 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10395 if (DBG) {
10396 log("set OEM network preferences :" + preference.toString());
10397 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010398
James Mattiscb1e0362021-04-06 17:07:42 -070010399 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010400 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10401 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10402 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010403 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010404
10405 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010406 try {
10407 listener.onComplete();
10408 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010409 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010410 }
James Mattis45d81842021-01-10 14:24:24 -080010411 }
10412 }
10413
paulhu74128522021-09-28 02:29:03 +000010414 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010415 // Skip the requests which are set by other network preference. Because the uid range rules
10416 // should stay in netd.
10417 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010418 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010419 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010420 }
10421
James Mattis3ce3d3c2021-02-09 18:18:28 -080010422 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10423 ensureRunningOnConnectivityServiceThread();
10424 mDefaultNetworkRequests.addAll(nris);
10425 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10426 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010427 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010428 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10429 nrisToRegister.addAll(
10430 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10431 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010432 }
10433
10434 /**
10435 * All current requests that are tracking the default network need to be assessed as to whether
10436 * or not the current set of per-application default requests will be changing their default
10437 * network. If so, those requests will need to be updated so that they will send callbacks for
10438 * default network changes at the appropriate time. Additionally, those requests tracking the
10439 * default that were previously updated by this flow will need to be reassessed.
10440 * @return the nris which will need to be updated.
10441 */
10442 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10443 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10444 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10445 // same nri in the map's values for each of its NetworkRequest objects.
10446 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010447 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010448 // Include this nri if it is currently being tracked.
10449 if (isPerAppTrackedNri(nri)) {
10450 defaultCallbackRequests.add(nri);
10451 continue;
10452 }
10453 // We only track callbacks for requests tracking the default.
10454 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10455 continue;
10456 }
10457 // Include this nri if it will be tracked by the new per-app default requests.
10458 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010459 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010460 if (isNriGoingToBeTracked) {
10461 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010462 }
10463 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010464 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010465 }
10466
James Mattis3ce3d3c2021-02-09 18:18:28 -080010467 /**
10468 * Create nris for those network requests that are currently tracking the default network that
10469 * are being controlled by a per-application default.
10470 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10471 * foundation when creating the nri. Important items include the calling uid's original
10472 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10473 * requests are assumed to have already been validated as needing to be updated.
10474 * @return the Set of nris to use when registering network requests.
10475 */
10476 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10477 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10478 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10479 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10480 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010481 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010482
Chalard Jean9473c982021-07-29 20:03:04 +090010483 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010484 if (trackingNri == mDefaultRequest) {
10485 callbackRequestsToRegister.add(new NetworkRequestInfo(
10486 callbackRequest,
10487 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10488 continue;
10489 }
10490
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010491 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010492 callbackRequestsToRegister.add(new NetworkRequestInfo(
10493 callbackRequest,
10494 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010495 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010496 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010497 }
10498 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010499 }
10500
Chalard Jean17215832021-03-01 14:06:28 +090010501 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10502 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010503 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010504 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010505 }
10506 }
10507
James Mattis45d81842021-01-10 14:24:24 -080010508 /**
10509 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10510 */
10511 @VisibleForTesting
10512 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010513 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010514 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010515 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010516 final SparseArray<Set<Integer>> uids =
10517 createUidsFromOemNetworkPreferences(preference);
10518 for (int i = 0; i < uids.size(); i++) {
10519 final int key = uids.keyAt(i);
10520 final Set<Integer> value = uids.valueAt(i);
10521 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10522 // No need to add an nri without any requests.
10523 if (0 == nri.mRequests.size()) {
10524 continue;
10525 }
10526 nris.add(nri);
10527 }
10528
10529 return nris;
10530 }
10531
10532 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10533 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010534 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010535 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010536 final List<UserHandle> users =
10537 mContext.getSystemService(UserManager.class).getUserHandles(true);
10538 if (null == users || users.size() == 0) {
10539 if (VDBG || DDBG) {
10540 log("No users currently available for setting the OEM network preference.");
10541 }
James Mattisb6b6a432021-06-01 22:30:36 -070010542 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010543 }
James Mattis45d81842021-01-10 14:24:24 -080010544 for (final Map.Entry<String, Integer> entry :
10545 preference.getNetworkPreferences().entrySet()) {
10546 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010547 // Add the rules for all users as this policy is device wide.
10548 for (final UserHandle user : users) {
10549 try {
10550 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10551 if (!prefToUids.contains(pref)) {
10552 prefToUids.put(pref, new ArraySet<>());
10553 }
10554 prefToUids.get(pref).add(uid);
10555 } catch (PackageManager.NameNotFoundException e) {
10556 // Although this may seem like an error scenario, it is ok that uninstalled
10557 // packages are sent on a network preference as the system will watch for
10558 // package installations associated with this network preference and update
10559 // accordingly. This is done to minimize race conditions on app install.
10560 continue;
James Mattis45d81842021-01-10 14:24:24 -080010561 }
James Mattis45d81842021-01-10 14:24:24 -080010562 }
10563 }
James Mattisb6b6a432021-06-01 22:30:36 -070010564 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010565 }
10566
10567 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10568 @OemNetworkPreferences.OemNetworkPreference final int preference,
10569 @NonNull final Set<Integer> uids) {
10570 final List<NetworkRequest> requests = new ArrayList<>();
10571 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10572 switch (preference) {
10573 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10574 requests.add(createUnmeteredNetworkRequest());
10575 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010576 requests.add(createDefaultInternetRequestForTransport(
10577 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010578 break;
10579 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10580 requests.add(createUnmeteredNetworkRequest());
10581 requests.add(createOemPaidNetworkRequest());
10582 break;
10583 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10584 requests.add(createOemPaidNetworkRequest());
10585 break;
10586 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10587 requests.add(createOemPrivateNetworkRequest());
10588 break;
James Mattisfa270db2021-05-31 17:11:10 -070010589 case OEM_NETWORK_PREFERENCE_TEST:
10590 requests.add(createUnmeteredNetworkRequest());
10591 requests.add(createTestNetworkRequest());
10592 requests.add(createDefaultRequest());
10593 break;
10594 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10595 requests.add(createTestNetworkRequest());
10596 break;
James Mattis45d81842021-01-10 14:24:24 -080010597 default:
10598 // This should never happen.
10599 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10600 + " called with invalid preference of " + preference);
10601 }
10602
James Mattisfa270db2021-05-31 17:11:10 -070010603 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010604 for (final int uid : uids) {
10605 ranges.add(new UidRange(uid, uid));
10606 }
10607 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010608 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010609 }
10610
10611 private NetworkRequest createUnmeteredNetworkRequest() {
10612 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10613 .addCapability(NET_CAPABILITY_NOT_METERED)
10614 .addCapability(NET_CAPABILITY_VALIDATED);
10615 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10616 }
10617
10618 private NetworkRequest createOemPaidNetworkRequest() {
10619 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10620 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10621 .addCapability(NET_CAPABILITY_OEM_PAID)
10622 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10623 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10624 }
10625
10626 private NetworkRequest createOemPrivateNetworkRequest() {
10627 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10628 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10629 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10630 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10631 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10632 }
10633
10634 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010635 final NetworkCapabilities netcap = new NetworkCapabilities();
10636 netcap.addCapability(NET_CAPABILITY_INTERNET);
10637 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10638 return netcap;
10639 }
10640
10641 private NetworkRequest createTestNetworkRequest() {
10642 final NetworkCapabilities netcap = new NetworkCapabilities();
10643 netcap.clearAll();
10644 netcap.addTransportType(TRANSPORT_TEST);
10645 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010646 }
James Mattis47db0582021-01-01 14:13:35 -080010647 }
markchien738ad912021-12-09 18:15:45 +080010648
10649 @Override
10650 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10651 enforceNetworkStackOrSettingsPermission();
10652
10653 try {
10654 if (add) {
10655 mNetd.bandwidthAddNiceApp(uid);
10656 } else {
10657 mNetd.bandwidthRemoveNiceApp(uid);
10658 }
10659 } catch (RemoteException | ServiceSpecificException e) {
10660 throw new IllegalStateException(e);
10661 }
10662 }
10663
10664 @Override
10665 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10666 enforceNetworkStackOrSettingsPermission();
10667
10668 try {
10669 if (add) {
10670 mNetd.bandwidthAddNaughtyApp(uid);
10671 } else {
10672 mNetd.bandwidthRemoveNaughtyApp(uid);
10673 }
10674 } catch (RemoteException | ServiceSpecificException e) {
10675 throw new IllegalStateException(e);
10676 }
10677 }
markchiene1561fa2021-12-09 22:00:56 +080010678
10679 @Override
10680 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10681 enforceNetworkStackOrSettingsPermission();
10682
10683 try {
10684 mNetd.firewallSetUidRule(chain, uid,
10685 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
10686 } catch (RemoteException | ServiceSpecificException e) {
10687 throw new IllegalStateException(e);
10688 }
10689 }
markchien98a6f952022-01-13 23:43:53 +080010690
10691 @Override
10692 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10693 enforceNetworkStackOrSettingsPermission();
10694
10695 try {
10696 mNetd.firewallEnableChildChain(chain, enable);
10697 } catch (RemoteException | ServiceSpecificException e) {
10698 throw new IllegalStateException(e);
10699 }
10700 }
10701
markchien00a0bed2022-01-13 23:46:13 +080010702 @Override
10703 public void replaceFirewallChain(final int chain, final int[] uids) {
10704 enforceNetworkStackOrSettingsPermission();
10705
10706 try {
10707 switch (chain) {
10708 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
10709 mNetd.firewallReplaceUidChain("fw_dozable", true /* isAllowList */, uids);
10710 break;
10711 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
10712 mNetd.firewallReplaceUidChain("fw_standby", false /* isAllowList */, uids);
10713 break;
10714 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
10715 mNetd.firewallReplaceUidChain("fw_powersave", true /* isAllowList */, uids);
10716 break;
10717 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
10718 mNetd.firewallReplaceUidChain("fw_restricted", true /* isAllowList */, uids);
10719 break;
10720 default:
10721 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10722 + chain);
10723 }
10724 } catch (RemoteException | ServiceSpecificException e) {
10725 throw new IllegalStateException(e);
10726 }
10727 }
markchien9c806112022-01-11 23:28:23 +080010728
10729 @Override
10730 public void swapActiveStatsMap() {
10731 enforceNetworkStackOrSettingsPermission();
10732 try {
10733 mNetd.trafficSwapActiveStatsMap();
10734 } catch (RemoteException | ServiceSpecificException e) {
10735 throw new IllegalStateException(e);
10736 }
10737 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010738}