blob: 359a3bde76a17fb64ca4bc3c1ee470643ec34a3e [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;
markchien3c04e662022-03-22 16:29:56 +080037import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
38import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090040import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090041import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090042import static android.net.ConnectivityManager.TYPE_MOBILE;
43import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
44import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
45import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
46import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
47import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
48import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
49import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
50import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
51import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070052import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090053import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070054import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090055import static android.net.ConnectivityManager.TYPE_WIFI;
56import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070057import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070058import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080059import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080061import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070062import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040064import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080075import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
76import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080079import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
80import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080081import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
82import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
83import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090084import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090085import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060086import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070087import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080088import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090089import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070090import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
91import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070092import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080093import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090094import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Patrick Rohr2857ac42022-01-21 14:58:16 +010095import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070096import static android.system.OsConstants.IPPROTO_TCP;
97import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060098
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090099import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900100import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
paulhu3ffffe72021-09-16 10:15:22 +0800101import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
102import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
103import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900104
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800105import static java.util.Map.Entry;
106
Chalard Jean5b639762020-03-09 21:25:37 +0900107import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000108import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800109import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800110import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800111import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800112import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700113import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700114import android.app.admin.DevicePolicyManager;
junyulaie7c7d2a2021-01-26 15:29:15 +0800115import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700116import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800117import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700121import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800122import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700123import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900124import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900125import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700126import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800127import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800128import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900130import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800131import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900132import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900133import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800134import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900135import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800136import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700137import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900138import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800139import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800140import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800141import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800142import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800143import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900144import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900145import android.net.INetworkMonitor;
146import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900147import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900148import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700149import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800150import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900151import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900152import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900153import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800154import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100155import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800156import android.net.NativeNetworkConfig;
157import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800158import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700159import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700160import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900161import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700162import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700164import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900165import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900166import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000167import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900168import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700169import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900170import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700171import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900172import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700173import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800174import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900175import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700176import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000177import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800178import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900179import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800180import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400181import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700182import android.net.QosCallbackException;
183import android.net.QosFilter;
184import android.net.QosSocketFilter;
185import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700186import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800187import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800188import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800189import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900190import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400191import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800192import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800193import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400194import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800195import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900196import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900197import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900198import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800199import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900200import android.net.networkstack.ModuleNetworkStackClient;
201import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900202import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800203import android.net.resolv.aidl.DnsHealthEventParcel;
204import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
205import android.net.resolv.aidl.Nat64PrefixEventParcel;
206import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900207import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900208import android.net.util.MultinetworkPolicyTracker;
he_won.hwang881307a2022-03-15 21:23:52 +0900209import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800210import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800212import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700213import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700215import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217import android.os.Looper;
218import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700219import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700220import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900221import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800222import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700223import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700224import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800225import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900227import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900228import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700229import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700230import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400231import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900233import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700234import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700235import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700236import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800237import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900238import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000239import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600240import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900241import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700242import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700243import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800244
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900245import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400246import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400247import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700248import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900249import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800250import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900251import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800252import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900253import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900254import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100255import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900256import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
257import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900258import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800259import com.android.net.module.util.NetworkCapabilitiesUtils;
Junyu Lai00d92df2022-07-05 11:01:52 +0800260import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800261import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100262import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000263import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900264import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800265import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800266import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900267import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900268import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500269import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700270import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900271import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900272import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100273import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700274import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700275import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600276import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900277import com.android.server.connectivity.NetworkNotificationManager;
278import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900279import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900280import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700281import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800282import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900283import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700284import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800285import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600286
Josh Gao461a1222020-06-16 15:58:11 -0700287import libcore.io.IoUtils;
288
The Android Open Source Project28527d22009-03-03 19:31:44 -0800289import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100290import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800291import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900292import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700293import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700294import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900295import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700296import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700297import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700298import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700299import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800300import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900301import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800302import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700303import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700304import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700305import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700306import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900307import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700308import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900309import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600310import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900311import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600312import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900313import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800314
315/**
316 * @hide
317 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800318public class ConnectivityService extends IConnectivityManager.Stub
319 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900320 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800321
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900322 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900323 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900324 private static final String NETWORK_ARG = "networks";
325 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800326 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900327
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900328 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900329 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
330 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800331
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900332 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700333
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100334 /**
335 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
336 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800337 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100338 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
339 * (preferably via runtime resource overlays).
340 */
341 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
342 "http://connectivitycheck.gstatic.com/generate_204";
343
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700344 // TODO: create better separation between radio types and network types
345
Robert Greenwalt2034b912009-08-12 16:08:25 -0700346 // how long to wait before switching back to a radio's default network
347 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
348 // system property that can override the above value
349 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
350 "android.telephony.apn-restore";
351
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900352 // How long to wait before putting up a "This network doesn't have an Internet connection,
353 // connect anyway?" dialog after the user selects a network that doesn't validate.
354 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
355
junyulai0ac374f2020-12-14 18:41:52 +0800356 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900357 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
358 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800359 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700360
he_won.hwang881307a2022-03-15 21:23:52 +0900361 // The maximum value for the blocking validation result, in milliseconds.
362 public static final int MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS = 10000;
363
Daniel Brightf9e945b2020-06-15 16:10:01 -0700364 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900365 @VisibleForTesting
366 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700367
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900368 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700369 @VisibleForTesting
370 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900371
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900372 @VisibleForTesting
373 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800374 @VisibleForTesting
375 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900376 // True if the cell radio of the device is capable of time-sharing.
377 @VisibleForTesting
378 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900379
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800380 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800381 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800382 private final int mReleasePendingIntentDelayMs;
383
Chalard Jean46bfbf02022-02-02 00:56:25 +0900384 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900385
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000386 @VisibleForTesting
387 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700388
Chalard Jean9473c982021-07-29 20:03:04 +0900389 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800390 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700391 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800392 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700393
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900394 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700395
junyulaif2c67e42018-08-07 19:50:45 +0800396 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000397 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
398 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800399 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900400 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800401
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900402 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900403 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000404 // The Context is created for UserHandle.ALL.
405 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900406 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900407 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700408 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700409 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800410
Chenbo Feng15416292018-11-08 17:36:21 -0800411 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800412 protected IDnsResolver mDnsResolver;
413 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800414 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700415 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900416 private final NetworkStatsManager mStatsManager;
417 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800418 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700419
Benedict Wong493e04b2018-11-09 14:45:34 -0800420 /**
421 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
422 * instances.
423 */
424 @GuardedBy("mTNSLock")
425 private TestNetworkService mTNS;
426
427 private final Object mTNSLock = new Object();
428
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700429 private String mCurrentTcpBufferSizes;
430
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900431 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800432 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900433
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500434 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400435 // Tear down networks that have no chance (e.g. even if validated) of becoming
436 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500437 // all networks have been rematched against all NetworkRequests.
438 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400439 // Don't reap networks. This should be passed when some networks have not yet been
440 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500441 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900442 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500443
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900444 private enum UnneededFor {
445 LINGER, // Determine whether this network is unneeded and should be lingered.
446 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
447 }
448
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700449 /**
paulhuaa0743d2021-05-26 21:56:03 +0800450 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800451 * should have priority. The order is passed to netd which will use it together
452 * with UID ranges to generate the corresponding IP rule. This serves to
453 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800454 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800455 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000456 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800457 *
paulhu48291862021-07-14 14:53:57 +0800458 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
459 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800460 */
paulhu48291862021-07-14 14:53:57 +0800461 // Used when sending to netd to code for "no order".
462 static final int PREFERENCE_ORDER_NONE = 0;
463 // Order for requests that don't code for a per-app preference. As it is
464 // out of the valid range, the corresponding order should be
465 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800466 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800467 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800468 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800469 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
470 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800471 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800472 static final int PREFERENCE_ORDER_OEM = 10;
473 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800474 // See {@link #setProfileNetworkPreference}.
475 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800476 static final int PREFERENCE_ORDER_PROFILE = 20;
477 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800478 // better scores are connected.
479 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800480 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800481 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900482 // Preference order that signifies the network shouldn't be set as a default network for
483 // the UIDs, only give them access to it. TODO : replace this with a boolean
484 // in NativeUidRangeConfig
485 @VisibleForTesting
486 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
487 // Bound for the lowest valid preference order.
488 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800489
490 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700491 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700492 * from one net to another. Clear happens when we get a new
493 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
494 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700495 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700496 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700497
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700498 /**
499 * used internally to reload global proxy settings
500 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700501 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700502
Robert Greenwalt34848c02011-03-25 13:09:25 -0700503 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400504 * PAC manager has received new port.
505 */
506 private static final int EVENT_PROXY_HAS_CHANGED = 16;
507
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700508 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900509 * used internally when registering NetworkProviders
510 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700511 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900512 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700513
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700514 /**
515 * used internally when registering NetworkAgents
516 * obj = Messenger
517 */
518 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
519
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700520 /**
521 * used to add a network request
522 * includes a NetworkRequestInfo
523 */
524 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
525
526 /**
527 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900528 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700529 * cancel it.
530 * includes a NetworkRequestInfo
531 */
532 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
533
534 /**
535 * used to add a network listener - no request
536 * includes a NetworkRequestInfo
537 */
538 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
539
540 /**
541 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400542 * arg1 = UID of caller
543 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700544 */
545 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
546
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700547 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900548 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700549 * obj = Messenger
550 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900551 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700552
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700553 /**
554 * used internally to expire a wakelock when transitioning
555 * from one net to another. Expire happens when we fail to find
556 * a new network (typically after 1 minute) -
557 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
558 * a replacement network.
559 */
560 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
561
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700562 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800563 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400564 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800565 */
566 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
567
568 /**
569 * used to remove a pending intent and its associated network request.
570 * arg1 = UID of caller
571 * obj = PendingIntent
572 */
573 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
574
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900575 /**
576 * used to specify whether a network should be used even if unvalidated.
577 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
578 * arg2 = whether to remember this choice in the future (1 or 0)
579 * obj = network
580 */
581 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
582
583 /**
584 * used to ask the user to confirm a connection to an unvalidated network.
585 * obj = network
586 */
587 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700588
Erik Kline05f2b402015-04-30 12:58:40 +0900589 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700590 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900591 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700592 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900593
Paul Jensenc8873fc2015-06-17 14:15:39 -0400594 /**
595 * used to add a network listener with a pending intent
596 * obj = NetworkRequestInfo
597 */
598 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
599
Hugo Benichid6b510a2017-04-06 17:22:18 +0900600 /**
601 * used to specify whether a network should not be penalized when it becomes unvalidated.
602 */
603 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
604
605 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700606 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900607 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700608 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900609
Erik Kline31b4a9e2018-01-11 21:07:29 +0900610 // Handle changes in Private DNS settings.
611 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
612
dalyk1720e542018-03-05 12:42:22 -0500613 // Handle private DNS validation status updates.
614 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
615
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900616 /**
617 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
618 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800619 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
620 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
621 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900622 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900623 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900624
625 /**
626 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
627 * config was resolved.
628 * obj = PrivateDnsConfig
629 * arg2 = netid
630 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900631 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900632
633 /**
634 * Request ConnectivityService display provisioning notification.
635 * arg1 = Whether to make the notification visible.
636 * arg2 = NetID.
637 * obj = Intent to be launched when notification selected by user, null if !arg1.
638 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900639 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900640
641 /**
lucaslin2240ef62019-03-12 13:08:03 +0800642 * Used to specify whether a network should be used even if connectivity is partial.
643 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
644 * false)
645 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
646 * obj = network
647 */
lucaslin444d43a2020-02-20 16:56:59 +0800648 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800649
650 /**
lucasline117e2e2019-10-22 18:27:33 +0800651 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
652 * Both of the arguments are bitmasks, and the value of bits come from
653 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900654 * arg1 = unused
655 * arg2 = netId
656 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800657 */
lucaslin444d43a2020-02-20 16:56:59 +0800658 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800659
660 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900661 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
662 * arg1 = unused
663 * arg2 = netId
664 * obj = captive portal data
665 */
lucaslin444d43a2020-02-20 16:56:59 +0800666 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900667
668 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900669 * Used by setRequireVpnForUids.
670 * arg1 = whether the specified UID ranges are required to use a VPN.
671 * obj = Array of UidRange objects.
672 */
673 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
674
675 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900676 * Used internally when setting the default networks for OemNetworkPreferences.
677 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800678 */
679 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
680
681 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800682 * Used to indicate the system default network becomes active.
683 */
684 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
685
686 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900687 * Used internally when setting a network preference for a user profile.
688 * obj = Pair<ProfileNetworkPreference, Listener>
689 */
690 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
691
692 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000693 * Event to specify that reasons for why an uid is blocked changed.
694 * arg1 = uid
695 * arg2 = blockedReasons
696 */
697 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
698
699 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900700 * Event to register a new network offer
701 * obj = NetworkOffer
702 */
703 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
704
705 /**
706 * Event to unregister an existing network offer
707 * obj = INetworkOfferCallback
708 */
709 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
710
711 /**
paulhu51f77dc2021-06-07 02:34:20 +0000712 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
713 */
714 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
715
716 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800717 * Event to set temporary allow bad wifi within a limited time to override
718 * {@code config_networkAvoidBadWifi}.
719 */
720 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
721
722 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100723 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
724 */
725 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
726
727 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900728 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
729 * should be shown.
730 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900731 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900732
733 /**
734 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
735 * should be hidden.
736 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900737 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900738
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800739 /**
740 * The maximum alive time to allow bad wifi configuration for testing.
741 */
742 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
743
Patrick Rohr2857ac42022-01-21 14:58:16 +0100744 /**
745 * The priority of the tc police rate limiter -- smaller value is higher priority.
746 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
747 */
748 private static final short TC_PRIO_POLICE = 1;
749
750 /**
751 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
752 */
753 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700754 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100755
Hugo Benichi47011212017-03-30 10:46:05 +0900756 private static String eventName(int what) {
757 return sMagicDecoderRing.get(what, Integer.toString(what));
758 }
759
paulhua10d8212020-11-10 15:32:56 +0800760 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900761 final DnsResolverServiceManager dsm = context.getSystemService(
762 DnsResolverServiceManager.class);
763 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800764 }
765
Cody Kesting73708bf2019-12-18 10:57:50 -0800766 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900767 @VisibleForTesting
768 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700769 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700770 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700771 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700772 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800773 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
774 @VisibleForTesting
775 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
776
Erik Kline32120082017-12-13 19:40:49 +0900777 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900778 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700779
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400780 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800781 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400782
Chalard Jean46bfbf02022-02-02 00:56:25 +0900783 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800784 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700785
Chalard Jean5d70ba42018-06-07 16:44:04 +0900786 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
787 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000788 @VisibleForTesting
789 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400790
Erik Kline05f2b402015-04-30 12:58:40 +0900791 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700792
Chalard Jean46bfbf02022-02-02 00:56:25 +0900793 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400794
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700795 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900796 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700797
Valentin Iftime9fa35092019-09-24 13:32:13 +0200798 private Set<String> mWolSupportedInterfaces;
799
Roshan Pius08c94fb2020-01-16 12:17:17 -0800800 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800801 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800802 private final AppOpsManager mAppOpsManager;
803
804 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400805
Chalard Jean46bfbf02022-02-02 00:56:25 +0900806 private final KeepaliveTracker mKeepaliveTracker;
807 private final QosCallbackTracker mQosCallbackTracker;
808 private final NetworkNotificationManager mNotifier;
809 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900810
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700811 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800812 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700813
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900814 // Sequence number for NetworkProvider IDs.
815 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
816 NetworkProvider.FIRST_PROVIDER_ID);
817
Erik Klineedf878b2015-07-09 18:24:03 +0900818 // NetworkRequest activity String log entries.
819 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
820 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
821
Hugo Benichid159fdd2016-07-11 11:05:12 +0900822 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900823 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900824 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
825
Hugo Benichi47011212017-03-30 10:46:05 +0900826 private static final int MAX_WAKELOCK_LOGS = 20;
827 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900828 private int mTotalWakelockAcquisitions = 0;
829 private int mTotalWakelockReleases = 0;
830 private long mTotalWakelockDurationMs = 0;
831 private long mMaxWakelockDurationMs = 0;
832 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900833
Hugo Benichi208c0102016-07-28 17:53:06 +0900834 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900835
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700836 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900837 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700838
Erik Kline95ecfee2016-10-02 18:02:14 +0900839 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900840 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900841
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900842 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800843 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
844 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800845
Patrick Rohr2857ac42022-01-21 14:58:16 +0100846 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
847 // configured via {@link
848 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
849 // Only the handler thread is allowed to access this field.
850 private long mIngressRateLimit = -1;
851
Robert Greenwalt802c1102014-06-02 15:32:02 -0700852 /**
853 * Implements support for the legacy "one network per network type" model.
854 *
855 * We used to have a static array of NetworkStateTrackers, one for each
856 * network type, but that doesn't work any more now that we can have,
857 * for example, more that one wifi network. This class stores all the
858 * NetworkAgentInfo objects that support a given type, but the legacy
859 * API will only see the first one.
860 *
861 * It serves two main purposes:
862 *
863 * 1. Provide information about "the network for a given type" (since this
864 * API only supports one).
865 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
866 * the first network for a given type changes, or if the default network
867 * changes.
868 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900869 @VisibleForTesting
870 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900871
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900872 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900873 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900874
Robert Greenwalt802c1102014-06-02 15:32:02 -0700875 /**
876 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
877 * Each list holds references to all NetworkAgentInfos that are used to
878 * satisfy requests for that network type.
879 *
880 * This array is built out at startup such that an unsupported network
881 * doesn't get an ArrayList instance, making this a tristate:
882 * unsupported, supported but not active and active.
883 *
884 * The actual lists are populated when we scan the network types that
885 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900886 *
887 * Threading model:
888 * - addSupportedType() is only called in the constructor
889 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
890 * They are therefore not thread-safe with respect to each other.
891 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
892 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900893 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900894 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700895 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900896 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900897 @NonNull
898 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700899
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900900 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
901 // an entry have no timer (equivalent to -1). Lazily loaded.
902 @NonNull
903 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
904
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900905 LegacyTypeTracker(@NonNull ConnectivityService service) {
906 mService = service;
907 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700908 }
909
Chiachang Wang3bc52762021-11-25 14:17:57 +0800910 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
911 // addressed.
912 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900913 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
914 final PackageManager pm = ctx.getPackageManager();
915 if (pm.hasSystemFeature(FEATURE_WIFI)) {
916 addSupportedType(TYPE_WIFI);
917 }
918 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
919 addSupportedType(TYPE_WIFI_P2P);
920 }
921 if (tm.isDataCapable()) {
922 // Telephony does not have granular support for these types: they are either all
923 // supported, or none is supported
924 addSupportedType(TYPE_MOBILE);
925 addSupportedType(TYPE_MOBILE_MMS);
926 addSupportedType(TYPE_MOBILE_SUPL);
927 addSupportedType(TYPE_MOBILE_DUN);
928 addSupportedType(TYPE_MOBILE_HIPRI);
929 addSupportedType(TYPE_MOBILE_FOTA);
930 addSupportedType(TYPE_MOBILE_IMS);
931 addSupportedType(TYPE_MOBILE_CBS);
932 addSupportedType(TYPE_MOBILE_IA);
933 addSupportedType(TYPE_MOBILE_EMERGENCY);
934 }
935 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
936 addSupportedType(TYPE_BLUETOOTH);
937 }
938 if (pm.hasSystemFeature(FEATURE_WATCH)) {
939 // TYPE_PROXY is only used on Wear
940 addSupportedType(TYPE_PROXY);
941 }
942 // Ethernet is often not specified in the configs, although many devices can use it via
943 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000944 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900945 addSupportedType(TYPE_ETHERNET);
946 }
947
948 // Always add TYPE_VPN as a supported type
949 addSupportedType(TYPE_VPN);
950 }
951
952 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700953 if (mTypeLists[type] != null) {
954 throw new IllegalStateException(
955 "legacy list for type " + type + "already initialized");
956 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900957 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700958 }
959
Robert Greenwalt802c1102014-06-02 15:32:02 -0700960 public boolean isTypeSupported(int type) {
961 return isNetworkTypeValid(type) && mTypeLists[type] != null;
962 }
963
964 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900965 synchronized (mTypeLists) {
966 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
967 return mTypeLists[type].get(0);
968 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700969 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900970 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700971 }
972
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900973 public int getRestoreTimerForType(int type) {
974 synchronized (mTypeLists) {
975 if (mRestoreTimers == null) {
976 mRestoreTimers = loadRestoreTimers();
977 }
978 return mRestoreTimers.getOrDefault(type, -1);
979 }
980 }
981
982 private ArrayMap<Integer, Integer> loadRestoreTimers() {
983 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900984 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900985 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
986 for (final String config : configs) {
987 final String[] splits = TextUtils.split(config, ",");
988 if (splits.length != 2) {
989 logwtf("Invalid restore timer token count: " + config);
990 continue;
991 }
992 try {
993 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
994 } catch (NumberFormatException e) {
995 logwtf("Invalid restore timer number format: " + config, e);
996 }
997 }
998 return ret;
999 }
1000
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001001 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001002 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001003 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001004 log("Sending " + state
1005 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001006 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001007 }
1008 }
1009
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001010 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1011 // network type, to preserve previous behaviour.
1012 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1013 if (vpnNai != mService.getLegacyLockdownNai()) return;
1014
1015 if (vpnNai.declaredUnderlyingNetworks == null
1016 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1017 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1018 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1019 return;
1020 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001021 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001022 vpnNai.declaredUnderlyingNetworks[0]);
1023 if (underlyingNai == null) return;
1024
1025 final int type = underlyingNai.networkInfo.getType();
1026 final DetailedState state = DetailedState.CONNECTED;
1027 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1028 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1029 }
1030
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001031 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001032 public void add(int type, NetworkAgentInfo nai) {
1033 if (!isTypeSupported(type)) {
1034 return; // Invalid network type.
1035 }
1036 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1037
1038 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1039 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001040 return;
1041 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001042 synchronized (mTypeLists) {
1043 list.add(nai);
1044 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001045
Chalard Jean5b409c72021-02-04 13:12:59 +09001046 // Send a broadcast if this is the first network of its type or if it's the default.
1047 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001048
1049 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1050 // to preserve previous behaviour.
1051 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001052 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001053 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1054 mService.sendLegacyNetworkBroadcast(nai, state, type);
1055 }
1056
1057 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1058 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001059 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001060 }
1061
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001062 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001063 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001064 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1065 if (list == null || list.isEmpty()) {
1066 return;
1067 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001068 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001069
Hugo Benichi389633f2016-06-21 09:48:07 +09001070 synchronized (mTypeLists) {
1071 if (!list.remove(nai)) {
1072 return;
1073 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001074 }
1075
Lorenzo Colitti49767722015-05-01 00:30:10 +09001076 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001077 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1078 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001079 }
1080
1081 if (!list.isEmpty() && wasFirstNetwork) {
1082 if (DBG) log("Other network available for type " + type +
1083 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001084 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001085 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001086 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001087 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001088 }
1089 }
1090
1091 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001092 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1093 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001095 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001096 }
1097 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001098
Chalard Jean46bfbf02022-02-02 00:56:25 +09001099 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001100 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001101 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001102 final DetailedState state = nai.networkInfo.getDetailedState();
1103 for (int type = 0; type < mTypeLists.length; type++) {
1104 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001105 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001106 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001107 if (isFirst || contains && isDefault) {
1108 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001109 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001110 }
1111 }
1112 }
1113
Robert Greenwalt94e22142014-07-30 16:31:24 -07001114 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001115 pw.println("mLegacyTypeTracker:");
1116 pw.increaseIndent();
1117 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001118 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001119 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001120 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001121 pw.println();
1122 pw.println("Current state:");
1123 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001124 synchronized (mTypeLists) {
1125 for (int type = 0; type < mTypeLists.length; type++) {
1126 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1127 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001128 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001129 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001130 }
1131 }
1132 pw.decreaseIndent();
1133 pw.decreaseIndent();
1134 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001135 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001136 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001137 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001138
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001139 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001140 /**
1141 * Helper class which parses out priority arguments and dumps sections according to their
1142 * priority. If priority arguments are omitted, function calls the legacy dump command.
1143 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001144 private class LocalPriorityDump {
1145 private static final String PRIORITY_ARG = "--dump-priority";
1146 private static final String PRIORITY_ARG_HIGH = "HIGH";
1147 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1148
1149 LocalPriorityDump() {}
1150
1151 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1152 doDump(fd, pw, new String[] {DIAG_ARG});
1153 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001154 }
1155
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001156 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1157 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001158 }
1159
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001160 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1161 if (args == null) {
1162 dumpNormal(fd, pw, args);
1163 return;
1164 }
1165
1166 String priority = null;
1167 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1168 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1169 argIndex++;
1170 priority = args[argIndex];
1171 }
1172 }
1173
1174 if (PRIORITY_ARG_HIGH.equals(priority)) {
1175 dumpHigh(fd, pw);
1176 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1177 dumpNormal(fd, pw, args);
1178 } else {
1179 // ConnectivityService publishes binder service using publishBinderService() with
1180 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001181 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1182 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001183 // TODO: Integrate into signal dump.
1184 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001185 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001186 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001187 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001188
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001189 /**
1190 * Dependencies of ConnectivityService, for injection in tests.
1191 */
1192 @VisibleForTesting
1193 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001194 public int getCallingUid() {
1195 return Binder.getCallingUid();
1196 }
1197
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001198 /**
1199 * Get system properties to use in ConnectivityService.
1200 */
1201 public MockableSystemProperties getSystemProperties() {
1202 return new MockableSystemProperties();
1203 }
1204
1205 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001206 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1207 */
1208 public ConnectivityResources getResources(@NonNull Context ctx) {
1209 return new ConnectivityResources(ctx);
1210 }
1211
1212 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001213 * Create a HandlerThread to use in ConnectivityService.
1214 */
1215 public HandlerThread makeHandlerThread() {
1216 return new HandlerThread("ConnectivityServiceThread");
1217 }
1218
1219 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001220 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001221 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001222 public NetworkStackClientBase getNetworkStack() {
1223 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001224 }
1225
1226 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001227 * @see ProxyTracker
1228 */
1229 public ProxyTracker makeProxyTracker(@NonNull Context context,
1230 @NonNull Handler connServiceHandler) {
1231 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1232 }
1233
1234 /**
1235 * @see NetIdManager
1236 */
1237 public NetIdManager makeNetIdManager() {
1238 return new NetIdManager();
1239 }
1240
1241 /**
1242 * @see NetworkUtils#queryUserAccess(int, int)
1243 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001244 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1245 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001246 }
1247
1248 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001249 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1250 * requires CAP_NET_ADMIN, which the unit tests do not have.
1251 */
1252 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1253 InetSocketAddress remote) {
1254 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1255 }
1256
1257 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001258 * @see MultinetworkPolicyTracker
1259 */
1260 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1261 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1262 return new MultinetworkPolicyTracker(c, h, r);
1263 }
1264
Aaron Huang330a4c02020-10-27 03:36:19 +08001265 /**
1266 * @see BatteryStatsManager
1267 */
1268 public void reportNetworkInterfaceForTransports(Context context, String iface,
1269 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001270 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001271 context.getSystemService(BatteryStatsManager.class);
1272 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1273 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001274
1275 public boolean getCellular464XlatEnabled() {
1276 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1277 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001278
1279 /**
1280 * @see PendingIntent#intentFilterEquals
1281 */
1282 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1283 return a.intentFilterEquals(b);
1284 }
1285
1286 /**
1287 * @see LocationPermissionChecker
1288 */
1289 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1290 return new LocationPermissionChecker(context);
1291 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001292
1293 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001294 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001295 *
1296 * This method returns null in versions before T, where carrier privilege
1297 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001298 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001299 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001300 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1301 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1302 if (SdkLevel.isAtLeastT()) {
1303 return new CarrierPrivilegeAuthenticator(context, tm);
1304 } else {
1305 return null;
1306 }
1307 }
1308
1309 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001310 * @see DeviceConfigUtils#isFeatureEnabled
1311 */
1312 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1313 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1314 TETHERING_MODULE_NAME, defaultEnabled);
1315 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001316
1317 /**
1318 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001319 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001320 * @return BpfNetMaps implementation.
1321 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001322 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1323 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001324 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001325
1326 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001327 * @see ClatCoordinator
1328 */
1329 public ClatCoordinator getClatCoordinator(INetd netd) {
1330 return new ClatCoordinator(
1331 new ClatCoordinator.Dependencies() {
1332 @NonNull
1333 public INetd getNetd() {
1334 return netd;
1335 }
1336 });
1337 }
1338
1339 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001340 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1341 */
1342 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1343 final InterfaceParams params = InterfaceParams.getByName(iface);
1344 if (params == null) {
1345 // the interface might have disappeared.
1346 logw("Failed to get interface params for interface " + iface);
1347 return;
1348 }
1349 try {
1350 // converting rateInBytesPerSecond from long to int is safe here because the
1351 // setting's range is limited to INT_MAX.
1352 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001353 Log.i(TAG,
1354 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001355 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1356 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1357 } catch (IOException e) {
1358 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1359 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1360 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1361 + ") failure: ", e);
1362 }
1363 }
1364
1365 /**
1366 * Wraps {@link TcUtils#tcFilterDelDev}
1367 */
1368 public void disableIngressRateLimit(String iface) {
1369 final InterfaceParams params = InterfaceParams.getByName(iface);
1370 if (params == null) {
1371 // the interface might have disappeared.
1372 logw("Failed to get interface params for interface " + iface);
1373 return;
1374 }
1375 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001376 Log.i(TAG,
1377 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001378 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1379 } catch (IOException e) {
1380 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1381 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1382 }
1383 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 }
1385
junyulaie7c7d2a2021-01-26 15:29:15 +08001386 public ConnectivityService(Context context) {
1387 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001388 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1389 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001390 }
1391
1392 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001393 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1394 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001395 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001396
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001397 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001398 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001399 mSystemProperties = mDeps.getSystemProperties();
1400 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001401 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001402 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001403 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1404 // Pass limit - 1 to maintain backward compatibility.
1405 // TODO: Remove the workaround.
1406 mNetworkRequestCounter =
1407 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1408 mSystemNetworkRequestCounter =
1409 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001410
Hugo Benichi208c0102016-07-28 17:53:06 +09001411 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001412 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001413 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1414 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001415 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001416 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001417 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001418 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1419 mDefaultNetworkRequests.add(mDefaultRequest);
1420 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001421
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001422 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001423 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001424
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001425 // The default WiFi request is a background request so that apps using WiFi are
1426 // migrated to a better network (typically ethernet) when one comes up, instead
1427 // of staying on WiFi forever.
1428 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1429 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1430
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001431 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1432 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1433 NetworkRequest.Type.BACKGROUND_REQUEST);
1434
Chalard Jean0702f982021-09-16 21:50:07 +09001435 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1436 // TODO: Consider making the timer customizable.
1437 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1438 mCellularRadioTimesharingCapable =
1439 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1440
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001441 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001442 mHandlerThread.start();
1443 mHandler = new InternalHandler(mHandlerThread.getLooper());
1444 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001445 mConnectivityDiagnosticsHandler =
1446 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001447
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001448 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001449 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001450
junyulaie7c7d2a2021-01-26 15:29:15 +08001451 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001452 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001453 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001454 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001455
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001456 mNetd = netd;
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001457 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001458 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001459 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001460 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001461 mCarrierPrivilegeAuthenticator =
1462 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001463
Sudheer Shanka9967d462021-03-18 19:09:25 +00001464 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001465 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1466 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001467 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001468
1469 final PowerManager powerManager = (PowerManager) context.getSystemService(
1470 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001471 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001472 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001473
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001474 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1475 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001476 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001477 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001478 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001479 mProtectedNetworks.add(p);
1480 } else {
1481 if (DBG) loge("Ignoring protectedNetwork " + p);
1482 }
1483 }
1484
soma, kawata29444ae2019-05-23 09:30:40 +09001485 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1486
Wayne Ma2fde98c2022-01-17 18:04:05 +08001487 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001488
James Mattis02220e22021-03-13 19:27:21 -08001489 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001490 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001491 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001492 final IntentFilter userIntentFilter = new IntentFilter();
1493 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1494 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1495 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1496 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001497
James Mattis02220e22021-03-13 19:27:21 -08001498 // Listen to package add/removes for netd
1499 final IntentFilter packageIntentFilter = new IntentFilter();
1500 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1501 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1502 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1503 packageIntentFilter.addDataScheme("package");
1504 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001505 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001506
lucaslind5c2d072021-02-20 18:59:47 +08001507 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001508
Chalard Jean46bfbf02022-02-02 00:56:25 +09001509 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001510 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001511 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001512 } catch (RemoteException | ServiceSpecificException e) {
1513 loge("Error registering event listener :" + e);
1514 }
1515
Erik Kline05f2b402015-04-30 12:58:40 +09001516 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1517 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001518
junyulai7e06ad42019-03-04 22:45:36 +08001519 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001520 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001521 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001522
1523 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001524 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001525 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1526 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001527 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001528 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1529 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001530
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001531 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001532 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001533 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001534
Chiachang Wangc1215d32020-10-20 15:38:58 +08001535 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001536 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001537
Chalard Jean28018572020-12-21 18:36:52 +09001538 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1539 // request that doesn't allow fallback to the default network. It should never be visible
1540 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1541 // arguments like the handler or the DnsResolver.
1542 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001543 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001544 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001545 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001546 new LinkProperties(), new NetworkCapabilities(),
1547 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001548 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1549 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001550
1551 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001552 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1553 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1554 // Even if it could, running on S would at least require mocking out the BPF map,
1555 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1556 // the bpf syscall. http://aosp/1907693
1557 if (SdkLevel.isAtLeastT()) {
1558 mDscpPolicyTracker = new DscpPolicyTracker();
1559 }
Tyler Wear72388212021-09-09 14:49:02 -07001560 } catch (ErrnoException e) {
1561 loge("Unable to create DscpPolicyTracker");
1562 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001563
1564 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1565 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001566 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001567
Xiao Ma0a171c02022-01-23 16:14:51 +00001568 /**
1569 * Check whether or not the device supports Ethernet transport.
1570 */
1571 public static boolean deviceSupportsEthernet(final Context context) {
1572 final PackageManager pm = context.getPackageManager();
1573 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1574 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1575 }
1576
Chalard Jean46adcf32018-04-18 20:18:38 +09001577 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001578 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1579 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001580 }
1581
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001582 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1583 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001584 final NetworkCapabilities netCap = new NetworkCapabilities();
1585 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001586 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001587 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001588 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001589 return netCap;
1590 }
1591
James Mattis45d81842021-01-10 14:24:24 -08001592 private NetworkRequest createDefaultRequest() {
1593 return createDefaultInternetRequestForTransport(
1594 TYPE_NONE, NetworkRequest.Type.REQUEST);
1595 }
1596
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001597 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001598 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001599 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001600 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001601 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001602 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001603 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001604 netCap.addTransportType(transportType);
1605 }
James Mattis45d81842021-01-10 14:24:24 -08001606 return createNetworkRequest(type, netCap);
1607 }
1608
1609 private NetworkRequest createNetworkRequest(
1610 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001611 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001612 }
1613
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001614 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1615 NetworkRequest.Type type) {
1616 final NetworkCapabilities netCap = new NetworkCapabilities();
1617 netCap.clearAll();
1618 netCap.addCapability(capability);
1619 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1620 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1621 }
1622
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001623 // Used only for testing.
1624 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001625 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001626 // changing ContentResolver to make registerContentObserver non-final).
1627 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1628 // by subclassing SettingsObserver.
1629 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001630 void updateAlwaysOnNetworks() {
1631 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001632 }
1633
Erik Kline9a62f012018-03-21 07:18:33 -07001634 // See FakeSettingsProvider comment above.
1635 @VisibleForTesting
1636 void updatePrivateDnsSettings() {
1637 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1638 }
1639
paulhu51f77dc2021-06-07 02:34:20 +00001640 @VisibleForTesting
1641 void updateMobileDataPreferredUids() {
1642 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1643 }
1644
Patrick Rohr2857ac42022-01-21 14:58:16 +01001645 @VisibleForTesting
1646 void updateIngressRateLimit() {
1647 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1648 }
1649
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001650 private void handleAlwaysOnNetworkRequest(
1651 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001652 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001653 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001654 handleAlwaysOnNetworkRequest(networkRequest, enable);
1655 }
1656
1657 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001658 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001659 if (enable == isEnabled) {
1660 return; // Nothing to do.
1661 }
1662
1663 if (enable) {
1664 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001665 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001666 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001667 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001668 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001669 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1670 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001671 }
1672 }
1673
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001674 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001675 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1676 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1677 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1678 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001679 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1680 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001681 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001682 }
1683
paulhu51f77dc2021-06-07 02:34:20 +00001684 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001685 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001686 private void registerSettingsCallbacks() {
1687 // Watch for global HTTP proxy changes.
1688 mSettingsObserver.observe(
1689 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1690 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1691
Chalard Jean46bfbf02022-02-02 00:56:25 +09001692 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001693 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001694 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001695 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1696
Chalard Jean46bfbf02022-02-02 00:56:25 +09001697 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001698 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001699 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001700 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001701
1702 // Watch for mobile data preferred uids changes.
1703 mSettingsObserver.observe(
1704 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1705 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001706
1707 // Watch for ingress rate limit changes.
1708 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001709 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001710 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1711 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001712 }
1713
Erik Kline31b4a9e2018-01-11 21:07:29 +09001714 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001715 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1716 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001717 }
1718 }
1719
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001720 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001721 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1722 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001723 return mNextNetworkRequestId++;
1724 }
1725
junyulai74f9a8b2018-06-13 15:00:37 +08001726 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001727 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001728 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001729 if (network == null) {
1730 return null;
1731 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001732 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001733 }
1734
1735 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001736 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001737 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001738 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001739 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001740
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001741 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001742 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001743 private NetworkAgentInfo getVpnForUid(int uid) {
1744 synchronized (mNetworkForNetId) {
1745 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1746 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1747 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1748 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001749 }
1750 }
1751 }
1752 return null;
1753 }
1754
Chalard Jean46bfbf02022-02-02 00:56:25 +09001755 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001756 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001757 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001758 final NetworkAgentInfo nai = getVpnForUid(uid);
1759 if (nai != null) return nai.declaredUnderlyingNetworks;
1760 return null;
1761 }
1762
Lorenzo Colittia7574052021-01-19 01:33:05 +09001763 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001764 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001765
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001766 final Network[] networks = getVpnUnderlyingNetworks(uid);
1767 if (networks != null) {
1768 // getUnderlyingNetworks() returns:
1769 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1770 // empty array => the VPN explicitly said "no default network".
1771 // non-empty array => the VPN specified one or more default networks; we use the
1772 // first one.
1773 if (networks.length > 0) {
1774 nai = getNetworkAgentInfoForNetwork(networks[0]);
1775 } else {
1776 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001777 }
1778 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001779 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001780 }
1781
1782 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001783 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001784 */
paulhu7aeba372020-12-30 00:42:19 +08001785 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1786 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001787 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001788 if (ignoreBlocked) {
1789 return false;
1790 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001791 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001792 final long ident = Binder.clearCallingIdentity();
1793 try {
1794 final boolean metered = nc == null ? true : nc.isMetered();
1795 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1796 } finally {
1797 Binder.restoreCallingIdentity(ident);
1798 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001799 }
1800
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001801 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001802 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1803 return;
1804 }
Hugo Benichi47011212017-03-30 10:46:05 +09001805 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001806 synchronized (mBlockedAppUids) {
1807 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001808 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001809 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001810 blocked = false;
1811 } else {
1812 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001813 }
1814 }
Hugo Benichi47011212017-03-30 10:46:05 +09001815 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1816 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1817 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001818 }
1819
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001820 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001821 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1822 return;
1823 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001824 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001825 final int requestId = nri.getActiveRequest() != null
1826 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001827 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001828 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001829 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001830 }
1831
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001832 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001833 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001834 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001835 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001836 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001837 @NonNull
1838 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1839 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001840 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1841 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1842 // but only exists if an app asks about them or requests them. Ensure the requesting app
1843 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001844 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001845 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1846 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1847 null /* extraInfo */);
1848 }
1849 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001850 return filtered;
1851 }
1852
1853 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1854 boolean ignoreBlocked) {
1855 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1856 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001857 }
1858
1859 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001860 * Return NetworkInfo for the active (i.e., connected) network interface.
1861 * It is assumed that at most one network is active at a time. If more
1862 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001863 * @return the info for the active network, or {@code null} if none is
1864 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001865 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001866 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001867 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001868 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001869 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001870 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001871 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1872 if (nai == null) return null;
1873 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1874 maybeLogBlockedNetworkInfo(networkInfo, uid);
1875 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001876 }
1877
Paul Jensen1f567382015-02-13 14:18:39 -05001878 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001879 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001880 public Network getActiveNetwork() {
1881 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001882 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001883 }
1884
1885 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001886 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001887 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001888 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001889 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001890 }
1891
Chalard Jean46bfbf02022-02-02 00:56:25 +09001892 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001893 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001894 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1895 if (vpnNai != null) {
1896 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1897 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1898 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001899 }
Paul Jensen1f567382015-02-13 14:18:39 -05001900 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001901
James Mattis2516da32021-01-31 17:06:19 -08001902 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001903 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1904 ignoreBlocked)) {
1905 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001906 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001907 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001908 }
1909
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001910 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001911 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001912 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001913 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001914 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1915 if (nai == null) return null;
1916 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001917 }
1918
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001919 /** Returns a NetworkInfo object for a network that doesn't exist. */
1920 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1921 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1922 getNetworkTypeName(networkType), "" /* subtypeName */);
1923 info.setIsAvailable(true);
1924 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1925 // background data is restricted.
1926 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1927 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1928 ? DetailedState.BLOCKED
1929 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001930 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1931 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001932 return info;
1933 }
1934
Lorenzo Colittia7574052021-01-19 01:33:05 +09001935 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001936 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1937 return null;
1938 }
1939 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001940 if (nai == null) {
1941 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001942 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001943 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1944 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001945 }
1946
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001947 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001948 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001949 public NetworkInfo getNetworkInfo(int networkType) {
1950 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001951 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001952 if (getVpnUnderlyingNetworks(uid) != null) {
1953 // A VPN is active, so we may need to return one of its underlying networks. This
1954 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001955 // getNetworkAgentInfoForUid.
1956 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1957 if (nai == null) return null;
1958 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1959 if (networkInfo.getType() == networkType) {
1960 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001961 }
1962 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001963 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001964 }
1965
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001966 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001967 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001968 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001969 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001970 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001971 if (nai == null) return null;
1972 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001973 }
1974
1975 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001976 public NetworkInfo[] getAllNetworkInfo() {
1977 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001978 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001979 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1980 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001981 NetworkInfo info = getNetworkInfo(networkType);
1982 if (info != null) {
1983 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001984 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001985 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001986 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001987 }
1988
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001989 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001990 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001991 public Network getNetworkForType(int networkType) {
1992 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001993 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1994 return null;
1995 }
1996 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1997 if (nai == null) {
1998 return null;
1999 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002000 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002001 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2002 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002003 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002004 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002005 }
2006
2007 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002008 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002009 public Network[] getAllNetworks() {
2010 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002011 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002012 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002013 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002014 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002015 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002016 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002017 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002018 }
2019
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002020 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002021 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002022 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002023 // The basic principle is: if an app's traffic could possibly go over a
2024 // network, without the app doing anything multinetwork-specific,
2025 // (hence, by "default"), then include that network's capabilities in
2026 // the array.
2027 //
2028 // In the normal case, app traffic only goes over the system's default
2029 // network connection, so that's the only network returned.
2030 //
2031 // With a VPN in force, some app traffic may go into the VPN, and thus
2032 // over whatever underlying networks the VPN specifies, while other app
2033 // traffic may go over the system default network (e.g.: a split-tunnel
2034 // VPN, or an app disallowed by the VPN), so the set of networks
2035 // returned includes the VPN's underlying networks and the system
2036 // default.
2037 enforceAccessPermission();
2038
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002039 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002040
James Mattis2516da32021-01-31 17:06:19 -08002041 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2042 if (!nri.isBeingSatisfied()) {
2043 continue;
2044 }
2045 final NetworkAgentInfo nai = nri.getSatisfier();
2046 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2047 if (null != nc
2048 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2049 && !result.containsKey(nai.network)) {
2050 result.put(
2051 nai.network,
2052 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002053 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002054 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2055 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002056 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002057 }
2058
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002059 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002060 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002061 if (null != networks) {
2062 for (final Network network : networks) {
2063 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2064 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002065 result.put(
2066 network,
2067 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002068 nc,
2069 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002070 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002071 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002072 }
2073 }
2074 }
2075
2076 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2077 out = result.values().toArray(out);
2078 return out;
2079 }
2080
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002081 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002082 public boolean isNetworkSupported(int networkType) {
2083 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002084 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002085 }
2086
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002087 /**
2088 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002089 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002090 * @return the ip properties for the active network, or {@code null} if
2091 * none is active
2092 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002093 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002094 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002095 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002096 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002097 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2098 if (nai == null) return null;
2099 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002100 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002101 }
2102
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002103 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002104 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002105 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002106 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002107 final LinkProperties lp = getLinkProperties(nai);
2108 if (lp == null) return null;
2109 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002110 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002111 }
2112
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002113 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002114 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002115 public LinkProperties getLinkProperties(Network network) {
2116 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002117 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2118 if (lp == null) return null;
2119 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002120 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002121 }
2122
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002123 @Nullable
2124 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002125 if (nai == null) {
2126 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002127 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002128 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002129 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002130 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002131 }
2132
lucaslinc582d502022-01-27 09:07:00 +08002133 @Override
2134 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002135 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002136 @NonNull String packageName, @Nullable String callingAttributionTag) {
2137 Objects.requireNonNull(packageName);
2138 Objects.requireNonNull(lp);
2139 enforceNetworkStackOrSettingsPermission();
2140 if (!checkAccessPermission(-1 /* pid */, uid)) {
2141 return null;
2142 }
2143 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2144 }
2145
Qingxi Lib2748102020-01-08 12:51:49 -08002146 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2147 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2148 }
2149
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002150 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002151 if (nai == null) return null;
2152 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002153 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002154 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002155 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002156 }
2157
2158 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002159 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2160 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002161 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002162 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002163 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002164 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002165 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002166 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002167 }
2168
lucaslinc582d502022-01-27 09:07:00 +08002169 @Override
lucaslind2b06132022-03-02 10:56:57 +08002170 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2171 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2172 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002173 Objects.requireNonNull(nc);
2174 Objects.requireNonNull(packageName);
2175 enforceNetworkStackOrSettingsPermission();
2176 if (!checkAccessPermission(-1 /* pid */, uid)) {
2177 return null;
2178 }
2179 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2180 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2181 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2182 callingAttributionTag);
2183 }
2184
lucaslin69e1aa92022-03-22 18:15:09 +08002185 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2186 if (nc.getUnderlyingNetworks() != null
2187 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2188 nc.setUnderlyingNetworks(null);
2189 }
2190 }
2191
Qingxi Libb8da982020-01-17 17:54:27 -08002192 @VisibleForTesting
2193 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002194 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002195 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2196 // this would be expensive (one more permission check every time any NC callback is
2197 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2198 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2199 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002200 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002201 if (!checkSettingsPermission(callerPid, callerUid)) {
2202 newNc.setUids(null);
2203 newNc.setSSID(null);
2204 }
Etan Cohen107ae952018-12-30 17:59:59 -08002205 if (newNc.getNetworkSpecifier() != null) {
2206 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2207 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002208 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2209 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2210 newNc.setAdministratorUids(new int[0]);
2211 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002212 if (!checkAnyPermissionOf(
2213 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002214 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002215 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002216 }
lucaslin69e1aa92022-03-22 18:15:09 +08002217 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002218
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002219 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002220 }
2221
Roshan Pius98f59ec2021-02-23 08:47:39 -08002222 /**
2223 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002224 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002225 * NetworkCapabilities.
2226 * Note: This wrapper does not support any sort of invalidation and thus must not be
2227 * persistent or long-lived. It may only be used for the time necessary to
2228 * compute the redactions required by one particular NetworkCallback or
2229 * synchronous call.
2230 */
2231 private class RedactionPermissionChecker {
2232 private final int mCallingPid;
2233 private final int mCallingUid;
2234 @NonNull private final String mCallingPackageName;
2235 @Nullable private final String mCallingAttributionTag;
2236
2237 private Boolean mHasLocationPermission = null;
2238 private Boolean mHasLocalMacAddressPermission = null;
2239 private Boolean mHasSettingsPermission = null;
2240
2241 RedactionPermissionChecker(int callingPid, int callingUid,
2242 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2243 mCallingPid = callingPid;
2244 mCallingUid = callingUid;
2245 mCallingPackageName = callingPackageName;
2246 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002247 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002248
2249 private boolean hasLocationPermissionInternal() {
2250 final long token = Binder.clearCallingIdentity();
2251 try {
2252 return mLocationPermissionChecker.checkLocationPermission(
2253 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2254 null /* message */);
2255 } finally {
2256 Binder.restoreCallingIdentity(token);
2257 }
2258 }
2259
2260 /**
2261 * Returns whether the app holds location permission or not (might return cached result
2262 * if the permission was already checked before).
2263 */
2264 public boolean hasLocationPermission() {
2265 if (mHasLocationPermission == null) {
2266 // If there is no cached result, perform the check now.
2267 mHasLocationPermission = hasLocationPermissionInternal();
2268 }
2269 return mHasLocationPermission;
2270 }
2271
2272 /**
2273 * Returns whether the app holds local mac address permission or not (might return cached
2274 * result if the permission was already checked before).
2275 */
2276 public boolean hasLocalMacAddressPermission() {
2277 if (mHasLocalMacAddressPermission == null) {
2278 // If there is no cached result, perform the check now.
2279 mHasLocalMacAddressPermission =
2280 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2281 }
2282 return mHasLocalMacAddressPermission;
2283 }
2284
2285 /**
2286 * Returns whether the app holds settings permission or not (might return cached
2287 * result if the permission was already checked before).
2288 */
2289 public boolean hasSettingsPermission() {
2290 if (mHasSettingsPermission == null) {
2291 // If there is no cached result, perform the check now.
2292 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2293 }
2294 return mHasSettingsPermission;
2295 }
2296 }
2297
2298 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2299 @NetworkCapabilities.NetCapability long redaction) {
2300 return (redactions & redaction) != 0;
2301 }
2302
2303 /**
2304 * Use the provided |applicableRedactions| to check the receiving app's
2305 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2306 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2307 * before being sent to the corresponding app.
2308 */
2309 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2310 @NetworkCapabilities.RedactionType long applicableRedactions,
2311 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2312 boolean includeLocationSensitiveInfo) {
2313 long redactions = applicableRedactions;
2314 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2315 if (includeLocationSensitiveInfo
2316 && redactionPermissionChecker.hasLocationPermission()) {
2317 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2318 }
2319 }
2320 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2321 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2322 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2323 }
2324 }
2325 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2326 if (redactionPermissionChecker.hasSettingsPermission()) {
2327 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2328 }
2329 }
2330 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002331 }
2332
Qingxi Lib2748102020-01-08 12:51:49 -08002333 @VisibleForTesting
2334 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002335 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002336 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002337 int callingPid, int callingUid, @NonNull String callingPkgName,
2338 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002339 if (nc == null) {
2340 return null;
2341 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002342 // Avoid doing location permission check if the transport info has no location sensitive
2343 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002344 final RedactionPermissionChecker redactionPermissionChecker =
2345 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2346 callingAttributionTag);
2347 final long redactions = retrieveRequiredRedactions(
2348 nc.getApplicableRedactions(), redactionPermissionChecker,
2349 includeLocationSensitiveInfo);
2350 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002351 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002352 // TODO : calling UID is redacted because apps should generally not know what UID is
2353 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002354 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002355 newNc.setOwnerUid(INVALID_UID);
2356 return newNc;
2357 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002358 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2359 if (nc.hasTransport(TRANSPORT_VPN)) {
2360 // Owner UIDs already checked above. No need to re-check.
2361 return newNc;
2362 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002363 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2364 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002365 // compatibility for older apps.
2366 if (!includeLocationSensitiveInfo
2367 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002368 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002369 newNc.setOwnerUid(INVALID_UID);
2370 return newNc;
2371 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002372 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002373 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002374 newNc.setOwnerUid(INVALID_UID);
2375 }
Qingxi Lib2748102020-01-08 12:51:49 -08002376 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002377 }
2378
lucaslinc582d502022-01-27 09:07:00 +08002379 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002380 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2381 LinkProperties lp, int callerPid, int callerUid) {
2382 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002383 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2384 // this would be expensive (one more permission check every time any LP callback is
2385 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2386 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2387 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002388
2389 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2390 final boolean needsSanitization =
2391 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2392 if (!needsSanitization) {
2393 return new LinkProperties(lp);
2394 }
2395
2396 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002397 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002398 }
2399
2400 final LinkProperties newLp = new LinkProperties(lp);
2401 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2402 // object gets parceled.
2403 newLp.setCaptivePortalApiUrl(null);
2404 newLp.setCaptivePortalData(null);
2405 return newLp;
2406 }
2407
Roshan Pius08c94fb2020-01-16 12:17:17 -08002408 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2409 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002410 // There is no need to track the effective UID of the request here. If the caller
2411 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002412 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002413 // Unprivileged apps can only pass in null or their own UID.
2414 if (nc.getUids() == null) {
2415 // If the caller passes in null, the callback will also match networks that do not
2416 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2417 // In this case, redact everything in the request immediately. This ensures that the
2418 // app is not able to get any redacted information by filing an unredacted request
2419 // and observing whether the request matches something.
2420 if (nc.getNetworkSpecifier() != null) {
2421 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2422 }
2423 } else {
2424 nc.setSingleUid(callerUid);
2425 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002426 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002427 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002428 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002429
2430 // Clear owner UID; this can never come from an app.
2431 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002432 }
2433
Chalard Jean38354d12018-03-20 19:13:57 +09002434 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002435 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002436 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2437 }
2438 }
2439
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002440 @Override
2441 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2442 enforceAccessPermission();
2443 final int callerUid = Binder.getCallingUid();
2444 final long token = Binder.clearCallingIdentity();
2445 try {
2446 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2447 } finally {
2448 Binder.restoreCallingIdentity(token);
2449 }
2450 }
2451
junyulaiebd15162021-03-03 12:09:05 +08002452 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002453 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002454 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002455 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002456 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002457
Serik Beketayev05130302021-01-15 16:47:25 -08002458 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002459 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002460 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2461 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002462 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002463 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002464 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002465 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2466 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002467 }
2468 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002469 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002470 }
2471
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002472 @Override
junyulaiebd15162021-03-03 12:09:05 +08002473 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002474 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002475 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002476 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002477
2478 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2479 for (Network network : getAllNetworks()) {
2480 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002481 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002482 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2483 // NetworkCapabilities, which may contain UIDs of apps to which the
2484 // network applies. Should the UIDs be cleared so as not to leak or
2485 // interfere ?
2486 result.add(nai.getNetworkStateSnapshot());
2487 }
2488 }
2489 return result;
2490 }
2491
2492 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002493 public boolean isActiveNetworkMetered() {
2494 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002495
Qingxi Lib2748102020-01-08 12:51:49 -08002496 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002497 if (caps != null) {
2498 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2499 } else {
2500 // Always return the most conservative value
2501 return true;
2502 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002503 }
2504
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002505 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002506 * Ensures that the system cannot call a particular method.
2507 */
2508 private boolean disallowedBecauseSystemCaller() {
2509 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002510 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2511 // for devices launched with Q and above. However, existing devices upgrading to Q and
2512 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002513 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002514 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002515 log("This method exists only for app backwards compatibility"
2516 + " and must not be called by system services.");
2517 return true;
2518 }
2519 return false;
2520 }
2521
paulhub2c28682021-08-18 18:35:54 +08002522 private int getAppUid(final String app, final UserHandle user) {
2523 final PackageManager pm =
2524 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2525 final long token = Binder.clearCallingIdentity();
2526 try {
2527 return pm.getPackageUid(app, 0 /* flags */);
2528 } catch (PackageManager.NameNotFoundException e) {
2529 return -1;
2530 } finally {
2531 Binder.restoreCallingIdentity(token);
2532 }
2533 }
2534
2535 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2536 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2537 if (getAppUid(packageName, user) != callingUid) {
2538 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2539 }
2540 }
2541
Lorenzo Colitti23862912018-09-28 11:31:55 +09002542 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002543 * Ensure that a network route exists to deliver traffic to the specified
2544 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002545 * @param networkType the type of the network over which traffic to the
2546 * specified host is to be routed
2547 * @param hostAddress the IP address of the host to which the route is
2548 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002549 * @return {@code true} on success, {@code false} on failure
2550 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002551 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002552 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2553 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002554 if (disallowedBecauseSystemCaller()) {
2555 return false;
2556 }
paulhub2c28682021-08-18 18:35:54 +08002557 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002558 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002559 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002560 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002561 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002562
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002563 InetAddress addr;
2564 try {
2565 addr = InetAddress.getByAddress(hostAddress);
2566 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002567 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002568 return false;
2569 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002570
The Android Open Source Project28527d22009-03-03 19:31:44 -08002571 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002572 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002573 return false;
2574 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002575
2576 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2577 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002578 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002579 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2580 } else {
2581 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2582 }
2583 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002584 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002585
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002586 DetailedState netState;
2587 synchronized (nai) {
2588 netState = nai.networkInfo.getDetailedState();
2589 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002590
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002591 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002592 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002593 log("requestRouteToHostAddress on down network "
2594 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002595 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002596 }
2597 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002598 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002599
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002600 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002601 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002602 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002603 LinkProperties lp;
2604 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002605 synchronized (nai) {
2606 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002607 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002608 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002609 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002610 if (DBG) {
2611 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2612 }
Wink Saville32506bc2013-06-29 21:10:57 -07002613 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002614 } finally {
2615 Binder.restoreCallingIdentity(token);
2616 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002617 }
2618
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002619 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002620 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002621 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002622 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002623 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002624 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002625 if (bestRoute.getGateway().equals(addr)) {
2626 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002627 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002628 } else {
2629 // if we will connect to this through another route, add a direct route
2630 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002631 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002632 }
2633 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002634 if (DBG) log("Adding legacy route " + bestRoute +
2635 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002636
2637 final String dst = bestRoute.getDestinationLinkAddress().toString();
2638 final String nextHop = bestRoute.hasGateway()
2639 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002640 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002641 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2642 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002643 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002644 return false;
2645 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002646 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002647 }
2648
paulhu7c0a2e62021-01-08 00:51:49 +08002649 class DnsResolverUnsolicitedEventCallback extends
2650 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002651 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002652 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002653 try {
2654 mHandler.sendMessage(mHandler.obtainMessage(
2655 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002656 new PrivateDnsValidationUpdate(event.netId,
2657 InetAddresses.parseNumericAddress(event.ipAddress),
2658 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002659 } catch (IllegalArgumentException e) {
2660 loge("Error parsing ip address in validation event");
2661 }
2662 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002663
2664 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002665 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2666 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002667 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2668 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2669 // event callback for certain nai. e.g. cellular. Register here to pass to
2670 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002671 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002672 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2673 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002674 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002675 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002676 }
2677 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002678
2679 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002680 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2681 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2682 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002683 }
dalyk1720e542018-03-05 12:42:22 -05002684
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002685 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002686 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002687 return this.VERSION;
2688 }
2689
2690 @Override
2691 public String getInterfaceHash() {
2692 return this.HASH;
2693 }
paulhu7c0a2e62021-01-08 00:51:49 +08002694 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002695
2696 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002697 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2698 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002699
paulhu7c0a2e62021-01-08 00:51:49 +08002700 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002701 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002702 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002703 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002704 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002705 }
2706 }
2707
Sudheer Shanka9967d462021-03-18 19:09:25 +00002708 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002709 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002710 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2712 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002713 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002714 };
2715
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002716 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002717 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002718 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002719 }
2720
paulhu1a407652019-03-22 16:35:06 +08002721 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2722 for (String permission : permissions) {
2723 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2724 return true;
2725 }
2726 }
2727 return false;
2728 }
2729
Paul Jensen83f5d572014-08-29 09:54:01 -04002730 private void enforceInternetPermission() {
2731 mContext.enforceCallingOrSelfPermission(
2732 android.Manifest.permission.INTERNET,
2733 "ConnectivityService");
2734 }
2735
The Android Open Source Project28527d22009-03-03 19:31:44 -08002736 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002737 mContext.enforceCallingOrSelfPermission(
2738 android.Manifest.permission.ACCESS_NETWORK_STATE,
2739 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002740 }
2741
lucaslinc582d502022-01-27 09:07:00 +08002742 private boolean checkAccessPermission(int pid, int uid) {
2743 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2744 == PERMISSION_GRANTED;
2745 }
2746
paulhua6ee2122021-02-22 15:40:43 +08002747 /**
2748 * Performs a strict and comprehensive check of whether a calling package is allowed to
2749 * change the state of network, as the condition differs for pre-M, M+, and
2750 * privileged/preinstalled apps. The caller is expected to have either the
2751 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2752 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2753 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2754 * permission and cannot be revoked. See http://b/23597341
2755 *
2756 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2757 * of this app will be updated to the current time.
2758 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002759 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002760 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2761 == PackageManager.PERMISSION_GRANTED) {
2762 return;
2763 }
2764
2765 if (callingPkg == null) {
2766 throw new SecurityException("Calling package name is null.");
2767 }
2768
2769 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2770 final int uid = mDeps.getCallingUid();
2771 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2772 callingPkg, callingAttributionTag, null /* message */);
2773
2774 if (mode == AppOpsManager.MODE_ALLOWED) {
2775 return;
2776 }
2777
2778 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2779 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2780 return;
2781 }
2782
2783 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2784 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2785 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002786 }
2787
Charles He9369e612017-05-15 17:07:18 +01002788 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002789 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002790 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002791 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002792 }
2793
paulhu8e96a752019-08-12 16:25:11 +08002794 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002795 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002796 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002797 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002798 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002799 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002800 }
2801
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002802 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002803 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002804 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002805 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002806 android.Manifest.permission.NETWORK_SETTINGS,
2807 android.Manifest.permission.NETWORK_FACTORY,
2808 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2809 }
2810
2811 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002812 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002813 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002814 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002815 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2816 android.Manifest.permission.NETWORK_FACTORY,
2817 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2818 }
2819
lucaslin69e1aa92022-03-22 18:15:09 +08002820 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2821 return PERMISSION_GRANTED == mContext.checkPermission(
2822 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2823 || PERMISSION_GRANTED == mContext.checkPermission(
2824 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2825 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002826 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002827 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002828 }
2829
Chalard Jean9a396cc2018-02-21 18:43:54 +09002830 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002831 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002832 android.Manifest.permission.NETWORK_SETTINGS,
2833 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002834 }
2835
2836 private boolean checkSettingsPermission(int pid, int uid) {
2837 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002838 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2839 || PERMISSION_GRANTED == mContext.checkPermission(
2840 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002841 }
2842
paulhu8e96a752019-08-12 16:25:11 +08002843 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002844 enforceNetworkStackPermissionOr(mContext,
2845 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002846 }
2847
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002848 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002849 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002850 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002851 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002852 }
2853
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002854 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002855 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002856 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2857 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002858 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002859 }
2860
James Mattis8378aec2021-01-26 14:05:36 -08002861 private void enforceOemNetworkPreferencesPermission() {
2862 mContext.enforceCallingOrSelfPermission(
2863 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2864 "ConnectivityService");
2865 }
2866
James Mattisfa270db2021-05-31 17:11:10 -07002867 private void enforceManageTestNetworksPermission() {
2868 mContext.enforceCallingOrSelfPermission(
2869 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2870 "ConnectivityService");
2871 }
2872
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002873 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002874 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002875 android.Manifest.permission.NETWORK_STACK,
2876 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002877 }
2878
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002879 private boolean checkNetworkStackPermission(int pid, int uid) {
2880 return checkAnyPermissionOf(pid, uid,
2881 android.Manifest.permission.NETWORK_STACK,
2882 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2883 }
2884
paulhu1a407652019-03-22 16:35:06 +08002885 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2886 return checkAnyPermissionOf(pid, uid,
2887 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002888 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2889 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002890 }
2891
Paul Hu8fc2a552022-05-04 18:44:42 +08002892 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2893 boolean checkUidsAllowedList) {
2894 if (PermissionUtils.checkAnyPermissionOf(mContext,
2895 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2896 return true;
2897 }
2898
2899 // fallback to ConnectivityInternalPermission
2900 // TODO: Remove this fallback check after all apps have declared
2901 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2902 if (PermissionUtils.checkAnyPermissionOf(mContext,
2903 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2904 return true;
2905 }
2906
2907 // Check whether uid is in allowed on restricted networks list.
2908 if (checkUidsAllowedList
2909 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2910 return true;
2911 }
2912 return false;
2913 }
2914
2915 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2916 final int callingUid = mDeps.getCallingUid();
2917 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2918 throw new SecurityException("ConnectivityService: user " + callingUid
2919 + " has no permission to access restricted network.");
2920 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002921 }
2922
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002923 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002924 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002925 }
2926
Roshan Pius98f59ec2021-02-23 08:47:39 -08002927 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2928 return PERMISSION_GRANTED == mContext.checkPermission(
2929 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2930 }
2931
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002932 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002933 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002934 }
2935
2936 private void sendInetConditionBroadcast(NetworkInfo info) {
2937 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2938 }
2939
Wink Saville4f0de1e2011-08-04 15:01:58 -07002940 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002941 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002942 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002943 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002944 if (info.isFailover()) {
2945 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2946 info.setFailover(false);
2947 }
2948 if (info.getReason() != null) {
2949 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2950 }
2951 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002952 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2953 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002954 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002955 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002956 return intent;
2957 }
2958
2959 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2960 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2961 }
2962
Chiachang Wang3bc52762021-11-25 14:17:57 +08002963 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2964 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002965 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002966 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002967 if (!mSystemReady
2968 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002969 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002970 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002971 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002972 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002973 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002974 }
2975
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002976 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002977 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002978 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002979 final NetworkInfo ni = intent.getParcelableExtra(
2980 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002981 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2982 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2983 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002984 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002985 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002986 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002987 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002988 } finally {
2989 Binder.restoreCallingIdentity(ident);
2990 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002991 }
2992 }
2993
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002994 /**
Aaron Huang96011892020-06-27 07:18:23 +08002995 * Called by SystemServer through ConnectivityManager when the system is ready.
2996 */
2997 @Override
2998 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002999 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003000 throw new SecurityException("Calling Uid is not system uid.");
3001 }
3002 systemReadyInternal();
3003 }
3004
3005 /**
3006 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003007 */
3008 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003009 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003010 // Load flags after PackageManager is ready to query module version
3011 mFlags.loadFlags(mDeps, mContext);
3012
Aaron Huang9a57acf2020-12-08 10:03:29 +08003013 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3014 // listening network request which is sent by MultipathPolicyTracker won't be added
3015 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3016 // be called after PermissionMonitor#startMonitoring().
3017 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3018 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3019 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003020 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003021 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003022 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003023
Hugo Benichie5220992017-04-26 14:53:28 +09003024 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003025 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003026 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003027 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003028 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003029 }
3030 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003031
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003032 // Create network requests for always-on networks.
3033 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003034
3035 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003036 // Note that updating can be skipped here if the list is empty only because no uid
3037 // rules are applied before system ready. Normally, the empty uid list means to clear
3038 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003039 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3040 updateMobileDataPreferredUids();
3041 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003042 }
3043
The Android Open Source Project28527d22009-03-03 19:31:44 -08003044 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003045 * Start listening for default data network activity state changes.
3046 */
3047 @Override
3048 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003049 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003050 }
3051
3052 /**
3053 * Stop listening for default data network activity state changes.
3054 */
3055 @Override
3056 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003057 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003058 }
3059
3060 /**
3061 * Check whether the default network radio is currently active.
3062 */
3063 @Override
3064 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003065 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003066 }
3067
3068 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003069 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003070 * and set it on it's iface.
3071 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003072 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3073 final String iface = newLp.getInterfaceName();
3074 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003075 if (oldLp == null && mtu == 0) {
3076 // Silently ignore unset MTU value.
3077 return;
3078 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003079 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3080 if (VDBG) log("identical MTU - not setting");
3081 return;
3082 }
paulhucbbc3db2019-03-08 16:35:20 +08003083 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003084 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003085 return;
3086 }
sy.yun4aa73922013-09-02 05:24:09 +09003087
w19976e714f1d2014-08-05 15:18:11 -07003088 // Cannot set MTU without interface name
3089 if (TextUtils.isEmpty(iface)) {
3090 loge("Setting MTU size with null iface.");
3091 return;
3092 }
3093
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003094 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003095 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003096 mNetd.interfaceSetMtu(iface, mtu);
3097 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003098 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003099 }
3100 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003101
Chenbo Feng15416292018-11-08 17:36:21 -08003102 @VisibleForTesting
3103 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003104
lucaslin821c9782018-11-28 19:27:52 +08003105 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003106 String[] values = null;
3107 if (tcpBufferSizes != null) {
3108 values = tcpBufferSizes.split(",");
3109 }
3110
3111 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003112 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003113 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3114 values = tcpBufferSizes.split(",");
3115 }
3116
3117 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3118
3119 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003120 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003121
Chenbo Feng15416292018-11-08 17:36:21 -08003122 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3123 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3124 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003125 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003126 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003127 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003128 }
3129 }
3130
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003131 @Override
3132 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003133 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003134 NETWORK_RESTORE_DELAY_PROP_NAME);
3135 if(restoreDefaultNetworkDelayStr != null &&
3136 restoreDefaultNetworkDelayStr.length() != 0) {
3137 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003138 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003139 } catch (NumberFormatException e) {
3140 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003141 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003142 // if the system property isn't set, use the value for the apn type
3143 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3144
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003145 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3146 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003147 }
3148 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003149 }
3150
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003151 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003152 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003153 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003154 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003155 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003156 // Start gathering diagnostic information.
3157 netDiags.add(new NetworkDiagnostics(
3158 nai.network,
3159 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003160 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003161 DIAG_TIME_MS));
3162 }
3163
3164 for (NetworkDiagnostics netDiag : netDiags) {
3165 pw.println();
3166 netDiag.waitForMeasurements();
3167 netDiag.dump(pw);
3168 }
3169 }
3170
The Android Open Source Project28527d22009-03-03 19:31:44 -08003171 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003172 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3173 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003174 if (!checkDumpPermission(mContext, TAG, writer)) return;
3175
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003176 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003177 }
3178
lucaslin99473f62020-12-10 15:10:54 +08003179 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3180 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3181 != PackageManager.PERMISSION_GRANTED) {
3182 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003183 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003184 + " due to missing android.permission.DUMP permission");
3185 return false;
3186 } else {
3187 return true;
3188 }
3189 }
3190
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003191 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003192 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003193
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003194 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003195 dumpNetworkDiagnostics(pw);
3196 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003197 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003198 dumpNetworks(pw);
3199 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003200 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003201 dumpNetworkRequests(pw);
3202 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003203 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3204 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3205 dumpTrafficController(pw, fd, verbose);
3206 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003207 }
Erik Kline9647f382015-06-05 17:47:34 +09003208
Junyu Lai0da479b2022-04-20 15:06:29 +08003209 pw.println("NetworkProviders for:");
3210 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003211 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003212 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003213 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003214 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003215 pw.println();
3216
Chalard Jean5b409c72021-02-04 13:12:59 +09003217 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003218 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003219 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003220 pw.println("none");
3221 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003222 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003223 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003224 pw.println();
3225
James Mattis8b298a02021-06-01 22:34:04 -07003226 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003227 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003228 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003229 pw.decreaseIndent();
3230 pw.println();
3231
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003232 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003233 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003234 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003235 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003236 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003237
junyulaif2c67e42018-08-07 19:50:45 +08003238 pw.println("Status for known UIDs:");
3239 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003240 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003241 for (int i = 0; i < size; i++) {
3242 // Don't crash if the array is modified while dumping in bugreports.
3243 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003244 final int uid = mUidBlockedReasons.keyAt(i);
3245 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3246 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003247 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003248 } catch (ArrayIndexOutOfBoundsException e) {
3249 pw.println(" ArrayIndexOutOfBoundsException");
3250 } catch (ConcurrentModificationException e) {
3251 pw.println(" ConcurrentModificationException");
3252 }
3253 }
3254 pw.println();
3255 pw.decreaseIndent();
3256
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003257 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003258 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003259 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003260 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003261 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003262
Junyu Lai0da479b2022-04-20 15:06:29 +08003263 pw.println("Network Offers:");
3264 pw.increaseIndent();
3265 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3266 pw.println(offerInfo.offer);
3267 }
3268 pw.decreaseIndent();
3269 pw.println();
3270
Robert Greenwalt94e22142014-07-30 16:31:24 -07003271 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003272
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003273 pw.println();
markchien5e866652019-09-30 14:40:57 +08003274 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003275
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003276 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003277 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003278
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003279 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003280
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003281 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003282 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003283 pw.println("mNetworkRequestInfoLogs (most recent first):");
3284 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003285 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003286 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003287
3288 pw.println();
3289 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3290 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003291 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003292 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003293
3294 pw.println();
3295 pw.println("NetTransition WakeLock activity (most recent first):");
3296 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003297 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3298 pw.println("total releases: " + mTotalWakelockReleases);
3299 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3300 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3301 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3302 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3303 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3304 }
James Mattiscb1e0362021-04-06 17:07:42 -07003305 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003306
3307 pw.println();
3308 pw.println("bandwidth update requests (by uid):");
3309 pw.increaseIndent();
3310 synchronized (mBandwidthRequests) {
3311 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3312 pw.println("[" + mBandwidthRequests.keyAt(i)
3313 + "]: " + mBandwidthRequests.valueAt(i));
3314 }
3315 }
3316 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003317 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003318
James Mattiscb1e0362021-04-06 17:07:42 -07003319 pw.println();
3320 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3321 pw.increaseIndent();
3322 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003323 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003324 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003325
3326 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003327
3328 pw.println();
3329 pw.println("Permission Monitor:");
3330 pw.increaseIndent();
3331 mPermissionMonitor.dump(pw);
3332 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003333
3334 pw.println();
3335 pw.println("Legacy network activity:");
3336 pw.increaseIndent();
3337 mNetworkActivityTracker.dump(pw);
3338 pw.decreaseIndent();
Ken Chendaf5cb62022-07-04 11:09:28 +08003339
3340 // pre-T is logged by netd.
3341 if (SdkLevel.isAtLeastT()) {
3342 pw.println();
3343 pw.println("BPF programs & maps:");
3344 pw.increaseIndent();
3345 // Flush is required. Otherwise, the traces in fd can interleave with traces in pw.
3346 pw.flush();
3347 dumpTrafficController(pw, fd, /*verbose=*/ true);
3348 pw.decreaseIndent();
3349 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003350 }
3351
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003352 private void dumpNetworks(IndentingPrintWriter pw) {
3353 for (NetworkAgentInfo nai : networksSortedById()) {
3354 pw.println(nai.toString());
3355 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003356 pw.println("Nat464Xlat:");
3357 pw.increaseIndent();
3358 nai.dumpNat464Xlat(pw);
3359 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003360 pw.println(String.format(
3361 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3362 nai.numForegroundNetworkRequests(),
3363 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3364 nai.numBackgroundNetworkRequests(),
3365 nai.numNetworkRequests()));
3366 pw.increaseIndent();
3367 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3368 pw.println(nai.requestAt(i).toString());
3369 }
3370 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003371 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003372 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003373 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003374 pw.decreaseIndent();
3375 pw.decreaseIndent();
3376 }
3377 }
3378
James Mattis8b298a02021-06-01 22:34:04 -07003379 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3380 if (!mProfileNetworkPreferences.isEmpty()) {
3381 pw.println("Profile preferences:");
3382 pw.increaseIndent();
3383 pw.println(mProfileNetworkPreferences.preferences);
3384 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003385 }
James Mattis8b298a02021-06-01 22:34:04 -07003386 if (!mOemNetworkPreferences.isEmpty()) {
3387 pw.println("OEM preferences:");
3388 pw.increaseIndent();
3389 pw.println(mOemNetworkPreferences);
3390 pw.decreaseIndent();
3391 }
3392 if (!mMobileDataPreferredUids.isEmpty()) {
3393 pw.println("Mobile data preferred UIDs:");
3394 pw.increaseIndent();
3395 pw.println(mMobileDataPreferredUids);
3396 pw.decreaseIndent();
3397 }
James Mattis45d81842021-01-10 14:24:24 -08003398
James Mattis8b298a02021-06-01 22:34:04 -07003399 pw.println("Default requests:");
3400 pw.increaseIndent();
3401 dumpPerAppDefaultRequests(pw);
3402 pw.decreaseIndent();
3403 }
3404
3405 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003406 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3407 if (mDefaultRequest == defaultRequest) {
3408 continue;
3409 }
3410
James Mattis8b298a02021-06-01 22:34:04 -07003411 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3412 final String networkOutput;
3413 if (null == satisfier) {
3414 networkOutput = "null";
3415 } else if (mNoServiceNetwork.equals(satisfier)) {
3416 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003417 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003418 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003419 }
James Mattis8b298a02021-06-01 22:34:04 -07003420 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3421 ? "" : " asUid: " + defaultRequest.mAsUid;
3422 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3423 + defaultRequest.mPid + asUidString + "]";
3424 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3425 + " Preference order: " + defaultRequest.mPreferenceOrder
3426 + " Tracked UIDs: " + defaultRequest.getUids();
3427 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003428 }
3429 }
3430
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003431 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003432 NetworkRequestInfo[] infos = null;
3433 while (infos == null) {
3434 try {
3435 infos = requestsSortedById();
3436 } catch (ConcurrentModificationException e) {
3437 // mNetworkRequests should only be accessed from handler thread, except dump().
3438 // As dump() is never called in normal usage, it would be needlessly expensive
3439 // to lock the collection only for its benefit. Instead, retry getting the
3440 // requests if ConcurrentModificationException is thrown during dump().
3441 }
3442 }
3443 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003444 pw.println(nri.toString());
3445 }
3446 }
3447
Ken Chene6d511f2022-01-25 11:10:42 +08003448 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3449 boolean verbose) {
3450 try {
3451 mBpfNetMaps.dump(fd, verbose);
3452 } catch (ServiceSpecificException e) {
3453 pw.println(e.getMessage());
3454 } catch (IOException e) {
3455 loge("Dump BPF maps failed, " + e);
3456 }
3457 }
3458
Chalard Jean524f0b12021-10-25 21:11:56 +09003459 private void dumpAllRequestInfoLogsToLogcat() {
3460 try (PrintWriter logPw = new PrintWriter(new Writer() {
3461 @Override
3462 public void write(final char[] cbuf, final int off, final int len) {
3463 // This method is called with 0-length and 1-length arrays for empty strings
3464 // or strings containing only the DEL character.
3465 if (len <= 1) return;
3466 Log.e(TAG, new String(cbuf, off, len));
3467 }
3468 @Override public void flush() {}
3469 @Override public void close() {}
3470 })) {
3471 mNetworkRequestInfoLogs.dump(logPw);
3472 }
3473 }
3474
Hugo Benichia480ba52018-09-03 08:19:02 +09003475 /**
3476 * Return an array of all current NetworkAgentInfos sorted by network id.
3477 */
3478 private NetworkAgentInfo[] networksSortedById() {
3479 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003480 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003481 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003482 return networks;
3483 }
3484
3485 /**
3486 * Return an array of all current NetworkRequest sorted by request id.
3487 */
James Mattis258ea3c2020-11-15 15:04:40 -08003488 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003489 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003490 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003491 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003492 // Sort the array based off the NRI containing the min requestId in its requests.
3493 Arrays.sort(requests,
3494 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3495 Comparator.comparingInt(req -> req.requestId)).requestId
3496 )
3497 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003498 return requests;
3499 }
3500
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003501 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003502 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003503 if (officialNai != null && officialNai.equals(nai)) return true;
3504 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003505 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003506 " - " + nai);
3507 }
3508 return false;
3509 }
3510
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003511 private boolean isDisconnectRequest(Message msg) {
3512 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3513 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3514 return info.getState() == NetworkInfo.State.DISCONNECTED;
3515 }
3516
Robert Greenwalt2034b912009-08-12 16:08:25 -07003517 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003518 private class NetworkStateTrackerHandler extends Handler {
3519 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003520 super(looper);
3521 }
3522
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003523 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003524 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3525 final NetworkAgentInfo nai = arg.first;
3526 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003527 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003528 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003529 }
3530 return;
3531 }
3532
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003533 // If the network has been destroyed, the only thing that it can do is disconnect.
3534 if (nai.destroyed && !isDisconnectRequest(msg)) {
3535 return;
3536 }
3537
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003538 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003539 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003540 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3541 final NetworkCapabilities sanitized =
3542 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003543 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003544 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003545 break;
3546 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003547 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003548 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003549 processLinkPropertiesFromAgent(nai, newLp);
3550 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003551 break;
3552 }
3553 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003554 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003555 updateNetworkInfo(nai, info);
3556 break;
3557 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003558 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003559 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003560 break;
3561 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003562 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003563 if (nai.everConnected) {
3564 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003565 // Note that if the NAI had been connected, this would affect the
3566 // score, and therefore would require re-mixing the score and performing
3567 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003568 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003569 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3570 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003571 // Mark the network as temporarily accepting partial connectivity so that it
3572 // will be validated (and possibly become default) even if it only provides
3573 // partial internet access. Note that if user connects to partial connectivity
3574 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3575 // out of wifi coverage) and if the same wifi is available again, the device
3576 // will auto connect to this wifi even though the wifi has "no internet".
3577 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003578 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003579 break;
3580 }
junyulai011b1f12019-01-03 18:50:15 +08003581 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003582 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003583 break;
3584 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003585 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003586 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003587 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003588
3589 if (isLegacyLockdownNai(nai)
3590 && (underlying == null || underlying.size() != 1)) {
3591 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3592 + " must have exactly one underlying network: " + underlying);
3593 }
3594
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003595 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3596 nai.declaredUnderlyingNetworks = (underlying != null)
3597 ? underlying.toArray(new Network[0]) : null;
3598
3599 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3600 if (DBG) {
3601 log(nai.toShortString() + " changed underlying networks to "
3602 + Arrays.toString(nai.declaredUnderlyingNetworks));
3603 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003604 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003605 notifyIfacesChangedForNetworkStats();
3606 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003607 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003608 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003609 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3610 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3611 nai.teardownDelayMs = msg.arg1;
3612 } else {
3613 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3614 }
Chalard Jean550b5212021-03-05 23:07:53 +09003615 break;
3616 }
3617 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3618 nai.setLingerDuration((int) arg.second);
3619 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003620 }
Tyler Wear72388212021-09-09 14:49:02 -07003621 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3622 DscpPolicy policy = (DscpPolicy) arg.second;
3623 if (mDscpPolicyTracker != null) {
3624 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3625 }
3626 break;
3627 }
3628 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3629 if (mDscpPolicyTracker != null) {
3630 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3631 }
3632 break;
3633 }
3634 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3635 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003636 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003637 }
3638 break;
3639 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003640 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003641 // If nai is not yet created, or is already destroyed, ignore.
3642 if (!shouldDestroyNativeNetwork(nai)) break;
3643
3644 final int timeoutMs = (int) arg.second;
3645 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3646 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3647 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3648 }
3649
3650 // Marking a network awaiting replacement is used to ensure that any requests
3651 // satisfied by the network do not switch to another network until a
3652 // replacement is available or the wait for a replacement times out.
3653 // If the network is inactive (i.e., nascent or lingering), then there are no
3654 // such requests, and there is no point keeping it. Just tear it down.
3655 // Note that setLingerDuration(0) cannot be used to do this because the network
3656 // could be nascent.
3657 nai.clearInactivityState();
3658 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3659 Log.d(TAG, nai.toShortString()
3660 + " marked awaiting replacement is unneeded, tearing down instead");
3661 teardownUnneededNetwork(nai);
3662 break;
3663 }
3664
3665 Log.d(TAG, "Marking " + nai.toShortString()
3666 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3667 destroyNativeNetwork(nai);
3668
3669 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3670 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3671 // consider the fact that the network could already have disconnected or been
3672 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3673 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3674 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3675 mKeepaliveTracker.handleStopAllKeepalives(nai,
3676 SocketKeepalive.ERROR_INVALID_NETWORK);
3677
3678 nai.updateScoreForNetworkAgentUpdate();
3679 // This rematch is almost certainly not going to result in any changes, because
3680 // the destroyed flag is only just above the "current satisfier wins"
3681 // tie-breaker. But technically anything that affects scoring should rematch.
3682 rematchAllNetworksAndRequests();
3683 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3684 break;
3685 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003686 }
3687 }
3688
3689 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003690 final int netId = msg.arg2;
3691 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003692 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
3693 if (nai != null && nai.destroyed) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003694 switch (msg.what) {
3695 default:
3696 return false;
lucasline117e2e2019-10-22 18:27:33 +08003697 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003698 if (nai == null) {
3699 break;
3700 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003701 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3702 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003703 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003704 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003705 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003706 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003707 if (probePrivateDnsCompleted) {
3708 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3709 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003710 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003711 }
3712 // Only show the notification when the private DNS is broken and the
3713 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003714 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003715 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3716 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003717 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003718 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3719 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3720 // private DNS is broken, it means this network is being reevaluated.
3721 // Either probing private DNS is not necessary any more or it hasn't been
3722 // done yet. In either case, the networkCapabilities should be updated to
3723 // reflect the new status.
3724 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003725 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003726 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003727 }
3728 break;
3729 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003730 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003731 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3732
Erik Kline31b4a9e2018-01-11 21:07:29 +09003733 if (nai == null) break;
3734
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003735 handleNetworkTested(nai, results.mTestResult,
3736 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003737 break;
3738 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003739 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003740 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003741 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003742 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3743 nai.lastCaptivePortalDetected = visible;
3744 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003745 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003746 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3747 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003748 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003749 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003750 teardownUnneededNetwork(nai);
3751 break;
3752 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003753 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003754 }
3755 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003756 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003757 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003758 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3759 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003760 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003761 if (nai == null) {
3762 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3763 break;
3764 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003765 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003766 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003767 (PendingIntent) msg.obj,
3768 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003769 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003770 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003771 break;
3772 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003773 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003774 if (nai == null) break;
3775
Erik Kline9a62f012018-03-21 07:18:33 -07003776 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003777 break;
3778 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003779 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003780 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003781 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003782 break;
3783 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003784 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003785 return true;
3786 }
3787
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003788 private void handleNetworkTested(
3789 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
he_won.hwang881307a2022-03-15 21:23:52 +09003790 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3791 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3792 // Assume the validation failure is due to a temporary failure after roaming
3793 // and ignore it. NetworkMonitor will continue to retry validation. If it
3794 // continues to fail after the block timeout expires, the network will be
3795 // marked unvalidated. If it succeeds, then validation state will not change.
3796 return;
3797 }
3798
3799 final boolean wasValidated = nai.lastValidated;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003800 final boolean wasPartial = nai.partialConnectivity;
3801 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3802 final boolean partialConnectivityChanged =
3803 (wasPartial != nai.partialConnectivity);
3804
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003805 if (DBG) {
3806 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3807 ? " with redirect to " + redirectUrl
3808 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003809 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003810 }
3811 if (valid != nai.lastValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003812 final FullScore oldScore = nai.getScore();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003813 nai.lastValidated = valid;
3814 nai.everValidated |= valid;
3815 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003816 if (valid) {
3817 handleFreshlyValidatedNetwork(nai);
3818 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3819 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003820 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003821 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003822 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003823 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003824 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003825 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003826 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003827 NotificationType.PRIVATE_DNS_BROKEN);
3828 // If network becomes valid, the hasShownBroken should be reset for
3829 // that network so that the notification will be fired when the private
3830 // DNS is broken again.
3831 nai.networkAgentConfig.hasShownBroken = false;
3832 }
3833 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003834 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003835 }
3836 updateInetCondition(nai);
3837 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003838 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003839 nai.onValidationStatusChanged(
3840 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3841 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003842
3843 // If NetworkMonitor detects partial connectivity before
3844 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3845 // immediately. Re-notify partial connectivity silently if no internet
3846 // notification already there.
3847 if (!wasPartial && nai.partialConnectivity) {
3848 // Remove delayed message if there is a pending message.
3849 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3850 handlePromptUnvalidated(nai.network);
3851 }
3852
3853 if (wasValidated && !nai.lastValidated) {
3854 handleNetworkUnvalidated(nai);
3855 }
3856 }
3857
Calvin Ondada1452016-10-11 15:10:46 -07003858 private int getCaptivePortalMode() {
3859 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003860 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3861 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003862 }
3863
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003864 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3865 switch (msg.what) {
3866 default:
3867 return false;
3868 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3869 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3870 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3871 handleLingerComplete(nai);
3872 }
3873 break;
3874 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003875 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3876 handleNetworkAgentRegistered(msg);
3877 break;
3878 }
3879 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3880 handleNetworkAgentDisconnected(msg);
3881 break;
3882 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003883 }
3884 return true;
3885 }
3886
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003887 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003888 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003889 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003890 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003891 maybeHandleNetworkAgentMessage(msg);
3892 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003893 }
3894 }
3895
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003896 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003897 private final int mNetId;
3898 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003899
3900 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003901 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003902 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003903 }
3904
3905 @Override
3906 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3907 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003908 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003909 }
3910
3911 @Override
3912 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003913 // Legacy version of notifyNetworkTestedWithExtras.
3914 // Would only be called if the system has a NetworkStack module older than the
3915 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003916 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003917 }
3918
3919 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003920 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003921 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3922 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003923 final Message msg = mTrackerHandler.obtainMessage(
3924 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003925 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003926 new NetworkTestedResults(
3927 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003928 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003929
3930 // Invoke ConnectivityReport generation for this Network test event.
3931 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3932 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003933
Cody Kestingf1120be2020-08-03 18:01:40 -07003934 // NetworkMonitor reports the network validation result as a bitmask while
3935 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3936 // logical value for ConnectivityDiagnostics.
3937 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3938 p.result);
3939
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003940 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003941 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003942 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3943 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3944
Aaron Huang959d3642021-01-21 15:47:41 +08003945 ConnectivityReportEvent reportEvent =
3946 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3947 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003948 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003949 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003950 }
3951
3952 @Override
3953 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3954 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3955 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003956 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003957 }
3958
3959 @Override
lucasline117e2e2019-10-22 18:27:33 +08003960 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3961 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3962 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003963 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003964 }
3965
3966 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003967 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3968 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3969 EVENT_CAPPORT_DATA_CHANGED,
3970 0, mNetId, data));
3971 }
3972
3973 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003974 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003975 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003976 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003977
3978 final PendingIntent pendingIntent;
3979 // Only the system server can register notifications with package "android"
3980 final long token = Binder.clearCallingIdentity();
3981 try {
paulhu7746e4e2020-06-09 19:07:03 +08003982 pendingIntent = PendingIntent.getBroadcast(
3983 mContext,
3984 0 /* requestCode */,
3985 intent,
3986 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003987 } finally {
3988 Binder.restoreCallingIdentity(token);
3989 }
3990 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3991 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003992 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003993 }
3994
3995 @Override
3996 public void hideProvisioningNotification() {
3997 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003998 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003999 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004000
4001 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004002 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004003 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004004 }
4005
4006 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004007 public int getInterfaceVersion() {
4008 return this.VERSION;
4009 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004010
4011 @Override
4012 public String getInterfaceHash() {
4013 return this.HASH;
4014 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004015 }
4016
Cody Kestingf1120be2020-08-03 18:01:40 -07004017 /**
4018 * Converts the given NetworkMonitor-specific validation result bitmask to a
4019 * ConnectivityDiagnostics-specific validation result int.
4020 */
4021 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4022 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4023 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4024 }
4025 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4026 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4027 }
4028 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4029 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4030 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4031 }
4032
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004033 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004034 log("Data stall detected with methods: " + p.detectionMethod);
4035
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004036 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004037 int detectionMethod = 0;
4038 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4039 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4040 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4041 }
4042 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4043 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4044 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4045 p.tcpMetricsCollectionPeriodMillis);
4046 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004047 }
4048
Cody Kestingf53a0752020-04-15 12:33:28 -07004049 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004050 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004051 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004052
4053 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4054 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4055 // the cost of going through two handlers.
4056 mConnectivityDiagnosticsHandler.sendMessage(msg);
4057 }
4058
Cody Kestingb37958e2020-05-15 10:36:01 -07004059 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4060 return (p.detectionMethod & detectionMethod) != 0;
4061 }
4062
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004063 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4064 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004065 }
4066
Erik Klinea73af002018-06-26 18:53:43 +09004067 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4068 if (nai == null) return;
4069 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4070 // in order to restart a validation pass from within netd.
4071 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4072 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004073 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004074 }
4075 }
4076
Erik Kline31b4a9e2018-01-11 21:07:29 +09004077 private void handlePrivateDnsSettingsChanged() {
4078 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4079
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004080 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004081 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004082 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004083 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4084 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004085 }
4086 }
4087
Erik Kline9a62f012018-03-21 07:18:33 -07004088 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4089 // Private DNS only ever applies to networks that might provide
4090 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004091 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004092
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004093 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004094 // schedule DNS resolutions. If a DNS resolution is required the
4095 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004096 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004097
4098 // With Private DNS bypass support, we can proceed to update the
4099 // Private DNS config immediately, even if we're in strict mode
4100 // and have not yet resolved the provider name into a set of IPs.
4101 updatePrivateDns(nai, cfg);
4102 }
4103
4104 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4105 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004106 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004107 }
4108
dalyk1720e542018-03-05 12:42:22 -05004109 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4110 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4111 if (nai == null) {
4112 return;
4113 }
4114 mDnsManager.updatePrivateDnsValidation(update);
4115 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4116 }
4117
paulhu7c0a2e62021-01-08 00:51:49 +08004118 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004119 int prefixLength) {
4120 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4121 if (nai == null) return;
4122
paulhu7c0a2e62021-01-08 00:51:49 +08004123 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4124 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004125
4126 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004127 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004128 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004129 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004130 prefixLength);
4131 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004132 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004133 return;
4134 }
4135 }
4136
Lorenzo Colittid523d142020-04-01 20:16:30 +09004137 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004138 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4139 }
4140
Hai Shalome58bdc62021-01-11 18:45:34 -08004141 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004142 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004143 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004144 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4145 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4146 }
4147
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004148 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004149 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004150 * @param nai the agent info to update
4151 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004152 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004153 */
junyulai2b6f0c22021-02-03 20:15:30 +08004154 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4155 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4156 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004157 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004158 // one lingered request, set inactive.
4159 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004160 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004161 if (DBG) log("Unsetting inactive " + nai.toShortString());
4162 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004163 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004164 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004165 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004166 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4167 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004168 }
junyulai2b6f0c22021-02-03 20:15:30 +08004169 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004170 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004171 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004172 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004173 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004174 }
4175
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004176 private void handleNetworkAgentRegistered(Message msg) {
4177 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4178 if (!mNetworkAgentInfos.contains(nai)) {
4179 return;
4180 }
4181
4182 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4183 if (VDBG) log("NetworkAgent registered");
4184 } else {
4185 loge("Error connecting NetworkAgent");
4186 mNetworkAgentInfos.remove(nai);
4187 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004188 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004189 synchronized (mNetworkForNetId) {
4190 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004191 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004192 mNetIdManager.releaseNetId(nai.network.getNetId());
4193 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004194 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004195 }
4196 }
4197 }
Paul Jensend5f53392014-11-25 15:26:53 -05004198
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004199 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
4200 return nai.created && !nai.destroyed;
4201 }
4202
he_won.hwang881307a2022-03-15 21:23:52 +09004203 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004204 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004205 if (SdkLevel.isAtLeastT()) return false;
4206 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4207 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4208 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4209 && blockTimeOut >= 0) {
4210 final long currentTimeMs = SystemClock.elapsedRealtime();
4211 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTimestamp;
4212 if (timeSinceLastRoam <= blockTimeOut) {
4213 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4214 return true;
4215 }
4216 }
4217 return false;
4218 }
4219
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004220 private void handleNetworkAgentDisconnected(Message msg) {
4221 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004222 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004223 }
4224
Chalard Jeand9fffc32018-05-11 20:19:20 +09004225 // Destroys a network, remove references to it from the internal state managed by
4226 // ConnectivityService, free its interfaces and clean up.
4227 // Must be called on the Handler thread.
4228 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004229 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004230
4231 if (!mNetworkAgentInfos.contains(nai)) return;
4232
Chalard Jeand9fffc32018-05-11 20:19:20 +09004233 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004234 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004235 }
lucaslinb25c9a62019-02-12 15:30:13 +08004236 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004237 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004238 // A network agent has disconnected.
4239 // TODO - if we move the logic to the network agent (have them disconnect
4240 // because they lost all their requests or because their score isn't good)
4241 // then they would disconnect organically, report their new state and then
4242 // disconnect the channel.
4243 if (nai.networkInfo.isConnected()) {
4244 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4245 null, null);
4246 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004247 final boolean wasDefault = isDefaultNetwork(nai);
4248 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004249 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004250 }
4251 notifyIfacesChangedForNetworkStats();
4252 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4253 // by other networks that are already connected. Perhaps that can be done by
4254 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4255 // of rematchAllNetworksAndRequests
4256 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004257 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004258
4259 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004260 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4261 // Disable wakeup packet monitoring for each interface.
4262 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4263 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004264 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004265 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004266 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004267 synchronized (mNetworkForNetId) {
4268 // Remove the NetworkAgent, but don't mark the netId as
4269 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004270 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004271 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004272 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004273 // Remove all previously satisfied requests.
4274 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004275 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004276 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004277 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004278 if (currentNetwork != null
4279 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004280 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004281 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4282 // rematch not to keep disconnected agents instead of setting it here ; this
4283 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004284 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004285 for (final NetworkOfferInfo noi : mNetworkOffers) {
4286 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004287 }
James Mattise3ef1912020-12-20 11:09:58 -08004288
Chalard Jean5b409c72021-02-04 13:12:59 +09004289 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004290 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004291 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004292 // network, because while incorrect this is the closest to the old (also
4293 // incorrect) behavior.
4294 mNetworkActivityTracker.updateDataActivityTracking(
4295 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004296 ensureNetworkTransitionWakelock(nai.toShortString());
4297 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004298 }
4299 }
junyulai2b6f0c22021-02-03 20:15:30 +08004300 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004301 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004302 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004303 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004304 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004305 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004306 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004307
4308 // Immediate teardown.
4309 if (nai.teardownDelayMs == 0) {
4310 destroyNetwork(nai);
4311 return;
4312 }
4313
4314 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304315 if (nai.created) {
4316 try {
4317 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4318 } catch (RemoteException e) {
4319 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4320 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004321 }
4322 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4323 }
4324
4325 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004326 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004327 // Tell netd to clean up the configuration for this network
4328 // (routing rules, DNS, etc).
4329 // This may be slow as it requires a lot of netd shelling out to ip and
4330 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004331 // after we've rematched networks with requests (which might change the default
4332 // network or service a new request from an app), so network traffic isn't interrupted
4333 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004334 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004335 }
4336 if (!nai.created && !SdkLevel.isAtLeastT()) {
4337 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4338 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4339 // false if the network was never created.
4340 // TODO: delete when S is no longer supported.
4341 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004342 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004343 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004344 }
4345
Ken Chen6df7a902021-04-09 15:08:42 +08004346 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004347 try {
4348 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004349 final NativeNetworkConfig config;
4350 if (nai.isVPN()) {
4351 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004352 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004353 return false;
4354 }
4355 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4356 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004357 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004358 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004359 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004360 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004361 getNetworkPermission(nai.networkCapabilities),
4362 false /* secure */,
4363 VpnManager.TYPE_VPN_NONE,
4364 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004365 }
Ken Chen6df7a902021-04-09 15:08:42 +08004366 mNetd.networkCreate(config);
4367 mDnsResolver.createNetworkCache(nai.network.getNetId());
4368 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4369 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004370 return true;
4371 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004372 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004373 return false;
4374 }
4375 }
4376
Ken Chen6df7a902021-04-09 15:08:42 +08004377 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004378 if (mDscpPolicyTracker != null) {
4379 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4380 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004381 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004382 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004383 } catch (RemoteException | ServiceSpecificException e) {
4384 loge("Exception destroying network(networkDestroy): " + e);
4385 }
4386 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004387 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004388 } catch (RemoteException | ServiceSpecificException e) {
4389 loge("Exception destroying network: " + e);
4390 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004391 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4392 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4393 // gets created, could add data to DnsManager data structures that will never get deleted.
4394 mDnsManager.removeNetwork(nai.network);
4395
4396 // clean up tc police filters on interface.
4397 if (nai.everConnected && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
4398 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4399 }
4400
4401 nai.destroyed = true;
4402 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004403 }
4404
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004405 // If this method proves to be too slow then we can maintain a separate
4406 // pendingIntent => NetworkRequestInfo map.
4407 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4408 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004409 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4410 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4411 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004412 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004413 return entry.getValue();
4414 }
4415 }
4416 return null;
4417 }
4418
Chalard Jean524f0b12021-10-25 21:11:56 +09004419 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4420 if (SdkLevel.isAtLeastT()) {
4421 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4422 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4423 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4424 // bug is fixed.
4425 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004426 throw new IllegalStateException("This NRI is already registered. New : " + nri
4427 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004428 }
4429 }
4430 }
4431 }
4432
Chalard Jeanac9ace02022-01-26 16:54:05 +09004433 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4434 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004435 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004436 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4437 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004438 }
4439 return false;
4440 }
4441
James Mattisf7027322020-12-13 16:28:14 -08004442 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004443 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004444 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4445 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4446 final NetworkRequestInfo existingRequest =
4447 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004448 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004449 if (DBG) {
4450 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4451 + nri.mRequests.get(0) + " because their intents matched.");
4452 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004453 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004454 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004455 }
Erik Kline05f2b402015-04-30 12:58:40 +09004456 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004457 }
4458
James Mattisf7027322020-12-13 16:28:14 -08004459 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004460 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004461 }
4462
James Mattis3ce3d3c2021-02-09 18:18:28 -08004463 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004464 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004465 for (final NetworkRequestInfo nri : nris) {
4466 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004467 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004468 for (final NetworkRequest req : nri.mRequests) {
4469 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004470 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004471 if (req.isListen()) {
4472 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4473 if (req.networkCapabilities.hasSignalStrength()
4474 && network.satisfiesImmutableCapabilitiesOf(req)) {
4475 updateSignalStrengthThresholds(network, "REGISTER", req);
4476 }
James Mattisf7027322020-12-13 16:28:14 -08004477 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004478 }
4479 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004480
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004481 // If this NRI has a satisfier already, it is replacing an older request that
4482 // has been removed. Track it.
4483 final NetworkRequest activeRequest = nri.getActiveRequest();
4484 if (null != activeRequest) {
4485 // If there is an active request, then for sure there is a satisfier.
4486 nri.getSatisfier().addRequest(activeRequest);
4487 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004488 }
James Mattisf7027322020-12-13 16:28:14 -08004489
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004490 if (mFlags.noRematchAllRequestsOnRegister()) {
4491 rematchNetworksAndRequests(nris);
4492 } else {
4493 rematchAllNetworksAndRequests();
4494 }
James Mattis45d81842021-01-10 14:24:24 -08004495
Chalard Jean0354d8c2021-01-12 10:58:56 +09004496 // Requests that have not been matched to a network will not have been sent to the
4497 // providers, because the old satisfier and the new satisfier are the same (null in this
4498 // case). Send these requests to the providers.
4499 for (final NetworkRequestInfo nri : nris) {
4500 for (final NetworkOfferInfo noi : mNetworkOffers) {
4501 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004502 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004503 }
4504 }
4505
James Mattisf7027322020-12-13 16:28:14 -08004506 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4507 final int callingUid) {
4508 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004509 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004510 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4511 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4512 handleReleaseNetworkRequest(
4513 nri.mRequests.get(0),
4514 callingUid,
4515 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004516 }
4517 }
4518
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004519 // Determines whether the network is the best (or could become the best, if it validated), for
4520 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4521 // on the value of reason:
4522 //
4523 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4524 // then it should be torn down.
4525 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4526 // then it should be lingered.
4527 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004528 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004529
4530 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4531 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4532 return false;
4533 }
4534
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004535 final int numRequests;
4536 switch (reason) {
4537 case TEARDOWN:
4538 numRequests = nai.numRequestNetworkRequests();
4539 break;
4540 case LINGER:
4541 numRequests = nai.numForegroundNetworkRequests();
4542 break;
4543 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004544 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004545 return true;
4546 }
4547
Chalard Jean947acd42021-03-08 22:29:27 +09004548 if (numRequests > 0) return false;
4549
Paul Jensende49eb12015-06-25 15:30:08 -04004550 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004551 if (reason == UnneededFor.LINGER
4552 && !nri.isMultilayerRequest()
4553 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004554 // Background requests don't affect lingering.
4555 continue;
4556 }
4557
James Mattis3d229892020-11-16 16:46:28 -08004558 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004559 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004560 }
4561 }
Paul Jensende49eb12015-06-25 15:30:08 -04004562 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004563 }
4564
James Mattis3d229892020-11-16 16:46:28 -08004565 private boolean isNetworkPotentialSatisfier(
4566 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4567 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004568 // request, return immediately. For multilayer requests, check to see if any of the
4569 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004570 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4571 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004572 return false;
4573 }
4574 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004575 // This multilayer listen request is satisfied therefore no further requests need to be
4576 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004577 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004578 return false;
4579 }
James Mattis3d229892020-11-16 16:46:28 -08004580 // As non-multilayer listen requests have already returned, the below would only happen
4581 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004582 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004583 continue;
4584 }
4585 // If this Network is already the highest scoring Network for a request, or if
4586 // there is hope for it to become one if it validated, then it is needed.
4587 if (candidate.satisfies(req)) {
4588 // As soon as a network is found that satisfies a request, return. Specifically for
4589 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4590 // is important so as to not evaluate lower priority requests further in
4591 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004592 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4593 ? nri.getSatisfier() : null;
4594 // Note that this catches two important cases:
4595 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4596 // is currently satisfying the request. This is desirable when
4597 // cellular ends up validating but WiFi does not.
4598 // 2. Unvalidated WiFi will not be reaped when validated cellular
4599 // is currently satisfying the request. This is desirable when
4600 // WiFi ends up validating and out scoring cellular.
4601 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004602 }
4603 }
4604
4605 return false;
4606 }
4607
Erik Kline0c04b742016-07-07 16:50:58 +09004608 private NetworkRequestInfo getNriForAppRequest(
4609 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004610 // Looking up the app passed param request in mRequests isn't possible since it may return
4611 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4612 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004613 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4614 // to avoid potential race conditions when validating a package->uid mapping when sending
4615 // the callback on the very low-chance that an application shuts down prior to the callback
4616 // being sent.
4617 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4618 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004619
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004620 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004621 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004622 log(String.format("UID %d attempted to %s for unowned request %s",
4623 callingUid, requestedOperation, nri));
4624 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004625 }
Erik Kline0c04b742016-07-07 16:50:58 +09004626 }
4627
4628 return nri;
4629 }
4630
James Mattisf7027322020-12-13 16:28:14 -08004631 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4632 final String callingMethod) {
4633 if (nri.isMultilayerRequest()) {
4634 throw new IllegalStateException(
4635 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004636 }
4637 }
4638
James Mattisf7027322020-12-13 16:28:14 -08004639 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004640 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004641 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4642 // single NetworkRequest and thus does not apply to multilayer requests.
4643 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4644 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004645 return;
4646 }
James Mattis2516da32021-01-31 17:06:19 -08004647 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004648 return;
4649 }
James Mattisf7027322020-12-13 16:28:14 -08004650 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4651 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004652 }
4653 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004654 callCallbackForRequest(
4655 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004656 }
4657
James Mattisf7027322020-12-13 16:28:14 -08004658 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4659 final int callingUid,
4660 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004661 final NetworkRequestInfo nri =
4662 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4663 if (nri == null) {
4664 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004665 }
James Mattisf7027322020-12-13 16:28:14 -08004666 if (VDBG || (DBG && request.isRequest())) {
4667 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004668 }
4669 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004670 if (callOnUnavailable) {
4671 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4672 }
Erik Kline155a59a2015-11-25 12:49:38 +09004673 }
Erik Kline0c04b742016-07-07 16:50:58 +09004674
James Mattisa076c532020-12-02 14:12:41 -08004675 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004676 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004677 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004678 if (null == mNetworkRequests.remove(req)) {
4679 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4680 continue;
4681 }
James Mattisa076c532020-12-02 14:12:41 -08004682 if (req.isListen()) {
4683 removeListenRequestFromNetworks(req);
4684 }
4685 }
James Mattis8f036802021-06-20 16:26:01 -07004686 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004687 if (mDefaultNetworkRequests.remove(nri)) {
4688 // If this request was one of the defaults, then the UID rules need to be updated
4689 // WARNING : if the app(s) for which this network request is the default are doing
4690 // traffic, this will kill their connected sockets, even if an equivalent request
4691 // is going to be reinstated right away ; unconnected traffic will go on the default
4692 // until the new default is set, which will happen very soon.
4693 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4694 // remove ranges for those requests that won't have a replacement
4695 final NetworkAgentInfo satisfier = nri.getSatisfier();
4696 if (null != satisfier) {
4697 try {
paulhu0e79d952021-06-09 16:11:35 +08004698 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4699 satisfier.network.getNetId(),
4700 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004701 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004702 } catch (RemoteException e) {
4703 loge("Exception setting network preference default network", e);
4704 }
4705 }
4706 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004707 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004708 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004709 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004710
4711 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004712 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004713 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004714 }
4715 }
4716
Chalard Jean0354d8c2021-01-12 10:58:56 +09004717 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4718 // needed for this offer.
4719 for (final NetworkOfferInfo noi : mNetworkOffers) {
4720 for (final NetworkRequest req : nri.mRequests) {
4721 if (req.isRequest() && noi.offer.neededFor(req)) {
4722 noi.offer.onNetworkUnneeded(req);
4723 }
4724 }
4725 }
James Mattisa076c532020-12-02 14:12:41 -08004726 }
4727
James Mattis3ce3d3c2021-02-09 18:18:28 -08004728 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4729 for (final NetworkRequestInfo nri : nris) {
4730 if (mDefaultRequest == nri) {
4731 // Make sure we never remove the default request.
4732 continue;
4733 }
4734 handleRemoveNetworkRequest(nri);
4735 }
4736 }
4737
James Mattisa076c532020-12-02 14:12:41 -08004738 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4739 // listens don't have a singular affected Network. Check all networks to see
4740 // if this listen request applies and remove it.
4741 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4742 nai.removeRequest(req.requestId);
4743 if (req.networkCapabilities.hasSignalStrength()
4744 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4745 updateSignalStrengthThresholds(nai, "RELEASE", req);
4746 }
4747 }
4748 }
4749
4750 /**
4751 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4752 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4753 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4754 */
4755 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4756 boolean wasKept = false;
4757 final NetworkAgentInfo nai = nri.getSatisfier();
4758 if (nai != null) {
4759 final int requestLegacyType = nri.getActiveRequest().legacyType;
4760 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4761 nai.removeRequest(nri.getActiveRequest().requestId);
4762 if (VDBG || DDBG) {
4763 log(" Removing from current network " + nai.toShortString()
4764 + ", leaving " + nai.numNetworkRequests() + " requests.");
4765 }
4766 // If there are still lingered requests on this network, don't tear it down,
4767 // but resume lingering instead.
4768 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004769 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004770 notifyNetworkLosing(nai, now);
4771 }
4772 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4773 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4774 teardownUnneededNetwork(nai);
4775 } else {
4776 wasKept = true;
4777 }
James Mattisa076c532020-12-02 14:12:41 -08004778 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4779 // Went from foreground to background.
4780 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004781 }
4782
Erik Kline0c04b742016-07-07 16:50:58 +09004783 // Maintain the illusion. When this request arrived, we might have pretended
4784 // that a network connected to serve it, even though the network was already
4785 // connected. Now that this request has gone away, we might have to pretend
4786 // that the network disconnected. LegacyTypeTracker will generate that
4787 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004788 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004789 boolean doRemove = true;
4790 if (wasKept) {
4791 // check if any of the remaining requests for this network are for the
4792 // same legacy type - if so, don't remove the nai
4793 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4794 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004795 if (otherRequest.legacyType == requestLegacyType
4796 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004797 if (DBG) log(" still have other legacy request - leaving");
4798 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004799 }
4800 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004801 }
4802
Erik Kline0c04b742016-07-07 16:50:58 +09004803 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004804 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004805 }
4806 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004807 }
4808 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004809
Junyu Lai00d92df2022-07-05 11:01:52 +08004810 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004811 return checkAnyPermissionOf(
4812 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4813 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4814 }
4815
Lorenzo Colittid6459092016-07-04 12:55:44 +09004816 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004817 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004818 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004819 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004820 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004821 }
4822
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004823 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004824 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4825 enforceNetworkStackSettingsOrSetup();
4826 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4827 encodeBool(accept), encodeBool(always), network));
4828 }
4829
4830 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004831 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004832 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004833 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4834 }
4835
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004836 @Override
4837 public void setTestAllowBadWifiUntil(long timeMs) {
4838 enforceSettingsPermission();
4839 if (!Build.isDebuggable()) {
4840 throw new IllegalStateException("Does not support in non-debuggable build");
4841 }
4842
4843 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4844 throw new IllegalArgumentException("It should not exceed "
4845 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4846 }
4847
4848 mHandler.sendMessage(
4849 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4850 }
4851
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004852 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4853 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4854 " accept=" + accept + " always=" + always);
4855
4856 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4857 if (nai == null) {
4858 // Nothing to do.
4859 return;
4860 }
4861
4862 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004863 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004864 return;
4865 }
4866
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004867 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004868 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004869 }
4870
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004871 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4872 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004873 // If network becomes partial connectivity and user already accepted to use this
4874 // network, we should respect the user's option and don't need to popup the
4875 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004876 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004877 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004878 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004879 }
4880
4881 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004882 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004883 }
4884
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004885 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004886 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004887 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004888 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004889 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004890 }
4891
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004892 }
4893
lucaslin2240ef62019-03-12 13:08:03 +08004894 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4895 boolean always) {
4896 if (DBG) {
4897 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4898 + " always=" + always);
4899 }
4900
4901 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4902 if (nai == null) {
4903 // Nothing to do.
4904 return;
4905 }
4906
4907 if (nai.lastValidated) {
4908 // The network validated while the dialog box was up. Take no action.
4909 return;
4910 }
4911
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004912 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4913 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004914 }
4915
4916 // TODO: Use the current design or save the user choice into IpMemoryStore.
4917 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004918 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004919 }
4920
4921 if (!accept) {
4922 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004923 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004924 // Tear down the network.
4925 teardownUnneededNetwork(nai);
4926 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004927 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4928 // result in a partial connectivity result which will be processed by
4929 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004930 //
4931 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4932 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004933 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004934 }
4935 }
4936
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004937 private void handleSetAvoidUnvalidated(Network network) {
4938 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4939 if (nai == null || nai.lastValidated) {
4940 // Nothing to do. The network either disconnected or revalidated.
4941 return;
4942 }
4943 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004944 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004945 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004946 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004947 }
4948 }
4949
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004950 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004951 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004952 mHandler.sendMessageDelayed(
4953 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4954 PROMPT_UNVALIDATED_DELAY_MS);
4955 }
4956
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004957 @Override
4958 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004959 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004960 mHandler.post(() -> {
4961 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4962 if (nai == null) return;
4963 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004964 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004965 });
4966 }
4967
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004968 /**
4969 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4970 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004971 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004972 * @param appExtras Bundle to use as intent extras for the captive portal application.
4973 * Must be treated as opaque to avoid preventing the captive portal app to
4974 * update its arguments.
4975 */
4976 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004977 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004978 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4979 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004980
4981 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4982 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004983 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4984 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004985 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4986
lucaslin75ff7022020-12-17 04:14:35 +08004987 final long token = Binder.clearCallingIdentity();
4988 try {
4989 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4990 } finally {
4991 Binder.restoreCallingIdentity(token);
4992 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004993 }
4994
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004995 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4996 private final Network mNetwork;
4997
4998 private CaptivePortalImpl(Network network) {
4999 mNetwork = network;
5000 }
5001
5002 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005003 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005004 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5005 enforceSettingsPermission();
5006 }
5007
Chiachang Wang938bfba2020-01-09 13:50:55 +08005008 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005009 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005010 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005011 }
5012
5013 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005014 public void appRequest(final int request) {
5015 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5016 if (nm == null) return;
5017
5018 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005019 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005020 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005021 }
5022 }
5023
5024 @Nullable
5025 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5026 // getNetworkAgentInfoForNetwork is thread-safe
5027 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5028 if (nai == null) return null;
5029
5030 // nai.networkMonitor() is thread-safe
5031 return nai.networkMonitor();
5032 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005033 }
5034
Hugo Benichic9048bc2016-09-14 23:23:08 +00005035 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005036 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005037 }
5038
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005039 /**
5040 * Return whether the device should maintain continuous, working connectivity by switching away
5041 * from WiFi networks having no connectivity.
5042 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5043 */
5044 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005045 if (!checkNetworkStackPermission()) {
5046 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5047 }
5048 return avoidBadWifi();
5049 }
5050
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005051 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005052 ensureRunningOnConnectivityServiceThread();
5053 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005054 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005055 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005056 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005057 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5058 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5059 for (final NetworkOfferInfo noi : offersToUpdate) {
5060 updateOfferScore(noi.offer);
5061 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005062 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005063 }
5064
Erik Kline95ecfee2016-10-02 18:02:14 +09005065 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005066 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005067 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005068 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005069 if (!configRestrict) {
5070 pw.println("Bad Wi-Fi avoidance: unrestricted");
5071 return;
5072 }
5073
5074 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5075 pw.increaseIndent();
5076 pw.println("Config restrict: " + configRestrict);
5077
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005078 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005079 String description;
5080 // Can't use a switch statement because strings are legal case labels, but null is not.
5081 if ("0".equals(value)) {
5082 description = "get stuck";
5083 } else if (value == null) {
5084 description = "prompt";
5085 } else if ("1".equals(value)) {
5086 description = "avoid";
5087 } else {
5088 description = value + " (?)";
5089 }
5090 pw.println("User setting: " + description);
5091 pw.println("Network overrides:");
5092 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005093 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005094 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09005095 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005096 }
5097 }
5098 pw.decreaseIndent();
5099 pw.decreaseIndent();
5100 }
5101
paulhu7746e4e2020-06-09 19:07:03 +08005102 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5103 // unify the method.
5104 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5105 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5106 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5107 return settingsComponent != null
5108 ? settingsComponent.getPackageName() : "com.android.settings";
5109 }
5110
lucaslinb1e8e382019-01-24 15:55:30 +08005111 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005112 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005113 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005114 switch (type) {
5115 case NO_INTERNET:
5116 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005117 // High priority because it is only displayed for explicitly selected networks.
5118 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005119 break;
lucasline117e2e2019-10-22 18:27:33 +08005120 case PRIVATE_DNS_BROKEN:
5121 action = Settings.ACTION_WIRELESS_SETTINGS;
5122 // High priority because we should let user know why there is no internet.
5123 highPriority = true;
5124 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005125 case LOST_INTERNET:
5126 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005127 // High priority because it could help the user avoid unexpected data usage.
5128 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005129 break;
lucaslin2240ef62019-03-12 13:08:03 +08005130 case PARTIAL_CONNECTIVITY:
5131 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005132 // Don't bother the user with a high-priority notification if the network was not
5133 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005134 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005135 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005136 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005137 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005138 return;
5139 }
5140
5141 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005142 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005143 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005144 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005145 // Some OEMs have their own Settings package. Thus, need to get the current using
5146 // Settings package name instead of just use default name "com.android.settings".
5147 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5148 intent.setClassName(settingsPkgName,
5149 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005150 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005151
paulhu2af50222020-10-11 22:52:27 +08005152 PendingIntent pendingIntent = PendingIntent.getActivity(
5153 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005154 0 /* requestCode */,
5155 intent,
paulhu2af50222020-10-11 22:52:27 +08005156 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005157
Serik Beketayevec8ad212020-12-07 22:43:07 -08005158 mNotifier.showNotification(
5159 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005160 }
5161
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005162 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5163 // Don't prompt if the network is validated, and don't prompt on captive portals
5164 // because we're already prompting the user to sign in.
5165 if (nai.everValidated || nai.everCaptivePortalDetected) {
5166 return false;
5167 }
5168
5169 // If a network has partial connectivity, always prompt unless the user has already accepted
5170 // partial connectivity and selected don't ask again. This ensures that if the device
5171 // automatically connects to a network that has partial Internet access, the user will
5172 // always be able to use it, either because they've already chosen "don't ask again" or
5173 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005174 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005175 return true;
5176 }
5177
5178 // If a network has no Internet access, only prompt if the network was explicitly selected
5179 // and if the user has not already told us to use the network regardless of whether it
5180 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005181 if (nai.networkAgentConfig.explicitlySelected
5182 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005183 return true;
5184 }
5185
5186 return false;
5187 }
5188
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005189 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09005190 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005191 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5192
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005193 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005194 return;
5195 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005196
5197 // Stop automatically reconnecting to this network in the future. Automatically connecting
5198 // to a network that provides no or limited connectivity is not useful, because the user
5199 // cannot use that network except through the notification shown by this method, and the
5200 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005201 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005202
lucaslin2240ef62019-03-12 13:08:03 +08005203 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5204 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5205 // popup the notification immediately when the network is partial connectivity.
5206 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08005207 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005208 } else {
5209 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5210 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005211 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005212
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005213 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5214 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005215 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005216
lucaslin2240ef62019-03-12 13:08:03 +08005217 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5218 return;
5219 }
5220
5221 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005222 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005223 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005224 }
5225
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005226 @Override
5227 public int getMultipathPreference(Network network) {
5228 enforceAccessPermission();
5229
5230 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005231 if (nai != null && nai.networkCapabilities
5232 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005233 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5234 }
5235
Aaron Huang9a57acf2020-12-08 10:03:29 +08005236 final NetworkPolicyManager netPolicyManager =
5237 mContext.getSystemService(NetworkPolicyManager.class);
5238
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005239 final long token = Binder.clearCallingIdentity();
5240 final int networkPreference;
5241 try {
5242 networkPreference = netPolicyManager.getMultipathPreference(network);
5243 } finally {
5244 Binder.restoreCallingIdentity(token);
5245 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005246 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005247 return networkPreference;
5248 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005249 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5250 }
5251
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005252 @Override
5253 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005254 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005255 }
5256
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005257 private class InternalHandler extends Handler {
5258 public InternalHandler(Looper looper) {
5259 super(looper);
5260 }
5261
5262 @Override
5263 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005264 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005265 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005266 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005267 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005268 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005269 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005270 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005271 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005272 break;
5273 }
Jason Monka69f1b02013-10-10 14:02:51 -04005274 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005275 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5276 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005277 break;
5278 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005279 case EVENT_REGISTER_NETWORK_PROVIDER: {
5280 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005281 break;
5282 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005283 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5284 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005285 break;
5286 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005287 case EVENT_REGISTER_NETWORK_OFFER: {
5288 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5289 break;
5290 }
5291 case EVENT_UNREGISTER_NETWORK_OFFER: {
5292 final NetworkOfferInfo offer =
5293 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5294 if (null != offer) {
5295 handleUnregisterNetworkOffer(offer);
5296 }
5297 break;
5298 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005299 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005300 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5301 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5302 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005303 break;
5304 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005305 case EVENT_REGISTER_NETWORK_REQUEST:
5306 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005307 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005308 break;
5309 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005310 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5311 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005312 handleRegisterNetworkRequestWithIntent(msg);
5313 break;
5314 }
Erik Kline155a59a2015-11-25 12:49:38 +09005315 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5316 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5317 handleTimedOutNetworkRequest(nri);
5318 break;
5319 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005320 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5321 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5322 break;
5323 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005324 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005325 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5326 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005327 break;
5328 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005329 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005330 Network network = (Network) msg.obj;
5331 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005332 break;
5333 }
lucaslin2240ef62019-03-12 13:08:03 +08005334 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5335 Network network = (Network) msg.obj;
5336 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5337 toBool(msg.arg2));
5338 break;
5339 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005340 case EVENT_SET_AVOID_UNVALIDATED: {
5341 handleSetAvoidUnvalidated((Network) msg.obj);
5342 break;
5343 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005344 case EVENT_PROMPT_UNVALIDATED: {
5345 handlePromptUnvalidated((Network) msg.obj);
5346 break;
5347 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005348 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5349 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005350 break;
5351 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005352 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005353 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005354 mKeepaliveTracker.handleStartKeepalive(msg);
5355 break;
5356 }
5357 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005358 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005359 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5360 int slot = msg.arg1;
5361 int reason = msg.arg2;
5362 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5363 break;
5364 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005365 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5366 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5367 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005368 break;
5369 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005370 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5371 handlePrivateDnsSettingsChanged();
5372 break;
dalyk1720e542018-03-05 12:42:22 -05005373 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5374 handlePrivateDnsValidationUpdate(
5375 (PrivateDnsValidationUpdate) msg.obj);
5376 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005377 case EVENT_UID_BLOCKED_REASON_CHANGED:
5378 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005379 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005380 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5381 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5382 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005383 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005384 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5385 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005386 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005387 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005388 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005389 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005390 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5391 IOnCompleteListener> arg =
5392 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5393 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005394 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005395 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005396 }
lucaslin1193a5d2021-01-21 02:04:15 +08005397 case EVENT_REPORT_NETWORK_ACTIVITY:
5398 mNetworkActivityTracker.handleReportNetworkActivity();
5399 break;
paulhu51f77dc2021-06-07 02:34:20 +00005400 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5401 handleMobileDataPreferredUidsChanged();
5402 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005403 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5404 final long timeMs = ((Long) msg.obj).longValue();
5405 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5406 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005407 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5408 handleIngressRateLimitChanged();
5409 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005410 }
5411 }
5412 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005413
Lorenzo Colittid6459092016-07-04 12:55:44 +09005414 @Override
markchien5776f962019-12-16 20:15:20 +08005415 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005416 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005417 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005418 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5419 Context.TETHERING_SERVICE);
5420 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005421 }
5422
Lorenzo Colittid6459092016-07-04 12:55:44 +09005423 @Override
markchien5776f962019-12-16 20:15:20 +08005424 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005425 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005426 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005427 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5428 Context.TETHERING_SERVICE);
5429 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005430 }
5431
Lorenzo Colittid6459092016-07-04 12:55:44 +09005432 @Override
markchien5776f962019-12-16 20:15:20 +08005433 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005434 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005435 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005436 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5437 Context.TETHERING_SERVICE);
5438 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005439 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005440
markchien5776f962019-12-16 20:15:20 +08005441
Lorenzo Colittid6459092016-07-04 12:55:44 +09005442 @Override
markchien5776f962019-12-16 20:15:20 +08005443 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005444 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005445 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005446 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5447 Context.TETHERING_SERVICE);
5448
5449 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005450 }
5451
Lorenzo Colittid6459092016-07-04 12:55:44 +09005452 @Override
markchien5776f962019-12-16 20:15:20 +08005453 @Deprecated
5454 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005455 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005456 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5457 Context.TETHERING_SERVICE);
5458
5459 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005460 }
5461
Udam Saini8f7d6a72017-06-07 12:06:28 -07005462 @Override
markchien5776f962019-12-16 20:15:20 +08005463 @Deprecated
5464 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005465 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005466 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5467 Context.TETHERING_SERVICE);
5468 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005469 }
5470
Robert Greenwalte0b00512014-07-02 09:59:16 -07005471 // Called when we lose the default network and have no replacement yet.
5472 // This will automatically be cleared after X seconds or a new default network
5473 // becomes CONNECTED, whichever happens first. The timer is started by the
5474 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005475 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005476 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005477 if (mNetTransitionWakeLock.isHeld()) {
5478 return;
5479 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005480 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005481 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5482 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005483 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005484 mWakelockLogs.log("ACQUIRE for " + forWhom);
5485 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005486 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005487 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005488 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005489 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005490
Hugo Benichi471b62a2017-03-30 23:18:10 +09005491 // Called when we gain a new default network to release the network transition wakelock in a
5492 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5493 // message is cancelled.
5494 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005495 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005496 if (!mNetTransitionWakeLock.isHeld()) {
5497 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005498 }
5499 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005500 // Cancel self timeout on wakelock hold.
5501 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5502 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5503 mHandler.sendMessageDelayed(msg, 1000);
5504 }
5505
5506 // Called when either message of ensureNetworkTransitionWakelock or
5507 // scheduleReleaseNetworkTransitionWakelock is processed.
5508 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5509 String event = eventName(eventId);
5510 synchronized (this) {
5511 if (!mNetTransitionWakeLock.isHeld()) {
5512 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005513 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005514 return;
5515 }
5516 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005517 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5518 mTotalWakelockDurationMs += lockDuration;
5519 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5520 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005521 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005522 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005523 }
5524
Robert Greenwalt986c7412010-09-08 15:24:47 -07005525 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005526 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005527 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005528 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005529 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005530 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005531 }
5532
Lorenzo Colittid6459092016-07-04 12:55:44 +09005533 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005534 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005535 enforceAccessPermission();
5536 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005537 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005538 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005539
5540 final NetworkAgentInfo nai;
5541 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005542 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005543 } else {
5544 nai = getNetworkAgentInfoForNetwork(network);
5545 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005546
5547 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005548 mHandler.obtainMessage(
5549 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005550 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005551
Hugo Benichid6b510a2017-04-06 17:22:18 +09005552 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005553 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005554 if (nai == null
5555 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005556 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005557 return;
5558 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005559 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005560 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005561 mConnectivityDiagnosticsHandler.sendMessage(
5562 mConnectivityDiagnosticsHandler.obtainMessage(
5563 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5564 new ReportedNetworkConnectivityInfo(
5565 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005566 return;
5567 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005568 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005569 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005570 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005571 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005572 // Validating a network that has not yet connected could result in a call to
5573 // rematchNetworkAndRequests() which is not meant to work on such networks.
5574 if (!nai.everConnected) {
5575 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005576 }
paulhu7aeba372020-12-30 00:42:19 +08005577 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5578 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005579 return;
5580 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005581
5582 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5583 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5584 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5585 // completed.
5586 mConnectivityDiagnosticsHandler.sendMessage(
5587 mConnectivityDiagnosticsHandler.obtainMessage(
5588 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5589 new ReportedNetworkConnectivityInfo(
5590 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005591 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005592 }
5593
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005594 // TODO: call into netd.
5595 private boolean queryUserAccess(int uid, Network network) {
5596 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5597 if (nai == null) return false;
5598
5599 // Any UID can use its default network.
5600 if (nai == getDefaultNetworkForUid(uid)) return true;
5601
5602 // Privileged apps can use any network.
5603 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5604 return true;
5605 }
5606
5607 // An unprivileged UID can use a VPN iff the VPN applies to it.
5608 if (nai.isVPN()) {
5609 return nai.networkCapabilities.appliesToUid(uid);
5610 }
5611
5612 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5613 // sockets, i.e., if it is the owner.
5614 final NetworkAgentInfo vpn = getVpnForUid(uid);
5615 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5616 && uid != vpn.networkCapabilities.getOwnerUid()) {
5617 return false;
5618 }
5619
5620 // The UID's permission must be at least sufficient for the network. Since the restricted
5621 // permission was already checked above, that just leaves background networks.
5622 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5623 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5624 }
5625
5626 // Unrestricted network. Anyone gets to use it.
5627 return true;
5628 }
5629
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005630 /**
5631 * Returns information about the proxy a certain network is using. If given a null network, it
5632 * it will return the proxy for the bound network for the caller app or the default proxy if
5633 * none.
5634 *
5635 * @param network the network we want to get the proxy information for.
5636 * @return Proxy information if a network has a proxy configured, or otherwise null.
5637 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005638 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005639 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005640 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005641 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005642 if (network == null) {
5643 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005644 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005645 true);
5646 if (activeNetwork == null) {
5647 return null;
5648 }
5649 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005650 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005651 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5652 // caller may not have.
5653 return getLinkPropertiesProxyInfo(network);
5654 }
5655 // No proxy info available if the calling UID does not have network access.
5656 return null;
5657 }
5658
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005659
5660 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005661 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5662 if (nai == null) return null;
5663 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005664 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5665 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005666 }
5667 }
5668
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005669 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005670 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005671 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005672 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005673 }
5674
Chalard Jean777e2e52018-06-07 18:02:37 +09005675 @Override
5676 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005677 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005678 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005679 }
5680
Jason Monk4d5e20f2014-04-25 15:00:09 -04005681 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005682 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005683 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005684 proxy = null;
5685 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005686 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005687 }
5688
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005689 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5690 // when any network changes proxy.
5691 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5692 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005693 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005694 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5695 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5696
Chalard Jean7d97afc2018-06-07 17:41:29 +09005697 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005698 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005699 }
5700 }
5701
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005702 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005703 final private HashMap<Uri, Integer> mUriEventMap;
5704 final private Context mContext;
5705 final private Handler mHandler;
5706
5707 SettingsObserver(Context context, Handler handler) {
5708 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005709 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005710 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005711 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005712 }
5713
Erik Kline05f2b402015-04-30 12:58:40 +09005714 void observe(Uri uri, int what) {
5715 mUriEventMap.put(uri, what);
5716 final ContentResolver resolver = mContext.getContentResolver();
5717 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005718 }
5719
5720 @Override
5721 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005722 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005723 }
5724
5725 @Override
5726 public void onChange(boolean selfChange, Uri uri) {
5727 final Integer what = mUriEventMap.get(uri);
5728 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005729 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005730 } else {
5731 loge("No matching event to send for URI=" + uri);
5732 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005733 }
5734 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005735
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005736 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005737 Log.d(TAG, s);
5738 }
5739
5740 private static void logw(String s) {
5741 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005742 }
5743
Daniel Brightf9e945b2020-06-15 16:10:01 -07005744 private static void logwtf(String s) {
5745 Log.wtf(TAG, s);
5746 }
5747
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005748 private static void logwtf(String s, Throwable t) {
5749 Log.wtf(TAG, s, t);
5750 }
5751
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005752 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005753 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005754 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005755
Hugo Benichi39621362017-02-11 17:04:43 +09005756 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005757 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005758 }
5759
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005760 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005761 * Return the information of all ongoing VPNs.
5762 *
5763 * <p>This method is used to update NetworkStatsService.
5764 *
5765 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005766 */
junyulai2050bed2021-01-23 09:46:34 +08005767 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005768 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005769 if (mLockdownEnabled) {
5770 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005771 }
junyulai2050bed2021-01-23 09:46:34 +08005772 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005773 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005774 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005775 if (info != null) {
5776 infoList.add(info);
5777 }
5778 }
junyulai2050bed2021-01-23 09:46:34 +08005779 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005780 }
5781
5782 /**
5783 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005784 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005785 */
junyulai2050bed2021-01-23 09:46:34 +08005786 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005787 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005788 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5789 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005790 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5791 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5792 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005793 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5794 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005795 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005796 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005797 }
5798 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005799
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005800 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005801
5802 List<String> interfaces = new ArrayList<>();
5803 for (Network network : underlyingNetworks) {
5804 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5805 if (underlyingNai == null) continue;
5806 LinkProperties lp = underlyingNai.linkProperties;
5807 for (String iface : lp.getAllInterfaceNames()) {
5808 if (!TextUtils.isEmpty(iface)) {
5809 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005810 }
5811 }
Benedict Wong34857f82019-06-12 17:46:15 +00005812 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005813
5814 if (interfaces.isEmpty()) return null;
5815
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005816 // Must be non-null or NetworkStatsService will crash.
5817 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5818 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005819 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005820 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005821
junyulai2050bed2021-01-23 09:46:34 +08005822 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5823 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005824 }
5825
James Mattisd31bdfa2020-12-23 16:37:26 -08005826 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005827 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5828 Network[] underlyingNetworks) {
5829 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005830 if (underlyingNetworks == null && defaultNetwork != null) {
5831 // null underlying networks means to track the default.
5832 underlyingNetworks = new Network[] { defaultNetwork };
5833 }
5834 return underlyingNetworks;
5835 }
5836
5837 // Returns true iff |network| is an underlying network of |nai|.
5838 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5839 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5840 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005841 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005842 final Network[] underlying = underlyingNetworksOrDefault(
5843 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005844 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005845 }
5846
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005847 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005848 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005849 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005850 * When underlying networks change, such networks may have to update capabilities to reflect
5851 * things like the metered bit, their transports, and so on. The capabilities are calculated
5852 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005853 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005854 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005855 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005856 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005857 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005858 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005859 }
5860 }
5861 }
5862
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005863 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5864 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5865 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5866 // a VPN is not up.
5867 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5868 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5869 for (UidRange range : blockedUidRanges) {
5870 if (range.contains(uid)) return true;
5871 }
5872 return false;
5873 }
5874
5875 @Override
5876 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005877 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005878 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5879 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5880 }
5881
5882 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5883 if (DBG) {
5884 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5885 + Arrays.toString(ranges));
5886 }
5887 // Cannot use a Set since the list of UID ranges might contain duplicates.
5888 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5889 for (int i = 0; i < ranges.length; i++) {
5890 if (requireVpn) {
5891 newVpnBlockedUidRanges.add(ranges[i]);
5892 } else {
5893 newVpnBlockedUidRanges.remove(ranges[i]);
5894 }
5895 }
5896
5897 try {
5898 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5899 } catch (RemoteException | ServiceSpecificException e) {
5900 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5901 + Arrays.toString(ranges) + "): netd command failed: " + e);
5902 }
5903
Motomu Utsumib08654c2022-05-11 05:56:26 +00005904 if (SdkLevel.isAtLeastT()) {
5905 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5906 }
5907
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005908 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5909 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005910 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5911 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005912 }
5913
5914 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5915 }
5916
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005917 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005918 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005919 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005920 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005921 }
5922
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005923 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5924 return mLockdownEnabled
5925 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5926 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005927 }
5928
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005929 private NetworkAgentInfo getLegacyLockdownNai() {
5930 if (!mLockdownEnabled) {
5931 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005932 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005933 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005934 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5935 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005936
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005937 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005938 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5939 // a local variable. There is no need to make a copy because its contents cannot change.
5940 final Network[] underlying = nai.declaredUnderlyingNetworks;
5941 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005942 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005943 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005944
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005945 // The legacy lockdown VPN always uses the default network.
5946 // If the VPN's underlying network is no longer the current default network, it means that
5947 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005948 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5949 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005950 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005951 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005952 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005953 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005954
5955 return nai;
5956 };
5957
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005958 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5959 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5960 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005961 private DetailedState getLegacyLockdownState(DetailedState origState) {
5962 if (origState != DetailedState.CONNECTED) {
5963 return origState;
5964 }
5965 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5966 ? DetailedState.CONNECTING
5967 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005968 }
5969
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005970 private void filterForLegacyLockdown(NetworkInfo ni) {
5971 if (!mLockdownEnabled || !ni.isConnected()) return;
5972 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5973 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5974 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5975 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5976 // network, this time with a state of CONNECTED.
5977 //
5978 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5979 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5980 // is not too far off the truth, since an always-on VPN, when not connected, is always
5981 // trying to reconnect.
5982 if (getLegacyLockdownNai() == null) {
5983 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5984 }
5985 }
5986
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005987 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005988 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005989 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005990 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005991 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5992 return;
5993 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005994 final long ident = Binder.clearCallingIdentity();
5995 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005996 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005997 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005998 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005999 } finally {
6000 Binder.restoreCallingIdentity(ident);
6001 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006002 }
Wink Savillecb117d32013-08-29 14:57:08 -07006003
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006004 @Override
6005 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006006 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006007 final long ident = Binder.clearCallingIdentity();
6008 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006009 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006010 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006011 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6012 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006013 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006014 } finally {
6015 Binder.restoreCallingIdentity(ident);
6016 }
6017 }
6018
James Mattis02220e22021-03-13 19:27:21 -08006019 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006020 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006021 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6022 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6023 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006024 }
6025
James Mattis02220e22021-03-13 19:27:21 -08006026 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006027 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006028 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006029 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006030 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006031 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006032 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6033 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6034 }
junyulaid91e7052020-08-28 13:44:33 +08006035 }
6036
James Mattis02220e22021-03-13 19:27:21 -08006037 private void onPackageChanged(@NonNull final String packageName) {
6038 // This is necessary in case a package is added or removed, but also when it's replaced to
6039 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6040 // as one in the preferences, then it should follow the same routing as that other package,
6041 // which means updating the rules is never to be needed in this case (whether it joins or
6042 // leaves a UID with a preference).
6043 if (isMappedInOemNetworkPreference(packageName)) {
6044 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6045 }
6046 }
6047
6048 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006049 @Override
6050 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006051 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006052 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006053 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006054
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006055 // User should be filled for below intents, check the existence.
6056 if (user == null) {
6057 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6058 return;
6059 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006060
Lorenzo Colitticd675292021-02-04 17:32:07 +09006061 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006062 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006063 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006064 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006065 } else {
junyulaid91e7052020-08-28 13:44:33 +08006066 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006067 }
6068 }
6069 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006070
James Mattis02220e22021-03-13 19:27:21 -08006071 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6072 @Override
6073 public void onReceive(Context context, Intent intent) {
6074 ensureRunningOnConnectivityServiceThread();
6075 switch (intent.getAction()) {
6076 case Intent.ACTION_PACKAGE_ADDED:
6077 case Intent.ACTION_PACKAGE_REMOVED:
6078 case Intent.ACTION_PACKAGE_REPLACED:
6079 onPackageChanged(intent.getData().getSchemeSpecificPart());
6080 break;
6081 default:
6082 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6083 }
6084 }
6085 };
6086
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006087 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006088 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006089
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006090 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006091 public final String name;
6092 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006093 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006094 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006095
lifraf3a3492021-03-10 13:58:14 +08006096 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6097 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006098 this.name = name;
6099 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006100 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006101 mDeathRecipient = deathRecipient;
6102
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006103 if (mDeathRecipient == null) {
6104 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006105 }
6106 }
6107
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006108 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006109 try {
6110 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6111 } catch (RemoteException e) {
6112 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006113 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006114 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006115 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006116
James Mattis4fce5d12020-11-12 15:53:42 -08006117 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6118 for (int i = 0; i < requests.size(); i++) {
6119 ensureNetworkRequestHasType(requests.get(i));
6120 }
6121 }
6122
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006123 private void ensureNetworkRequestHasType(NetworkRequest request) {
6124 if (request.type == NetworkRequest.Type.NONE) {
6125 throw new IllegalArgumentException(
6126 "All NetworkRequests in ConnectivityService must have a type");
6127 }
6128 }
6129
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006130 /**
6131 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006132 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006133 */
James Mattis258ea3c2020-11-15 15:04:40 -08006134 @VisibleForTesting
6135 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006136 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6137 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006138 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006139
James Mattisa076c532020-12-02 14:12:41 -08006140 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6141 void setSatisfier(
6142 @Nullable final NetworkAgentInfo satisfier,
6143 @Nullable final NetworkRequest activeRequest) {
6144 mSatisfier = satisfier;
6145 mActiveRequest = activeRequest;
6146 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006147
James Mattisd31bdfa2020-12-23 16:37:26 -08006148 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006149 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006150 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006151 private NetworkAgentInfo mSatisfier;
6152 NetworkAgentInfo getSatisfier() {
6153 return mSatisfier;
6154 }
6155
6156 // The request in mRequests assigned to a network agent. This is null if none of the
6157 // requests in mRequests can be satisfied. This member has the constraint of only being
6158 // accessible on the handler thread.
6159 @Nullable
6160 private NetworkRequest mActiveRequest;
6161 NetworkRequest getActiveRequest() {
6162 return mActiveRequest;
6163 }
6164
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006165 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006166 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006167 @Nullable
6168 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006169
6170 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006171 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006172 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006173 final int mPid;
6174 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006175 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006176 @Nullable
6177 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006178
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006179 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006180 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006181
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006182 // Effective UID of this request. This is different from mUid when a privileged process
6183 // files a request on behalf of another UID. This UID is used to determine blocked status,
6184 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6185 // maximum limit of registered callbacks per UID.
6186 final int mAsUid;
6187
paulhu48291862021-07-14 14:53:57 +08006188 // Preference order of this request.
6189 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006190
James Mattis3ce3d3c2021-02-09 18:18:28 -08006191 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6192 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6193 // maintained for keying off of. This is only a concern when the original nri
6194 // mNetworkRequests changes which happens currently for apps that register callbacks to
6195 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6196 // that match the per-app default nri that currently tracks the calling app's uid so that
6197 // callbacks are fired at the appropriate time. When the callbacks fire,
6198 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6199 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6200 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6201 @NonNull
6202 private final NetworkRequest mNetworkRequestForCallback;
6203 NetworkRequest getNetworkRequestForCallback() {
6204 return mNetworkRequestForCallback;
6205 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006206
James Mattisd31bdfa2020-12-23 16:37:26 -08006207 /**
6208 * Get the list of UIDs this nri applies to.
6209 */
6210 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006211 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006212 // networkCapabilities.getUids() returns a defensive copy.
6213 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006214 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6215 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006216 }
6217
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006218 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6219 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006220 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006221 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006222 }
6223
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006224 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006225 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006226 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006227 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006228 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006229 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006230 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006231 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006232 mBinder = null;
6233 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006234 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006235 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006236 mPerUidCounter = getRequestCounter(this);
6237 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006238 /**
6239 * Location sensitive data not included in pending intent. Only included in
6240 * {@link NetworkCallback}.
6241 */
6242 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006243 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006244 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006245 }
6246
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006247 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006248 @Nullable final IBinder binder,
6249 @NetworkCallback.Flag int callbackFlags,
6250 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006251 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6252 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006253 }
6254
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006255 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006256 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006257 @Nullable final IBinder binder,
6258 @NetworkCallback.Flag int callbackFlags,
6259 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006260 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006261 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006262 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006263 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006264 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006265 mBinder = binder;
6266 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006267 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006268 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006269 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006270 mPerUidCounter = getRequestCounter(this);
6271 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006272 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006273 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006274 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006275 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006276 }
6277
James Mattis3ce3d3c2021-02-09 18:18:28 -08006278 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6279 @NonNull final List<NetworkRequest> r) {
6280 super();
6281 ensureAllNetworkRequestsHaveType(r);
6282 mRequests = initializeRequests(r);
6283 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006284 final NetworkAgentInfo satisfier = nri.getSatisfier();
6285 if (null != satisfier) {
6286 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6287 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006288 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006289 // As this code creates a new NRI with a new set of requests, figure out which of
6290 // the list of requests should be the active request. It is always the first
6291 // request of the list that can be satisfied by the satisfier since the order of
6292 // requests is a priority order.
6293 // Note even in the presence of a satisfier there may not be an active request,
6294 // when the satisfier is the no-service network.
6295 NetworkRequest activeRequest = null;
6296 for (final NetworkRequest candidate : r) {
6297 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6298 activeRequest = candidate;
6299 break;
6300 }
6301 }
6302 setSatisfier(satisfier, activeRequest);
6303 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006304 mMessenger = nri.mMessenger;
6305 mBinder = nri.mBinder;
6306 mPid = nri.mPid;
6307 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006308 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006309 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006310 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006311 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006312 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006313 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006314 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006315 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006316 }
6317
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006318 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006319 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006320 }
6321
paulhue9913722021-05-26 15:19:20 +08006322 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006323 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006324 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006325 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006326 }
6327
James Mattis2516da32021-01-31 17:06:19 -08006328 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6329 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6330 // false.
6331 boolean isBeingSatisfied() {
6332 return (null != mSatisfier && null != mActiveRequest);
6333 }
6334
James Mattis3d229892020-11-16 16:46:28 -08006335 boolean isMultilayerRequest() {
6336 return mRequests.size() > 1;
6337 }
6338
James Mattis45d81842021-01-10 14:24:24 -08006339 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6340 // Creating a defensive copy to prevent the sender from modifying the list being
6341 // reflected in the return value of this method.
6342 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006343 return Collections.unmodifiableList(tempRequests);
6344 }
6345
James Mattisb1392002021-03-31 13:57:52 -07006346 void linkDeathRecipient() {
6347 if (null != mBinder) {
6348 try {
6349 mBinder.linkToDeath(this, 0);
6350 } catch (RemoteException e) {
6351 binderDied();
6352 }
6353 }
6354 }
6355
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006356 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006357 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006358 try {
6359 mBinder.unlinkToDeath(this, 0);
6360 } catch (NoSuchElementException e) {
6361 // Temporary workaround for b/194394697 pending analysis of additional logs
6362 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6363 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006364 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006365 }
6366
paulhu48291862021-07-14 14:53:57 +08006367 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6368 // Compare two preference orders.
6369 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006370 }
6371
paulhu48291862021-07-14 14:53:57 +08006372 int getPreferenceOrderForNetd() {
6373 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6374 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6375 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006376 }
paulhu48291862021-07-14 14:53:57 +08006377 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006378 }
6379
James Mattis4fce5d12020-11-12 15:53:42 -08006380 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006381 public void binderDied() {
6382 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006383 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006384 // As an immutable collection, mRequests cannot change by the time the
6385 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6386 // is acceptable. Use handleReleaseNetworkRequest and not directly
6387 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6388 // the app already unregistered the request.
6389 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6390 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006391 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006392
James Mattis4fce5d12020-11-12 15:53:42 -08006393 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006394 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006395 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6396 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006397 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006398 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006399 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006400 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006401 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006402 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006403 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006404 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006405 }
6406
Junyu Lai00d92df2022-07-05 11:01:52 +08006407 // Keep backward compatibility since the ServiceSpecificException is used by
6408 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6409 public static class RequestInfoPerUidCounter extends PerUidCounter {
6410 RequestInfoPerUidCounter(int maxCountPerUid) {
6411 super(maxCountPerUid);
6412 }
6413
6414 @Override
6415 public synchronized void incrementCountOrThrow(int uid) {
6416 try {
6417 super.incrementCountOrThrow(uid);
6418 } catch (IllegalStateException e) {
6419 throw new ServiceSpecificException(
6420 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6421 "Uid " + uid + " exceeded its allotted requests limit");
6422 }
6423 }
6424
6425 @Override
6426 public synchronized void decrementCountOrThrow(int uid) {
6427 throw new UnsupportedOperationException("Use decrementCount instead.");
6428 }
6429
6430 public synchronized void decrementCount(int uid) {
6431 try {
6432 super.decrementCountOrThrow(uid);
6433 } catch (IllegalStateException e) {
6434 logwtf("Exception when decrement per uid request count: ", e);
6435 }
6436 }
6437 }
6438
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006439 // This checks that the passed capabilities either do not request a
6440 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006441 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006442 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006443 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006444 throw new SecurityException("Insufficient permissions to request a specific SSID");
6445 }
paulhu1a407652019-03-22 16:35:06 +08006446
6447 if (nc.hasSignalStrength()
6448 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6449 throw new SecurityException(
6450 "Insufficient permissions to request a specific signal strength");
6451 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006452 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006453
junyulai2217bec2021-04-14 23:33:31 +08006454 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006455 enforceNetworkFactoryPermission();
6456 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006457 }
6458
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006459 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006460 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006461 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006462 // mNetworkRequests may contain the same value multiple times in case of
6463 // multilayer requests. It won't matter in this case because the thresholds
6464 // will then be the same and be deduplicated as they enter the `thresholds` set.
6465 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006466 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6467 for (final NetworkRequest req : nri.mRequests) {
6468 if (req.networkCapabilities.hasSignalStrength()
6469 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6470 thresholds.add(req.networkCapabilities.getSignalStrength());
6471 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006472 }
6473 }
6474 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006475 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006476 }
6477
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006478 private void updateSignalStrengthThresholds(
6479 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006480 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006481
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006482 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006483 String detail;
6484 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6485 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6486 } else {
6487 detail = reason;
6488 }
6489 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006490 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006491 }
6492
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006493 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006494 }
6495
Chalard Jeandd421992021-12-16 23:16:02 +09006496 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006497 if (nc == null) {
6498 return;
6499 }
6500 NetworkSpecifier ns = nc.getNetworkSpecifier();
6501 if (ns == null) {
6502 return;
6503 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006504 if (ns instanceof MatchAllNetworkSpecifier) {
6505 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6506 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006507 }
6508
Chalard Jeandd421992021-12-16 23:16:02 +09006509 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006510 ensureValidNetworkSpecifier(nc);
6511 if (nc.isPrivateDnsBroken()) {
6512 throw new IllegalArgumentException("Can't request broken private DNS");
6513 }
Chalard Jeande665262022-02-25 16:12:12 +09006514 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006515 throw new IllegalArgumentException("Can't request access UIDs");
6516 }
lucasline117e2e2019-10-22 18:27:33 +08006517 }
6518
Chalard Jeandd421992021-12-16 23:16:02 +09006519 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6520 ensureListenableCapabilities(nc);
6521 final String badCapability = nc.describeFirstNonRequestableCapability();
6522 if (badCapability != null) {
6523 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6524 }
6525 }
6526
Chiachang Wang3bc52762021-11-25 14:17:57 +08006527 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6528 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006529 private boolean isTargetSdkAtleast(int version, int callingUid,
6530 @NonNull String callingPackageName) {
6531 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006532 final PackageManager pm =
6533 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006534 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006535 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006536 if (callingVersion < version) return false;
6537 } catch (PackageManager.NameNotFoundException e) { }
6538 return true;
6539 }
6540
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006541 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006542 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006543 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006544 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006545 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006546 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006547 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6548 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006549 throw new SecurityException("Insufficient permissions to specify legacy type");
6550 }
markchienfac84a22020-03-18 21:16:15 +08006551 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006552 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006553 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006554 // Privileged callers can track the default network of another UID by passing in a UID.
6555 if (asUid != Process.INVALID_UID) {
6556 enforceSettingsPermission();
6557 } else {
6558 asUid = callingUid;
6559 }
junyulaiad010792021-01-11 16:53:38 +08006560 final NetworkRequest.Type reqType;
6561 try {
6562 reqType = NetworkRequest.Type.values()[reqTypeInt];
6563 } catch (ArrayIndexOutOfBoundsException e) {
6564 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6565 }
6566 switch (reqType) {
6567 case TRACK_DEFAULT:
6568 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006569 // is unused and will be replaced by ones appropriate for the UID (usually, the
6570 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006571 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006572 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006573 enforceAccessPermission();
6574 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006575 case TRACK_SYSTEM_DEFAULT:
6576 enforceSettingsPermission();
6577 networkCapabilities = new NetworkCapabilities(defaultNc);
6578 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006579 case BACKGROUND_REQUEST:
6580 enforceNetworkStackOrSettingsPermission();
6581 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006582 case REQUEST:
6583 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6584 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006585 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006586 // TODO: this is incorrect. We mark the request as metered or not depending on
6587 // the state of the app when the request is filed, but we never change the
6588 // request if the app changes network state. http://b/29964605
6589 enforceMeteredApnPolicy(networkCapabilities);
6590 break;
junyulai1b1c8742021-03-12 20:05:08 +08006591 case LISTEN_FOR_BEST:
6592 enforceAccessPermission();
6593 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6594 break;
junyulaiad010792021-01-11 16:53:38 +08006595 default:
6596 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006597 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006598 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006599 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006600 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006601
junyulai1b1c8742021-03-12 20:05:08 +08006602 // Enforce FOREGROUND if the caller does not have permission to use background network.
6603 if (reqType == LISTEN_FOR_BEST) {
6604 restrictBackgroundRequestForCaller(networkCapabilities);
6605 }
6606
6607 // Set the UID range for this request to the single UID of the requester, unless the
6608 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006609 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6610 // are no visible methods to set the UIDs, an app could use reflection to try and get
6611 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006612 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006613 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6614 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006615
Etan Cohen85000162017-02-05 10:42:27 -08006616 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006617 throw new IllegalArgumentException("Bad timeout specified");
6618 }
Etan Cohen9786d922015-11-18 10:56:15 -08006619
James Mattis3ce3d3c2021-02-09 18:18:28 -08006620 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006621 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006622 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006623 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006624 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006625 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006626
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006627 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6628 // copied from the default request above. (This is necessary to ensure, for example, that
6629 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6630 // changes don't alter request matching.
6631 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6632 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006633 throw new IllegalStateException(
6634 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006635 + networkCapabilities + " vs. " + defaultNc);
6636 }
6637
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006638 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006639 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006640 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006641 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006642 }
6643 return networkRequest;
6644 }
6645
James Mattis3ce3d3c2021-02-09 18:18:28 -08006646 /**
6647 * Return the nri to be used when registering a network request. Specifically, this is used with
6648 * requests registered to track the default request. If there is currently a per-app default
6649 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6650 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006651 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6652 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006653 * @param nr the network request for the nri.
6654 * @param msgr the messenger for the nri.
6655 * @param binder the binder for the nri.
6656 * @param callingAttributionTag the calling attribution tag for the nri.
6657 * @return the nri to register.
6658 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006659 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006660 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006661 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006662 @Nullable String callingAttributionTag) {
6663 final List<NetworkRequest> requests;
6664 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6665 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006666 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006667 } else {
6668 requests = Collections.singletonList(nr);
6669 }
Roshan Pius951c0032020-12-22 15:10:42 -08006670 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006671 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006672 }
6673
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006674 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006675 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006676 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006677 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6678 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6679 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6680 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006681 }
junyulai96bd9fe2022-03-08 17:36:42 +08006682 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006683 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006684 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006685 }
6686 }
6687
fenglu3f357402015-03-20 11:29:56 -07006688 @Override
fenglub00f4882015-04-21 17:12:05 -07006689 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006690 enforceAccessPermission();
6691 NetworkAgentInfo nai = null;
6692 if (network == null) {
6693 return false;
6694 }
6695 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006696 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006697 }
6698 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006699 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006700 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006701 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006702 Integer uidReqs = mBandwidthRequests.get(uid);
6703 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006704 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006705 }
6706 mBandwidthRequests.put(uid, ++uidReqs);
6707 }
fenglu3f357402015-03-20 11:29:56 -07006708 return true;
6709 }
6710 return false;
6711 }
6712
Felipe Leme0a5ae422016-06-20 16:36:29 -07006713 private boolean isSystem(int uid) {
6714 return uid < Process.FIRST_APPLICATION_UID;
6715 }
fenglu3f357402015-03-20 11:29:56 -07006716
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006717 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006718 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006719 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006720 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006721 return;
6722 }
Hugo Benichi39621362017-02-11 17:04:43 +09006723 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6724 // Policy already enforced.
6725 return;
6726 }
paulhuaf50d7d2020-12-24 19:47:34 +08006727 final long ident = Binder.clearCallingIdentity();
6728 try {
6729 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6730 // If UID is restricted, don't allow them to bring up metered APNs.
6731 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6732 }
6733 } finally {
6734 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006735 }
6736 }
6737
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006738 @Override
6739 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006740 PendingIntent operation, @NonNull String callingPackageName,
6741 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006742 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006743 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006744 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006745 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006746 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006747 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006748 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006749 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006750 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006751 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6752 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006753
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006754 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006755 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006756 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6757 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006758 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006759 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6760 nri));
6761 return networkRequest;
6762 }
6763
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006764 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6765 mHandler.sendMessageDelayed(
6766 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006767 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006768 }
6769
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006770 @Override
6771 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006772 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006773 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006774 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006775 }
6776
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006777 // In order to implement the compatibility measure for pre-M apps that call
6778 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6779 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6780 // This ensures it has permission to do so.
6781 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6782 if (nc == null) {
6783 return false;
6784 }
6785 int[] transportTypes = nc.getTransportTypes();
6786 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6787 return false;
6788 }
6789 try {
6790 mContext.enforceCallingOrSelfPermission(
6791 android.Manifest.permission.ACCESS_WIFI_STATE,
6792 "ConnectivityService");
6793 } catch (SecurityException e) {
6794 return false;
6795 }
6796 return true;
6797 }
6798
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006799 @Override
6800 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006801 Messenger messenger, IBinder binder,
6802 @NetworkCallback.Flag int callbackFlags,
6803 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006804 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006805 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6806 enforceAccessPermission();
6807 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006808
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006809 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006810 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006811 Binder.getCallingPid(), callingUid, callingPackageName);
6812 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006813 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6814 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6815 // onLost and onAvailable callbacks when networks move in and out of the background.
6816 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6817 // can't request networks.
6818 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006819 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006820
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006821 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006822 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006823 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006824 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006825 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006826 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006827
6828 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6829 return networkRequest;
6830 }
6831
6832 @Override
6833 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006834 PendingIntent operation, @NonNull String callingPackageName,
6835 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006836 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006837 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006838 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6839 enforceAccessPermission();
6840 }
Chalard Jeandd421992021-12-16 23:16:02 +09006841 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006842 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006843 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006844 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006845 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006846
6847 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006848 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006849 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6850 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006851 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006852
WeiZhang1cc3f172021-06-03 19:02:04 -05006853 mHandler.sendMessage(mHandler.obtainMessage(
6854 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006855 }
6856
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006857 /** Returns the next Network provider ID. */
6858 public final int nextNetworkProviderId() {
6859 return mNextNetworkProviderId.getAndIncrement();
6860 }
6861
Erik Kline0c04b742016-07-07 16:50:58 +09006862 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006863 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006864 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006865 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006866 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006867 }
6868
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006869 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6870 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006871 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6872 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6873 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006874 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006875 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006876 return;
6877 }
6878
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006879 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6880 mNetworkProviderInfos.put(npi.messenger, npi);
6881 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006882 }
6883
6884 @Override
6885 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006886 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006887 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006888 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006889 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006890 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6891 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006892 }
6893
6894 @Override
6895 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006896 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006897 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006898 }
6899
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006900 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006901 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006902 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6903 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006904 Objects.requireNonNull(score);
6905 Objects.requireNonNull(caps);
6906 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006907 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006908 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006909 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6910 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006911 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6912 }
6913
Chalard Jeanbb902a52021-08-18 01:35:19 +09006914 private void updateOfferScore(final NetworkOffer offer) {
6915 final boolean yieldToBadWiFi =
6916 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6917 final NetworkOffer newOffer = new NetworkOffer(
6918 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6919 offer.caps, offer.callback, offer.providerId);
6920 if (offer.equals(newOffer)) return;
6921 handleRegisterNetworkOffer(newOffer);
6922 }
6923
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006924 @Override
6925 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006926 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006927 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6928 }
6929
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006930 private void handleUnregisterNetworkProvider(Messenger messenger) {
6931 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6932 if (npi == null) {
6933 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006934 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006935 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006936 // Unregister all the offers from this provider
6937 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6938 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006939 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006940 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6941 toRemove.add(noi);
6942 }
6943 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006944 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006945 handleUnregisterNetworkOffer(noi);
6946 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006947 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006948 }
6949
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006950 @Override
James Mattisf7027322020-12-13 16:28:14 -08006951 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006952 if (request.hasTransport(TRANSPORT_TEST)) {
6953 enforceNetworkFactoryOrTestNetworksPermission();
6954 } else {
6955 enforceNetworkFactoryPermission();
6956 }
James Mattisf7027322020-12-13 16:28:14 -08006957 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6958 if (nri != null) {
6959 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6960 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6961 mHandler.post(() -> handleReleaseNetworkRequest(
6962 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6963 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006964 }
6965
Paul Jensen1f567382015-02-13 14:18:39 -05006966 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6967 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006968 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006969 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006970 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006971 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006972 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006973
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006974 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006975 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006976 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006977
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006978 // UID ranges for users that are currently blocked by VPNs.
6979 // This array is accessed and iterated on multiple threads without holding locks, so its
6980 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6981 // (on the handler thread).
6982 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6983
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006984 // Must only be accessed on the handler thread
6985 @NonNull
6986 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6987
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006988 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006989 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006990
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006991 // Current OEM network preferences. This object must only be written to on the handler thread.
6992 // Since it is immutable and always non-null, other threads may read it if they only care
6993 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006994 @NonNull
6995 private OemNetworkPreferences mOemNetworkPreferences =
6996 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006997 // Current per-profile network preferences. This object follows the same threading rules as
6998 // the OEM network preferences above.
6999 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007000 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7001 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007002
paulhu51f77dc2021-06-07 02:34:20 +00007003 // A set of UIDs that should use mobile data preferentially if available. This object follows
7004 // the same threading rules as the OEM network preferences above.
7005 @NonNull
7006 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7007
James Mattiscb1e0362021-04-06 17:07:42 -07007008 // OemNetworkPreferences activity String log entries.
7009 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7010 @NonNull
7011 private final LocalLog mOemNetworkPreferencesLogs =
7012 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7013
James Mattis02220e22021-03-13 19:27:21 -08007014 /**
7015 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7016 * @param packageName the package name to check existence of a mapping for.
7017 * @return true if a mapping exists, false otherwise
7018 */
7019 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7020 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7021 }
7022
James Mattise3ef1912020-12-20 11:09:58 -08007023 // The always-on request for an Internet-capable network that apps without a specific default
7024 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007025 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007026 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007027 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007028 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007029 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007030 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007031 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007032
James Mattisd31bdfa2020-12-23 16:37:26 -08007033 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7034 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7035 }
7036
7037 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007038 * Return the default network request currently tracking the given uid.
7039 * @param uid the uid to check.
7040 * @return the NetworkRequestInfo tracking the given uid.
7041 */
7042 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007043 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007044 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007045 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007046 // Checking the first request is sufficient as only multilayer requests will have more
7047 // than one request and for multilayer, all requests will track the same uids.
7048 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007049 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007050 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007051 highestPriorityNri = nri;
7052 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007053 }
7054 }
paulhuaa0743d2021-05-26 21:56:03 +08007055 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007056 }
7057
7058 /**
7059 * Get a copy of the network requests of the default request that is currently tracking the
7060 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007061 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7062 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007063 * @param requestorUid the uid to check the default for.
7064 * @param requestorPackageName the requestor's package name.
7065 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7066 */
7067 @NonNull
7068 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007069 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007070 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007071 getDefaultRequestTrackingUid(asUid).mRequests,
7072 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007073 }
7074
7075 /**
7076 * Copy the given nri's NetworkRequest collection.
7077 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007078 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7079 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007080 * @param requestorUid the uid to set on the copied collection.
7081 * @param requestorPackageName the package name to set on the copied collection.
7082 * @return the copied NetworkRequest collection.
7083 */
7084 @NonNull
7085 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007086 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7087 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007088 final List<NetworkRequest> requests = new ArrayList<>();
7089 for (final NetworkRequest nr : requestsToCopy) {
7090 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007091 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007092 nr.legacyType, nextNetworkRequestId(), nr.type));
7093 }
7094 return requests;
7095 }
7096
7097 @NonNull
7098 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007099 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7100 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007101 // These capabilities are for a TRACK_DEFAULT callback, so:
7102 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7103 // mDefaultRequest and a per-UID default request.
7104 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007105 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007106 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007107 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7108 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007109 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007110 restrictRequestUidsForCallerAndSetRequestorInfo(
7111 netCap, requestorUid, requestorPackageName);
7112 return netCap;
7113 }
7114
7115 /**
7116 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7117 * @param nr the network request to check for equality against.
7118 * @return the nri if one exists, null otherwise.
7119 */
7120 @Nullable
7121 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7122 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7123 if (nri.getNetworkRequestForCallback().equals(nr)) {
7124 return nri;
7125 }
7126 }
7127 return null;
7128 }
7129
7130 /**
7131 * Check if an nri is currently being managed by per-app default networking.
7132 * @param nri the nri to check.
7133 * @return true if this nri is currently being managed by per-app default networking.
7134 */
7135 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7136 // nri.mRequests.get(0) is only different from the original request filed in
7137 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7138 // functionality therefore if these two don't match, it means this particular nri is
7139 // currently being managed by a per-app default.
7140 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7141 }
7142
7143 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007144 * Determine if an nri is a managed default request that disallows default networking.
7145 * @param nri the request to evaluate
7146 * @return true if device-default networking is disallowed
7147 */
7148 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7149 // Check if this nri is a managed default that supports the default network at its
7150 // lowest priority request.
7151 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7152 final NetworkCapabilities lowestPriorityNetCap =
7153 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7154 return isPerAppDefaultRequest(nri)
7155 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7156 lowestPriorityNetCap));
7157 }
7158
Erik Kline05f2b402015-04-30 12:58:40 +09007159 // Request used to optionally keep mobile data active even when higher
7160 // priority networks like Wi-Fi are active.
7161 private final NetworkRequest mDefaultMobileDataRequest;
7162
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007163 // Request used to optionally keep wifi data active even when higher
7164 // priority networks like ethernet are active.
7165 private final NetworkRequest mDefaultWifiRequest;
7166
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007167 // Request used to optionally keep vehicle internal network always active
7168 private final NetworkRequest mDefaultVehicleRequest;
7169
James Mattisd31bdfa2020-12-23 16:37:26 -08007170 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7171 // network with no service. This NAI should never be matched against, nor should any public API
7172 // ever return the associated network. For this reason, this NAI is not in the list of available
7173 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7174 // default requests that don't support using the device default network which will ultimately
7175 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7176 @VisibleForTesting
7177 final NetworkAgentInfo mNoServiceNetwork;
7178
Chalard Jean5b409c72021-02-04 13:12:59 +09007179 // The NetworkAgentInfo currently satisfying the default request, if any.
7180 private NetworkAgentInfo getDefaultNetwork() {
7181 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007182 }
7183
James Mattis2516da32021-01-31 17:06:19 -08007184 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007185 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007186 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7187 // Currently, all network requests will have the same uids therefore checking the first
7188 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007189 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007190 if (null == uids) {
7191 continue;
7192 }
7193 for (final UidRange range : uids) {
7194 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007195 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007196 highestPriorityNri = nri;
7197 }
James Mattis2516da32021-01-31 17:06:19 -08007198 }
7199 }
7200 }
paulhuaa0743d2021-05-26 21:56:03 +08007201 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007202 }
7203
Varun Ananddf569952019-02-06 10:13:38 -08007204 @Nullable
7205 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7206 return nai != null ? nai.network : null;
7207 }
7208
7209 private void ensureRunningOnConnectivityServiceThread() {
7210 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7211 throw new IllegalStateException(
7212 "Not running on ConnectivityService thread: "
7213 + Thread.currentThread().getName());
7214 }
7215 }
7216
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007217 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007218 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7219 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007220 }
7221
Chalard Jean29d06db2018-05-02 21:14:54 +09007222 /**
7223 * Register a new agent with ConnectivityService to handle a network.
7224 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007225 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007226 * @param networkInfo the initial info associated with this network. It can be updated later :
7227 * see {@link #updateNetworkInfo}.
7228 * @param linkProperties the initial link properties of this network. They can be updated
7229 * later : see {@link #updateLinkProperties}.
7230 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007231 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007232 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007233 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007234 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007235 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007236 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007237 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007238 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007239 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7240 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007241 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7242 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7243 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007244 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007245 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007246 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007247 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007248 } else {
7249 enforceNetworkFactoryPermission();
7250 }
7251
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007252 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007253 final long token = Binder.clearCallingIdentity();
7254 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007255 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007256 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007257 } finally {
7258 Binder.restoreCallingIdentity(token);
7259 }
7260 }
7261
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007262 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007263 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007264 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7265 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007266
Chalard Jeandbc46952022-02-02 00:14:18 +09007267 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7268 // and mutate them at any time.
7269 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7270 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7271 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7272
Chalard Jean366c5252022-01-25 18:27:53 +09007273 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007274 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007275 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7276 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007277 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007278 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007279 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007280 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7281 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007282
Chalard Jeandbc46952022-02-02 00:14:18 +09007283 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007284 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007285 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007286 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007287 mDeps.getNetworkStack().makeNetworkMonitor(
7288 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007289 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7290 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007291 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007292 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007293 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007294 }
7295
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007296 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007297 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007298 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007299 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007300 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007301 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7302 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7303 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007304
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007305 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007306
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007307 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007308 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007309 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007310 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007311
7312 try {
7313 networkMonitor.start();
7314 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007315 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007316 }
Chalard Jean366c5252022-01-25 18:27:53 +09007317
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007318 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007319 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007320 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007321 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007322 }
7323
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007324 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7325 @NonNull public final NetworkOffer offer;
7326
7327 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7328 this.offer = offer;
7329 }
7330
7331 @Override
7332 public void binderDied() {
7333 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7334 }
7335 }
7336
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007337 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7338 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7339 if (npi.providerId == providerId) return true;
7340 }
7341 return false;
7342 }
7343
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007344 /**
7345 * Register or update a network offer.
7346 * @param newOffer The new offer. If the callback member is the same as an existing
7347 * offer, it is an update of that offer.
7348 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007349 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007350 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7351 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007352 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007353 // This may actually happen if a provider updates its score or registers and then
7354 // immediately unregisters. The offer would still be in the handler queue, but the
7355 // provider would have been removed.
7356 if (DBG) log("Received offer from an unregistered provider");
7357 return;
7358 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007359 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7360 if (null != existingOffer) {
7361 handleUnregisterNetworkOffer(existingOffer);
7362 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007363 if (DBG) {
7364 // handleUnregisterNetworkOffer has already logged the old offer
7365 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7366 }
7367 } else {
7368 if (DBG) {
7369 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7370 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007371 }
7372 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7373 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007374 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007375 } catch (RemoteException e) {
7376 noi.binderDied();
7377 return;
7378 }
7379 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007380 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007381 }
7382
7383 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7384 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007385 if (DBG) {
7386 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7387 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007388
7389 // If the provider removes the offer and dies immediately afterwards this
7390 // function may be called twice in a row, but the array will no longer contain
7391 // the offer.
7392 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007393 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007394 }
7395
7396 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7397 @NonNull final INetworkOfferCallback callback) {
7398 ensureRunningOnConnectivityServiceThread();
7399 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007400 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007401 }
7402 return null;
7403 }
7404
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007405 /**
7406 * Called when receiving LinkProperties directly from a NetworkAgent.
7407 * Stores into |nai| any data coming from the agent that might also be written to the network's
7408 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7409 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007410 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007411 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007412 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7413 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007414 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007415 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007416 }
7417
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007418 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007419 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007420 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007421
Lorenzo Colittid523d142020-04-01 20:16:30 +09007422 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7423 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7424 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007425 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007426
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007427 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007428
7429 // update filtering rules, need to happen after the interface update so netd knows about the
7430 // new interface (the interface name -> index map becomes initialized)
7431 updateVpnFiltering(newLp, oldLp, networkAgent);
7432
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007433 updateMtu(newLp, oldLp);
7434 // TODO - figure out what to do for clat
7435// for (LinkProperties lp : newLp.getStackedLinks()) {
7436// updateMtu(lp, null);
7437// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007438 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007439 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7440 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007441
Erik Klineb9888902016-04-05 13:30:49 +09007442 updateRoutes(newLp, oldLp, netId);
7443 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007444 // Make sure LinkProperties represents the latest private DNS status.
7445 // This does not need to be done before updateDnses because the
7446 // LinkProperties are not the source of the private DNS configuration.
7447 // updateDnses will fetch the private DNS configuration from DnsManager.
7448 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007449
Chalard Jean5b409c72021-02-04 13:12:59 +09007450 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007451 handleApplyDefaultProxy(newLp.getHttpProxy());
7452 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007453 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007454 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007455
7456 updateWakeOnLan(newLp);
7457
Hai Shalome58bdc62021-01-11 18:45:34 -08007458 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7459 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7460 // does, it needs to be merged here.
7461 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7462 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007463
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007464 // TODO - move this check to cover the whole function
7465 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007466 synchronized (networkAgent) {
7467 networkAgent.linkProperties = newLp;
7468 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007469 // Start or stop DNS64 detection and 464xlat according to network state.
7470 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007471 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007472 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7473 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007474 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007475 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007476
7477 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007478 }
7479
Hai Shalome58bdc62021-01-11 18:45:34 -08007480 /**
7481 * @param naData captive portal data from NetworkAgent
7482 * @param apiData captive portal data from capport API
7483 */
7484 @Nullable
7485 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7486 CaptivePortalData apiData) {
7487 if (naData == null || apiData == null) {
7488 return naData == null ? apiData : naData;
7489 }
7490 final CaptivePortalData.Builder captivePortalBuilder =
7491 new CaptivePortalData.Builder(naData);
7492
7493 if (apiData.isCaptive()) {
7494 captivePortalBuilder.setCaptive(true);
7495 }
7496 if (apiData.isSessionExtendable()) {
7497 captivePortalBuilder.setSessionExtendable(true);
7498 }
7499 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7500 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7501 // otherwise data would be inconsistent. Prefer the capport API info if present,
7502 // as it can generally be refreshed more often.
7503 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7504 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7505 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7506 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7507 // No source has time / bytes remaining information: surface the newest refresh time
7508 // for other fields
7509 captivePortalBuilder.setRefreshTime(
7510 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7511 }
7512
Hai Shalom7c6ab402021-02-04 19:34:06 -08007513 // Prioritize the user portal URL from the network agent if the source is authenticated.
7514 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7515 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7516 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7517 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007518 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007519 // Prioritize the venue information URL from the network agent if the source is
7520 // authenticated.
7521 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7522 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7523 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7524 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007525 }
7526 return captivePortalBuilder.build();
7527 }
7528
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007529 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007530 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007531 // marks on unsupported interfaces is harmless.
7532 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7533 return;
7534 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007535
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007536 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7537 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7538
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007539 // Mask/mark of zero will not detect anything interesting.
7540 // Don't install rules unless both values are nonzero.
7541 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007542 return;
7543 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007544
7545 final String prefix = "iface:" + iface;
7546 try {
7547 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007548 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007549 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007550 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007551 }
7552 } catch (Exception e) {
7553 loge("Exception modifying wakeup packet monitoring: " + e);
7554 }
7555
Joel Scherpelza235a812017-05-22 13:47:41 +09007556 }
7557
Chalard Jean9589e722019-11-19 19:03:53 +09007558 private void updateInterfaces(final @Nullable LinkProperties newLp,
7559 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007560 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007561 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007562 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7563 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007564 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007565 for (final String iface : interfaceDiff.added) {
7566 try {
7567 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007568 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007569 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007570 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7571 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007572 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007573 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007574 }
Paul Jensenbff73492014-04-28 10:33:11 -04007575 }
7576 }
Chalard Jean9589e722019-11-19 19:03:53 +09007577 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007578 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007579 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007580 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007581 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007582 } catch (Exception e) {
7583 loge("Exception removing interface: " + e);
7584 }
7585 }
7586 }
7587
Tyler Weare4314862019-12-05 14:55:30 -08007588 // TODO: move to frameworks/libs/net.
7589 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7590 final String nextHop;
7591
7592 switch (route.getType()) {
7593 case RouteInfo.RTN_UNICAST:
7594 if (route.hasGateway()) {
7595 nextHop = route.getGateway().getHostAddress();
7596 } else {
7597 nextHop = INetd.NEXTHOP_NONE;
7598 }
7599 break;
7600 case RouteInfo.RTN_UNREACHABLE:
7601 nextHop = INetd.NEXTHOP_UNREACHABLE;
7602 break;
7603 case RouteInfo.RTN_THROW:
7604 nextHop = INetd.NEXTHOP_THROW;
7605 break;
7606 default:
7607 nextHop = INetd.NEXTHOP_NONE;
7608 break;
7609 }
7610
7611 final RouteInfoParcel rip = new RouteInfoParcel();
7612 rip.ifName = route.getInterface();
7613 rip.destination = route.getDestination().toString();
7614 rip.nextHop = nextHop;
7615 rip.mtu = route.getMtu();
7616
7617 return rip;
7618 }
7619
Paul Jensene0fd4a82014-08-06 15:51:33 -04007620 /**
7621 * Have netd update routes from oldLp to newLp.
7622 * @return true if routes changed between oldLp and newLp
7623 */
7624 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007625 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007626 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7627 new CompareOrUpdateResult<>(
7628 oldLp != null ? oldLp.getAllRoutes() : null,
7629 newLp != null ? newLp.getAllRoutes() : null,
7630 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007631
7632 // add routes before removing old in case it helps with continuous connectivity
7633
Chalard Jean9dd11612018-06-04 16:52:49 +09007634 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007635 for (RouteInfo route : routeDiff.added) {
7636 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007637 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007638 try {
Tyler Weare4314862019-12-05 14:55:30 -08007639 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007640 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007641 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007642 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007643 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007644 }
7645 }
7646 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007647 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007648 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007649 try {
Tyler Weare4314862019-12-05 14:55:30 -08007650 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007651 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007652 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007653 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007654 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007655 }
7656 }
7657
7658 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007659 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007660 try {
Tyler Weare4314862019-12-05 14:55:30 -08007661 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007662 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007663 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007664 }
7665 }
Tyler Weare4314862019-12-05 14:55:30 -08007666
7667 for (RouteInfo route : routeDiff.updated) {
7668 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7669 try {
7670 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7671 } catch (Exception e) {
7672 loge("Exception in networkUpdateRouteParcel: " + e);
7673 }
7674 }
7675 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7676 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007677 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007678
Erik Klineb9888902016-04-05 13:30:49 +09007679 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7680 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7681 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007682 }
Erik Klineb9888902016-04-05 13:30:49 +09007683
Erik Kline31b4a9e2018-01-11 21:07:29 +09007684 if (DBG) {
7685 final Collection<InetAddress> dnses = newLp.getDnsServers();
7686 log("Setting DNS servers for network " + netId + " to " + dnses);
7687 }
Erik Klineb9888902016-04-05 13:30:49 +09007688 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007689 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007690 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007691 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007692 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007693 }
Erik Kline54e35c02017-04-07 15:29:29 +09007694 }
7695
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007696 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7697 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007698 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7699 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007700 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7701 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007702
7703 if (!wasFiltering && !needsFiltering) {
7704 // Nothing to do.
7705 return;
7706 }
7707
7708 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7709 // Nothing changed.
7710 return;
7711 }
7712
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007713 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007714 if (ranges == null || ranges.isEmpty()) {
7715 return;
7716 }
7717
Qingxi Libb8da982020-01-17 17:54:27 -08007718 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007719 // TODO: this create a window of opportunity for apps to receive traffic between the time
7720 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007721 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007722 // old rules are being removed.
7723 if (wasFiltering) {
7724 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7725 }
7726 if (needsFiltering) {
7727 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7728 }
7729 }
7730
Valentin Iftime9fa35092019-09-24 13:32:13 +02007731 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007732 if (mWolSupportedInterfaces == null) {
7733 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007734 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007735 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007736 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7737 }
7738
Luke Huangb913c812018-08-24 20:33:16 +08007739 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007740 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007741 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007742 }
7743 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007744 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007745 }
Luke Huangb913c812018-08-24 20:33:16 +08007746 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007747 }
7748
Chalard Jean62edfd82019-12-02 18:39:29 +09007749 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7750 @NonNull final NetworkCapabilities newNc) {
7751 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7752 final int newPermission = getNetworkPermission(newNc);
7753 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7754 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007755 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007756 } catch (RemoteException | ServiceSpecificException e) {
7757 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007758 }
7759 }
7760 }
7761
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007762 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007763 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007764 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007765 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007766 underlyingNetworks = underlyingNetworksOrDefault(
7767 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007768 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007769 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7770 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007771 // metered if any underlying is metered, or originally declared metered by the agent.
7772 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007773 boolean roaming = false; // roaming if any underlying is roaming
7774 boolean congested = false; // congested if any underlying is congested
7775 boolean suspended = true; // suspended if all underlying are suspended
7776
7777 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007778 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007779 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007780 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007781 for (Network underlyingNetwork : underlyingNetworks) {
7782 final NetworkAgentInfo underlying =
7783 getNetworkAgentInfoForNetwork(underlyingNetwork);
7784 if (underlying == null) continue;
7785
7786 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7787 hadUnderlyingNetworks = true;
7788 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007789 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007790 }
7791
7792 // Merge capabilities of this underlying network. For bandwidth, assume the
7793 // worst case.
7794 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7795 underlyingCaps.getLinkDownstreamBandwidthKbps());
7796 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7797 underlyingCaps.getLinkUpstreamBandwidthKbps());
7798 // If this underlying network is metered, the VPN is metered (it may cost money
7799 // to send packets on this network).
7800 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7801 // If this underlying network is roaming, the VPN is roaming (the billing structure
7802 // is different than the usual, local one).
7803 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7804 // If this underlying network is congested, the VPN is congested (the current
7805 // condition of the network affects the performance of this network).
7806 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7807 // If this network is not suspended, the VPN is not suspended (the VPN
7808 // is able to transfer some data).
7809 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007810 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007811 }
7812 }
7813 if (!hadUnderlyingNetworks) {
7814 // No idea what the underlying networks are; assume reasonable defaults
7815 metered = true;
7816 roaming = false;
7817 congested = false;
7818 suspended = false;
7819 }
7820
lifrade6c2a2021-03-04 14:08:08 +08007821 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007822 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7823 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7824 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7825 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7826 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7827 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007828 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007829 }
7830
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007831 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007832 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7833 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7834 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007835 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007836 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007837 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007838 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007839 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7840 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007841 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007842 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007843 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007844 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007845 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7846 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007847 // does not cause any request (that is not a listen) currently matching that agent to
7848 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007849 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007850 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007851 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007852 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007853 }
7854
Paul Jensen53f08952015-06-16 14:27:36 -04007855 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007856 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007857 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007858 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007859 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007860 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007861 }
Paul Jensende49eb12015-06-25 15:30:08 -04007862 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007863 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007864 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007865 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007866 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007867 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007868 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007869 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007870 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007871 }
lucaslin2240ef62019-03-12 13:08:03 +08007872 if (nai.partialConnectivity) {
7873 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7874 } else {
7875 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7876 }
lucasline117e2e2019-10-22 18:27:33 +08007877 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007878
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007879 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007880 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7881 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007882 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007883 }
7884
Lorenzo Colittibd079452021-07-02 11:47:57 +09007885 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007886 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007887 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007888 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007889 }
7890
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007891 return newNc;
7892 }
7893
Lorenzo Colitti44840702021-01-11 22:27:57 +09007894 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7895 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7896 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7897 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7898 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7899 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7900 if (prevSuspended != suspended) {
7901 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7902 // onResumed have been removed.
7903 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7904 : ConnectivityManager.CALLBACK_RESUMED);
7905 }
7906 if (prevSuspended != suspended || prevRoaming != roaming) {
7907 // updateNetworkInfo will mix in the suspended info from the capabilities and
7908 // take appropriate action for the network having possibly changed state.
7909 updateNetworkInfo(nai, nai.networkInfo);
7910 }
7911 }
7912
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007913 /**
7914 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7915 *
7916 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7917 * capabilities we manage and store in {@code nai}, such as validated status and captive
7918 * portal status)
7919 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7920 * potentially triggers rematches.
7921 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7922 * change.)
7923 *
7924 * @param oldScore score of the network before any of the changes that prompted us
7925 * to call this function.
7926 * @param nai the network having its capabilities updated.
7927 * @param nc the new network capabilities.
7928 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007929 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007930 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007931 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007932 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007933 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007934 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007935
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007936 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09007937 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007938 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007939
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007940 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007941 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7942 // the change we're processing can't affect any requests, it can only affect the listens
7943 // on this network. We might have been called by rematchNetworkAndRequests when a
7944 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007945 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007946 } else {
7947 // If the requestable capabilities have changed or the score changed, we can't have been
7948 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007949 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007950 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007951 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007952 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007953
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007954 final boolean oldMetered = prevNc.isMetered();
7955 final boolean newMetered = newNc.isMetered();
7956 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007957
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007958 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007959 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7960 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007961 }
junyulaif2c67e42018-08-07 19:50:45 +08007962
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007963 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7964 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007965
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007966 // Report changes that are interesting for network statistics tracking.
7967 if (meteredChanged || roamingChanged) {
7968 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007969 }
7970
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007971 // This network might have been underlying another network. Propagate its capabilities.
7972 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007973
7974 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007975 mDnsManager.updateTransportsForNetwork(
7976 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007977 }
lucaslin53e8a262021-06-08 01:43:59 +08007978
7979 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007980 }
7981
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007982 /** Convenience method to update the capabilities for a given network. */
7983 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007984 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007985 }
7986
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007987 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00007988 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007989 *
7990 * Ingress interface filtering enforces that all apps under the given network can only receive
7991 * packets from the network's interface (and loopback). This is important for VPNs because
7992 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7993 * non-VPN interfaces.
7994 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00007995 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007996 * 1. the network is an app VPN (not legacy VPN)
7997 * 2. the VPN does not allow bypass
7998 * 3. the VPN is fully-routed
7999 * 4. the VPN interface is non-null
8000 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008001 * @see INetd#firewallAddUidInterfaceRules
8002 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008003 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008004 @Nullable
8005 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008006 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008007 if (nc == null || lp == null) return null;
8008 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008009 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008010 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008011 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008012 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008013 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008014 && !lp.hasExcludeRoute()) {
8015 return lp.getInterfaceName();
8016 }
8017 return null;
8018 }
8019
8020 /**
8021 * Returns whether we need to set interface filtering rule or not
8022 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008023 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008024 String isolationIface) {
8025 // Allow rules are always needed if VPN isolation is enabled.
8026 if (isolationIface != null) return true;
8027
8028 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8029 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8030 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8031 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008032 }
8033
Chiachang Wang28afaff2020-12-10 22:24:47 +08008034 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8035 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8036 int index = 0;
8037 for (UidRange range : ranges) {
8038 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8039 index++;
8040 }
8041 return stableRanges;
8042 }
8043
Chalard Jeane6c95272022-01-25 21:04:21 +09008044 private static UidRangeParcel[] intsToUidRangeStableParcels(
8045 final @NonNull ArraySet<Integer> uids) {
8046 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8047 int index = 0;
8048 for (int uid : uids) {
8049 stableRanges[index] = new UidRangeParcel(uid, uid);
8050 index++;
8051 }
8052 return stableRanges;
8053 }
8054
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008055 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8056 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8057 for (int i = 0; i < ranges.length; i++) {
8058 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8059 }
8060 return stableRanges;
8061 }
8062
Ken Chen5e65a852020-12-24 12:59:10 +08008063 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8064 int[] exemptUids) {
8065 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8066 try {
8067 mNetd.socketDestroy(ranges, exemptUids);
8068 } catch (Exception e) {
8069 loge("Exception in socket destroy: ", e);
8070 }
8071 }
8072 }
8073
paulhuaa0743d2021-05-26 21:56:03 +08008074 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008075 int[] exemptUids = new int[2];
8076 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8077 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8078 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8079 exemptUids[0] = VPN_UID;
8080 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8081 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8082
8083 maybeCloseSockets(nai, ranges, exemptUids);
8084 try {
8085 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008086 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008087 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008088 } else {
paulhu0e79d952021-06-09 16:11:35 +08008089 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008090 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008091 }
8092 } catch (Exception e) {
8093 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8094 " on netId " + nai.network.netId + ". " + e);
8095 }
8096 maybeCloseSockets(nai, ranges, exemptUids);
8097 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008098
lucaslin53e8a262021-06-08 01:43:59 +08008099 private boolean isProxySetOnAnyDefaultNetwork() {
8100 ensureRunningOnConnectivityServiceThread();
8101 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8102 final NetworkAgentInfo nai = nri.getSatisfier();
8103 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8104 return true;
8105 }
8106 }
8107 return false;
8108 }
8109
8110 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8111 NetworkCapabilities newNc) {
8112 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8113 // the proxy might be changed since the default network satisfied by the apps might also
8114 // changed.
8115 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8116 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008117 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8118 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
8119 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008120 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8121 mProxyTracker.sendProxyBroadcast();
8122 }
8123 }
8124
Chalard Jeane6c95272022-01-25 21:04:21 +09008125 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8126 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008127 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8128 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008129 if (null == prevRanges) prevRanges = new ArraySet<>();
8130 if (null == newRanges) newRanges = new ArraySet<>();
8131 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8132
8133 prevRanges.removeAll(newRanges);
8134 newRanges.removeAll(prevRangesCopy);
8135
8136 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008137 // When updating the VPN uid routing rules, add the new range first then remove the old
8138 // range. If old range were removed first, there would be a window between the old
8139 // range being removed and the new range being added, during which UIDs contained
8140 // in both ranges are not subject to any VPN routing rules. Adding new range before
8141 // removing old range works because, unlike the filtering rules below, it's possible to
8142 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008143 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8144 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8145 // [1-5] & [1-2],[4-5] == [3]
8146 // Then we can do:
8147 // maybeCloseSockets([3])
8148 // mNetd.networkAddUidRanges([1-2],[4-5])
8149 // mNetd.networkRemoveUidRanges([1-5])
8150 // maybeCloseSockets([3])
8151 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8152 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008153 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008154 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008155 }
8156 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008157 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008158 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008159 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8160 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008161 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8162 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008163 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008164 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008165 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8166 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8167 // were added first and then newRanges got removed later, there would be only one uid
8168 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8169 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8170 // Note that this is in contrast with the (more robust) update of VPN routing rules
8171 // above, where the addition of new ranges happens before the removal of old ranges.
8172 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8173 // to be removed will never overlap with the new range to be added.
8174 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008175 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8176 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008177 }
8178 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008179 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008180 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008181 } catch (Exception e) {
8182 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008183 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008184 }
8185 }
8186
Chalard Jeande665262022-02-25 16:12:12 +09008187 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008188 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8189 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008190 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8191 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008192 if (prevEmpty && newEmpty) return;
8193
8194 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008195 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008196 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008197 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008198
8199 if (prevUids.equals(newUids)) return;
8200
8201 // This implementation is very simple and vastly faster for sets of Integers than
8202 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8203 // a key computed from the value and has storage for that.
8204 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8205 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8206 toRemove.removeAll(newUids);
8207 toAdd.removeAll(prevUids);
8208
8209 try {
8210 if (!toAdd.isEmpty()) {
8211 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8212 nai.network.netId,
8213 intsToUidRangeStableParcels(toAdd),
8214 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8215 }
8216 if (!toRemove.isEmpty()) {
8217 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8218 nai.network.netId,
8219 intsToUidRangeStableParcels(toRemove),
8220 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8221 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008222 } catch (ServiceSpecificException e) {
8223 // Has the interface disappeared since the network was built ?
8224 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008225 } catch (RemoteException e) {
8226 // Netd died. This usually causes a runtime restart anyway.
8227 }
8228 }
8229
Hugo Benichi9d35b752017-09-01 01:23:32 +00008230 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008231 ensureRunningOnConnectivityServiceThread();
8232
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008233 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008234 // Ignore updates for disconnected networks
8235 return;
8236 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008237 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008238 log("Update of LinkProperties for " + nai.toShortString()
8239 + "; created=" + nai.created
8240 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00008241 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008242 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8243 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008244 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008245 }
8246
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008247 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8248 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008249 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008250 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008251 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008252 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8253 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8254 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008255 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8256 // need to be sent as a separate extra.
8257 final NetworkRequest req = nri.isMultilayerRequest()
8258 ? nri.getActiveRequest()
8259 // Non-multilayer listen requests do not have an active request
8260 : nri.mRequests.get(0);
8261 if (req == null) {
8262 Log.wtf(TAG, "No request in NRI " + nri);
8263 }
8264 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008265 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008266 sendIntent(nri.mPendingIntent, intent);
8267 }
8268 // else not handled
8269 }
8270
8271 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8272 mPendingIntentWakeLock.acquire();
8273 try {
8274 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008275 final BroadcastOptions options = BroadcastOptions.makeBasic();
8276 if (SdkLevel.isAtLeastT()) {
8277 // Explicitly disallow the receiver from starting activities, to prevent apps from
8278 // utilizing the PendingIntent as a backdoor to do this.
8279 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8280 }
8281 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8282 null /* requiredPermission */,
8283 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008284 } catch (PendingIntent.CanceledException e) {
8285 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8286 mPendingIntentWakeLock.release();
8287 releasePendingNetworkRequest(pendingIntent);
8288 }
8289 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8290 }
8291
8292 @Override
8293 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8294 String resultData, Bundle resultExtras) {
8295 if (DBG) log("Finished sending " + pendingIntent);
8296 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008297 // Release with a delay so the receiving client has an opportunity to put in its
8298 // own request.
8299 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008300 }
8301
Chalard Jean46bfbf02022-02-02 00:56:25 +09008302 // networkAgent is only allowed to be null if notificationType is
8303 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8304 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008305 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008306 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008307 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008308 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008309 // Default request has no msgr. Also prevents callbacks from being invoked for
8310 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8311 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8312 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008313 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008314 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008315 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008316 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008317 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008318 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008319 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008320 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8321 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008322 }
Roshan Pius951c0032020-12-22 15:10:42 -08008323 final boolean includeLocationSensitiveInfo =
8324 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008325 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008326 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008327 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008328 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008329 networkCapabilitiesRestrictedForCallerPermissions(
8330 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8331 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008332 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008333 nri.mCallingAttributionTag);
8334 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008335 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8336 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008337 // For this notification, arg1 contains the blocked status.
8338 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008339 break;
8340 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008341 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008342 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008343 break;
8344 }
8345 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008346 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008347 final NetworkCapabilities netCap =
8348 networkCapabilitiesRestrictedForCallerPermissions(
8349 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8350 putParcelable(
8351 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008352 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008353 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008354 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008355 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008356 break;
8357 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008358 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008359 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8360 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008361 break;
8362 }
junyulaif2c67e42018-08-07 19:50:45 +08008363 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008364 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008365 msg.arg1 = arg1;
8366 break;
8367 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008368 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008369 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008370 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008371 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008372 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008373 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008374 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008375 }
James Mattis45d81842021-01-10 14:24:24 -08008376 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008377 } catch (RemoteException e) {
8378 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008379 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008380 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008381 }
8382
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008383 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8384 bundle.putParcelable(t.getClass().getSimpleName(), t);
8385 }
8386
Chalard Jean0702f982021-09-16 21:50:07 +09008387 /**
8388 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8389 *
8390 * When a request should be assigned to a new network, it is normally lingered to give
8391 * time for apps to gracefully migrate their connections. When both networks are on the same
8392 * radio, but that radio can't do time-sharing efficiently, this may end up being
8393 * counter-productive because any traffic on the old network may drastically reduce the
8394 * performance of the new network.
8395 * The stack supports a configuration to let modem vendors state that their radio can't
8396 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8397 * from one cell network to another can't be done gracefully.
8398 *
8399 * @param oldNai the old network serving the request
8400 * @param newNai the new network serving the request
8401 * @return whether the switch can be graceful
8402 */
8403 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8404 @NonNull final NetworkAgentInfo newSatisfier) {
8405 if (mCellularRadioTimesharingCapable) return true;
8406 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8407 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8408 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8409 }
8410
Paul Jensenaf94b982014-09-30 15:37:41 -04008411 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008412 if (nai.numRequestNetworkRequests() != 0) {
8413 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8414 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008415 // Ignore listening and track default requests.
8416 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008417 loge("Dead network still had at least " + nr);
8418 break;
8419 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008420 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008421 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008422 }
8423
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008424 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8425 if (oldNetwork == null) {
8426 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8427 return;
8428 }
Chalard Jean49707572019-12-10 21:07:02 +09008429 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008430
8431 // If we get here it means that the last linger timeout for this network expired. So there
8432 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008433 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008434
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008435 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008436 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008437 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008438 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008439 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008440 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008441 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008442 }
8443
James Mattise3ef1912020-12-20 11:09:58 -08008444 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8445 boolean isDefaultChanged = false;
8446 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8447 final NetworkReassignment.RequestReassignment reassignment =
8448 changes.getReassignment(defaultRequestInfo);
8449 if (null == reassignment) {
8450 continue;
8451 }
8452 // reassignment only contains those instances where the satisfying network changed.
8453 isDefaultChanged = true;
8454 // Notify system services of the new default.
8455 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8456 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008457
James Mattise3ef1912020-12-20 11:09:58 -08008458 if (isDefaultChanged) {
8459 // Hold a wakelock for a short time to help apps in migrating to a new default.
8460 scheduleReleaseNetworkTransitionWakelock();
8461 }
8462 }
8463
8464 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8465 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8466 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8467 if (DBG) {
8468 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8469 }
Chalard Jean8e382112019-12-03 20:45:30 +09008470
James Mattisd31bdfa2020-12-23 16:37:26 -08008471 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8472 if (newDefaultNetwork != null) {
8473 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008474 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008475
James Mattisd31bdfa2020-12-23 16:37:26 -08008476 // Set an app level managed default and return since further processing only applies to the
8477 // default network.
8478 if (mDefaultRequest != nri) {
8479 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8480 return;
8481 }
8482
8483 makeDefaultNetwork(newDefaultNetwork);
8484
James Mattise3ef1912020-12-20 11:09:58 -08008485 if (oldDefaultNetwork != null) {
8486 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8487 }
8488 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008489 handleApplyDefaultProxy(null != newDefaultNetwork
8490 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8491 updateTcpBufferSizes(null != newDefaultNetwork
8492 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008493 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008494 }
8495
James Mattisd31bdfa2020-12-23 16:37:26 -08008496 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8497 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8498 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8499 try {
8500 if (VDBG) {
8501 log("Setting default network for " + nri
8502 + " using UIDs " + nri.getUids()
8503 + " with old network " + (oldDefaultNetwork != null
8504 ? oldDefaultNetwork.network().getNetId() : "null")
8505 + " and new network " + (newDefaultNetwork != null
8506 ? newDefaultNetwork.network().getNetId() : "null"));
8507 }
8508 if (nri.getUids().isEmpty()) {
8509 throw new IllegalStateException("makeDefaultForApps called without specifying"
8510 + " any applications to set as the default." + nri);
8511 }
8512 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008513 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008514 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008515 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008516 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008517 }
8518 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008519 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008520 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008521 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008522 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008523 }
8524 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008525 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008526 }
8527 }
8528
8529 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8530 try {
8531 if (null != newDefaultNetwork) {
8532 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8533 } else {
8534 mNetd.networkClearDefault();
8535 }
8536 } catch (RemoteException | ServiceSpecificException e) {
8537 loge("Exception setting default network :" + e);
8538 }
8539 }
8540
Chalard Jean05cbe972019-12-09 11:50:38 +09008541 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008542 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008543 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008544 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008545 processNewlySatisfiedListenRequests(nai);
8546 }
8547
8548 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008549 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8550 if (nri.isMultilayerRequest()) {
8551 continue;
8552 }
8553 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008554 if (!nr.isListen()) continue;
8555 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008556 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008557 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8558 }
8559 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008560 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008561
Chalard Jeancd397a22019-11-22 22:33:33 +09008562 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008563 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8564 if (nri.isMultilayerRequest()) {
8565 continue;
8566 }
8567 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008568 if (!nr.isListen()) continue;
8569 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8570 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008571 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008572 }
8573 }
8574 }
8575
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008576 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008577 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008578 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008579 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008580 @Nullable public final NetworkRequest mOldNetworkRequest;
8581 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008582 @Nullable public final NetworkAgentInfo mOldNetwork;
8583 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008584 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008585 @Nullable final NetworkRequest oldNetworkRequest,
8586 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008587 @Nullable final NetworkAgentInfo oldNetwork,
8588 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008589 mNetworkRequestInfo = networkRequestInfo;
8590 mOldNetworkRequest = oldNetworkRequest;
8591 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008592 mOldNetwork = oldNetwork;
8593 mNewNetwork = newNetwork;
8594 }
Chalard Jean49707572019-12-10 21:07:02 +09008595
8596 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008597 final NetworkRequest requestToShow = null != mNewNetworkRequest
8598 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8599 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008600 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8601 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008602 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008603 }
8604
Chalard Jean46a62372019-12-10 21:25:24 +09008605 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008606
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008607 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008608 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008609 }
8610
8611 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008612 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008613 // The code is never supposed to add two reassignments of the same request. Make
8614 // sure this stays true, but without imposing this expensive check on all
8615 // reassignments on all user devices.
8616 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008617 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008618 throw new IllegalStateException("Trying to reassign ["
8619 + reassignment + "] but already have ["
8620 + existing + "]");
8621 }
8622 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008623 }
Chalard Jean46a62372019-12-10 21:25:24 +09008624 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008625 }
8626
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008627 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008628 // the passed request.
8629 @Nullable
8630 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008631 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008632 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008633 }
8634 return null;
8635 }
Chalard Jean49707572019-12-10 21:07:02 +09008636
8637 public String toString() {
8638 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8639 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008640 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008641 for (final RequestReassignment rr : getRequestReassignments()) {
8642 sj.add(rr.toString());
8643 }
8644 return sj.toString();
8645 }
8646
8647 public String debugString() {
8648 final StringBuilder sb = new StringBuilder();
8649 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008650 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008651 for (final RequestReassignment rr : getRequestReassignments()) {
8652 sb.append("\n ").append(rr);
8653 }
8654 return sb.append("\n").toString();
8655 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008656 }
8657
Chalard Jean24344d72019-12-04 13:32:31 +09008658 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008659 @Nullable final NetworkRequest previousRequest,
8660 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008661 @Nullable final NetworkAgentInfo previousSatisfier,
8662 @Nullable final NetworkAgentInfo newSatisfier,
8663 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008664 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008665 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008666 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008667 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008668 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008669 }
James Mattisa076c532020-12-02 14:12:41 -08008670 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008671 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
8672 && !previousSatisfier.destroyed) {
Chalard Jean0702f982021-09-16 21:50:07 +09008673 // If this network switch can't be supported gracefully, the request is not
8674 // lingered. This allows letting go of the network sooner to reclaim some
8675 // performance on the new network, since the radio can't do both at the same
8676 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008677 //
8678 // Also don't linger the request if the old network has been destroyed.
8679 // A destroyed network does not provide actual network connectivity, so
8680 // lingering it is not useful. In particular this ensures that a destroyed
8681 // network is outscored by its replacement,
8682 // then it is torn down immediately instead of being lingered, and any apps that
8683 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008684 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8685 }
Chalard Jean24344d72019-12-04 13:32:31 +09008686 } else {
8687 if (VDBG || DDBG) log(" accepting network in place of null");
8688 }
junyulai0ac374f2020-12-14 18:41:52 +08008689
8690 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8691 // and immediately satisfies a request then remove the timer. This will happen for
8692 // all networks except in the case of an underlying network for a VCN.
8693 if (newSatisfier.isNascent()) {
8694 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008695 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008696 }
8697
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008698 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008699 newSatisfier.unlingerRequest(newRequest.requestId);
8700 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008701 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008702 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008703 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008704 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008705 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008706 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008707 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008708 }
James Mattisa076c532020-12-02 14:12:41 -08008709 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008710 }
James Mattisa076c532020-12-02 14:12:41 -08008711 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008712 }
8713
James Mattisa076c532020-12-02 14:12:41 -08008714 /**
8715 * This function is triggered when something can affect what network should satisfy what
8716 * request, and it computes the network reassignment from the passed collection of requests to
8717 * network match to the one that the system should now have. That data is encoded in an
8718 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8719 * satisfier.
8720 *
8721 * After the reassignment is computed, it is applied to the state objects.
8722 *
8723 * @param networkRequests the nri objects to evaluate for possible network reassignment
8724 * @return NetworkReassignment listing of proposed network assignment changes
8725 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008726 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008727 private NetworkReassignment computeNetworkReassignment(
8728 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008729 final NetworkReassignment changes = new NetworkReassignment();
8730
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008731 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008732 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008733 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008734 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008735 }
Chalard Jean857a1712019-12-10 21:08:07 +09008736
James Mattisa076c532020-12-02 14:12:41 -08008737 for (final NetworkRequestInfo nri : networkRequests) {
8738 // Non-multilayer listen requests can be ignored.
8739 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8740 continue;
8741 }
8742 NetworkAgentInfo bestNetwork = null;
8743 NetworkRequest bestRequest = null;
8744 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008745 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008746 // Stop evaluating as the highest possible priority request is satisfied.
8747 if (null != bestNetwork) {
8748 bestRequest = req;
8749 break;
8750 }
8751 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008752 if (null == bestNetwork && isDefaultBlocked(nri)) {
8753 // Remove default networking if disallowed for managed default requests.
8754 bestNetwork = mNoServiceNetwork;
8755 }
8756 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008757 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008758 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008759 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008760 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008761 }
8762 return changes;
8763 }
8764
James Mattisa076c532020-12-02 14:12:41 -08008765 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8766 return new HashSet<>(mNetworkRequests.values());
8767 }
8768
Paul Jensenc88b39b2015-06-16 14:27:36 -04008769 /**
James Mattisa076c532020-12-02 14:12:41 -08008770 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008771 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008772 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008773 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008774 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8775 }
8776
8777 /**
8778 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8779 * being disconnected.
8780 */
8781 private void rematchNetworksAndRequests(
8782 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8783 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008784 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008785 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008786 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008787 final long computed = SystemClock.elapsedRealtime();
8788 applyNetworkReassignment(changes, start);
8789 final long applied = SystemClock.elapsedRealtime();
8790 issueNetworkNeeds();
8791 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008792 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008793 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8794 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008795 log(changes.debugString());
8796 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008797 // Shorter form, only one line of log
8798 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8799 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008800 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008801 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008802
Chalard Jeand7f762d2019-12-10 19:01:29 +09008803 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008804 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008805 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008806
8807 // Since most of the time there are only 0 or 1 background networks, it would probably
8808 // be more efficient to just use an ArrayList here. TODO : measure performance
8809 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8810 for (final NetworkAgentInfo nai : nais) {
8811 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8812 }
8813
Chalard Jeand7f762d2019-12-10 19:01:29 +09008814 // First, update the lists of satisfied requests in the network agents. This is necessary
8815 // because some code later depends on this state to be correct, most prominently computing
8816 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008817 for (final NetworkReassignment.RequestReassignment event :
8818 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008819 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8820 event.mOldNetworkRequest, event.mNewNetworkRequest,
8821 event.mOldNetwork, event.mNewNetwork,
8822 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008823 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008824
James Mattise3ef1912020-12-20 11:09:58 -08008825 // Process default network changes if applicable.
8826 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008827
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008828 // Notify requested networks are available after the default net is switched, but
8829 // before LegacyTypeTracker sends legacy broadcasts
8830 for (final NetworkReassignment.RequestReassignment event :
8831 changes.getRequestReassignments()) {
8832 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008833 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008834 } else {
James Mattisa076c532020-12-02 14:12:41 -08008835 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008836 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008837 }
8838 }
8839
junyulai0ac374f2020-12-14 18:41:52 +08008840 // Update the inactivity state before processing listen callbacks, because the background
8841 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008842 // just yet though, because they have to be sent after the listens are processed to keep
8843 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008844 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008845 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008846 // Rematching may have altered the inactivity state of some networks, so update all
8847 // inactivity timers. updateInactivityState reads the state from the network agent
8848 // and does nothing if the state has not changed : the source of truth is controlled
8849 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8850 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008851 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008852 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008853 }
8854 }
8855
Chalard Jeanb10ab412019-12-11 14:12:30 +09008856 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008857 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008858 // Process listen requests and update capabilities if the background state has
8859 // changed for this network. For consistency with previous behavior, send onLost
8860 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008861 processNewlyLostListenRequests(nai);
8862 if (oldBackground != nai.isBackgroundNetwork()) {
8863 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008864 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008865 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008866 }
8867
junyulai0ac374f2020-12-14 18:41:52 +08008868 for (final NetworkAgentInfo nai : inactiveNetworks) {
8869 // For nascent networks, if connecting with no foreground request, skip broadcasting
8870 // LOSING for backward compatibility. This is typical when mobile data connected while
8871 // wifi connected with mobile data always-on enabled.
8872 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008873 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008874 }
8875
James Mattise3ef1912020-12-20 11:09:58 -08008876 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008877
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008878 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008879 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008880 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008881 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008882 // This network has active linger timers and no requests, but is not
8883 // lingering. Linger it.
8884 //
8885 // One way (the only way?) this can happen if this network is unvalidated
8886 // and became unneeded due to another network improving its score to the
8887 // point where this network will no longer be able to satisfy any requests
8888 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008889 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008890 notifyNetworkLosing(nai, now);
8891 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008892 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008893 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008894 teardownUnneededNetwork(nai);
8895 }
8896 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008897 }
8898 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008899
Chalard Jean62edfd82019-12-02 18:39:29 +09008900 /**
8901 * Apply a change in background state resulting from rematching networks with requests.
8902 *
8903 * During rematch, a network may change background states by starting to satisfy or stopping
8904 * to satisfy a foreground request. Listens don't count for this. When a network changes
8905 * background states, its capabilities need to be updated and callbacks fired for the
8906 * capability change.
8907 *
8908 * @param nai The network that changed background states
8909 */
8910 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8911 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8912 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8913 updateNetworkPermissions(nai, newNc);
8914 nai.getAndSetNetworkCapabilities(newNc);
8915 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8916 }
8917
Chalard Jeanf0344532019-11-19 19:23:38 +09008918 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008919 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008920 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008921 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8922 changes.getReassignment(mDefaultRequest);
8923 final NetworkAgentInfo oldDefaultNetwork =
8924 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8925 final NetworkAgentInfo newDefaultNetwork =
8926 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008927
Chalard Jean5b409c72021-02-04 13:12:59 +09008928 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008929 // Maintain the illusion : since the legacy API only understands one network at a time,
8930 // if the default network changed, apps should see a disconnected broadcast for the
8931 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008932 if (oldDefaultNetwork != null) {
8933 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8934 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008935 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008936 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008937 // The new default network can be newly null if and only if the old default
8938 // network doesn't satisfy the default request any more because it lost a
8939 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008940 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008941 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008942 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008943 }
8944 }
8945
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008946 // Now that all the callbacks have been sent, send the legacy network broadcasts
8947 // as needed. This is necessary so that legacy requests correctly bind dns
8948 // requests to this network. The legacy users are listening for this broadcast
8949 // and will generally do a dns request so they can ensureRouteToHost and if
8950 // they do that before the callbacks happen they'll use the default network.
8951 //
8952 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8953 // callbacks, but if apps can receive the broadcast before the callback, they still might
8954 // have an inconsistent view of networking.
8955 //
8956 // This *does* introduce a race where if the user uses the new api
8957 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8958 // they may get old info. Reverse this after the old startUsing api is removed.
8959 // This is on top of the multiple intent sequencing referenced in the todo above.
8960 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008961 if (nai.everConnected) {
8962 addNetworkToLegacyTypeTracker(nai);
8963 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008964 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008965 }
8966
Chalard Jean0354d8c2021-01-12 10:58:56 +09008967 private void issueNetworkNeeds() {
8968 ensureRunningOnConnectivityServiceThread();
8969 for (final NetworkOfferInfo noi : mNetworkOffers) {
8970 issueNetworkNeeds(noi);
8971 }
8972 }
8973
8974 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8975 ensureRunningOnConnectivityServiceThread();
8976 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8977 informOffer(nri, noi.offer, mNetworkRanker);
8978 }
8979 }
8980
8981 /**
8982 * Inform a NetworkOffer about any new situation of a request.
8983 *
8984 * This function handles updates to offers. A number of events may happen that require
8985 * updating the registrant for this offer about the situation :
8986 * • The offer itself was updated. This may lead the offer to no longer being able
8987 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8988 * or conversely being strengthened enough to beat the satisfier (and therefore
8989 * start being needed)
8990 * • The network satisfying a request changed (including cases where the request
8991 * starts or stops being satisfied). The new network may be a stronger or weaker
8992 * match than the old one, possibly affecting whether the offer is needed.
8993 * • The network satisfying a request updated their score. This may lead the offer
8994 * to no longer be able to beat it if the current satisfier got better, or
8995 * conversely start being a good choice if the current satisfier got weaker.
8996 *
8997 * @param nri The request
8998 * @param offer The offer. This may be an updated offer.
8999 */
9000 private static void informOffer(@NonNull NetworkRequestInfo nri,
9001 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9002 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9003 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009004
9005 // Multi-layer requests have a currently active request, the one being satisfied.
9006 // Since the system will try to bring up a better network than is currently satisfying
9007 // the request, NetworkProviders need to be told the offers matching the requests *above*
9008 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9009 // not needed, and the offer is needed for the active request iff the offer can beat
9010 // the satisfier.
9011 // For non-multilayer requests, the logic above gracefully degenerates to only the
9012 // last case.
9013 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9014 // providers that the offer is needed for this request, until the active request is found.
9015 // In a second phase, deal with the currently active request. In a third phase, inform
9016 // the providers that offer is unneeded for the remaining requests.
9017
9018 // First phase : inform providers of all requests above the active request.
9019 int i;
9020 for (i = 0; nri.mRequests.size() > i; ++i) {
9021 final NetworkRequest request = nri.mRequests.get(i);
9022 if (activeRequest == request) break; // Found the active request : go to phase 2
9023 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9024 // Since this request is higher-priority than the one currently satisfied, if the
9025 // offer can satisfy it, the provider should try and bring up the network for sure ;
9026 // no need to even ask the ranker – an offer that can satisfy is always better than
9027 // no network. Hence tell the provider so unless it already knew.
9028 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9029 offer.onNetworkNeeded(request);
9030 }
9031 }
9032
9033 // Second phase : deal with the active request (if any)
9034 if (null != activeRequest && activeRequest.isRequest()) {
9035 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009036 // If an offer can satisfy the request, it is considered needed if it is currently
9037 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009038 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009039 && satisfier.factorySerialNumber == offer.providerId
9040 && activeRequest.canBeSatisfiedBy(offer.caps);
9041 final boolean newNeeded = currentlyServing
9042 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009043 if (newNeeded != oldNeeded) {
9044 if (newNeeded) {
9045 offer.onNetworkNeeded(activeRequest);
9046 } else {
9047 // The offer used to be able to beat the satisfier. Now it can't.
9048 offer.onNetworkUnneeded(activeRequest);
9049 }
9050 }
9051 }
9052
9053 // Third phase : inform the providers that the offer isn't needed for any request
9054 // below the active one.
9055 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9056 final NetworkRequest request = nri.mRequests.get(i);
9057 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9058 // Since this request is lower-priority than the one currently satisfied, if the
9059 // offer can satisfy it, the provider should not try and bring up the network.
9060 // Hence tell the provider so unless it already knew.
9061 if (offer.neededFor(request)) {
9062 offer.onNetworkUnneeded(request);
9063 }
9064 }
9065 }
9066
Chalard Jean61c79252019-11-07 23:07:32 +09009067 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9068 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9069 NetworkRequest nr = nai.requestAt(i);
9070 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9071 // legacy type tracker filters out repeat adds
9072 mLegacyTypeTracker.add(nr.legacyType, nai);
9073 }
9074 }
9075
9076 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009077 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009078 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9079 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9080 if (nai.isVPN()) {
9081 mLegacyTypeTracker.add(TYPE_VPN, nai);
9082 }
9083 }
9084
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009085 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009086 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09009087 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009088 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009089 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009090 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009091
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009092 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009093 // Don't repeat publish.
9094 if (newInetCondition == mDefaultInetConditionPublished) return;
9095
9096 mDefaultInetConditionPublished = newInetCondition;
9097 sendInetConditionBroadcast(nai.networkInfo);
9098 }
9099
Chalard Jeand61375d2020-01-14 22:46:36 +09009100 @NonNull
9101 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9102 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009103 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009104 final boolean suspended =
9105 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9106 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9107 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9108 // state. This is because the network could have been suspended before connecting,
9109 // or it could be disconnecting while being suspended, and in both these cases
9110 // the state should not be overridden. Note that the only detailed state that
9111 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9112 // worry about multiple different substates of CONNECTED.
9113 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9114 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009115 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9116 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9117 // network agent is created, then goes to suspended, then goes out of suspended without
9118 // ever setting connected. Check if network agent is ever connected to update the state.
9119 newInfo.setDetailedState(nai.everConnected
9120 ? NetworkInfo.DetailedState.CONNECTED
9121 : NetworkInfo.DetailedState.CONNECTING,
9122 info.getReason(),
9123 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009124 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009125 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009126 return newInfo;
9127 }
9128
9129 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9130 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9131
Erik Kline99f301b2017-02-15 19:59:17 +09009132 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009133 NetworkInfo oldInfo = null;
9134 synchronized (networkAgent) {
9135 oldInfo = networkAgent.networkInfo;
9136 networkAgent.networkInfo = newInfo;
9137 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009138
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009139 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009140 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9141 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009142 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009143
Robin Leea8c0b6e2016-05-01 23:00:00 +01009144 if (!networkAgent.created
9145 && (state == NetworkInfo.State.CONNECTED
9146 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009147
9148 // A network that has just connected has zero requests and is thus a foreground network.
9149 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9150
Luke Huangfdd11f82019-04-09 18:41:49 +08009151 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009152 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009153 // Initialize the network's capabilities to their starting values according to the
9154 // underlying networks. This ensures that the capabilities are correct before
9155 // anything happens to the network.
9156 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009157 }
Paul Jensen74940202014-08-04 12:21:19 -04009158 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009159 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009160 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009161 }
9162
9163 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
9164 networkAgent.everConnected = true;
9165
lucaslin45e639b2019-04-03 17:09:28 +08009166 // NetworkCapabilities need to be set before sending the private DNS config to
9167 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009168 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9169
Erik Kline9a62f012018-03-21 07:18:33 -07009170 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009171 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9172 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009173
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009174 // If a rate limit has been configured and is applicable to this network (network
9175 // provides internet connectivity), apply it. The tc police filter cannot be attached
9176 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9177 // updateInterfaces -> INetd#networkAddInterface.
9178 // Note: in case of a system server crash, the NetworkController constructor in netd
9179 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9180 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9181 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9182 mIngressRateLimit);
9183 }
9184
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009185 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9186 // command must be sent after updating LinkProperties to maximize chances of
9187 // NetworkMonitor seeing the correct LinkProperties when starting.
9188 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009189 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009190 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009191 }
Chalard Jeand4900722022-02-06 12:25:38 +09009192 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9193 params.networkAgentConfig = networkAgent.networkAgentConfig;
9194 params.networkCapabilities = networkAgent.networkCapabilities;
9195 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9196 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009197 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9198 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9199 // call that would cause a Log.wtf to be emitted from the system_server process, and
9200 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9201 // process to check the interface version, just use an SDK check. NetworkStack will
9202 // always be new enough when running on T+.
9203 if (SdkLevel.isAtLeastT()) {
9204 networkAgent.networkMonitor().notifyNetworkConnected(params);
9205 } else {
9206 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9207 params.networkCapabilities);
9208 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09009209 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009210
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009211 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9212 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9213 // capabilities, so it only needs to be done once on initial connect, not every time the
9214 // network's capabilities change. Note that we do this before rematching the network,
9215 // so we could decide to tear it down immediately afterwards. That's fine though - on
9216 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9217 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009218 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009219
junyulai0ac374f2020-12-14 18:41:52 +08009220 // Before first rematching networks, put an inactivity timer without any request, this
9221 // allows {@code updateInactivityState} to update the state accordingly and prevent
9222 // tearing down for any {@code unneeded} evaluation in this period.
9223 // Note that the timer will not be rescheduled since the expiry time is
9224 // fixed after connection regardless of the network satisfying other requests or not.
9225 // But it will be removed as soon as the network satisfies a request for the first time.
9226 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9227 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009228 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009229
Paul Jensen05e85ee2014-09-11 11:00:39 -04009230 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009231 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009232
9233 // This has to happen after matching the requests, because callbacks are just requests.
9234 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009235 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009236 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009237 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009238 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009239 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009240 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009241 if (networkAgent.isVPN()) {
9242 // As the active or bound network changes for apps, broadcast the default proxy, as
9243 // apps may need to update their proxy data. This is called after disconnecting from
9244 // VPN to make sure we do not broadcast the old proxy data.
9245 // TODO(b/122649188): send the broadcast only to VPN users.
9246 mProxyTracker.sendProxyBroadcast();
9247 }
Yintang Gu5014b522019-06-18 14:24:32 +08009248 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
9249 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009250 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009251 }
9252 }
9253
Chalard Jean28018572020-12-21 18:36:52 +09009254 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009255 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9256 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009257 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009258 }
9259
Erik Kline99f301b2017-02-15 19:59:17 +09009260 // Notify only this one new request of the current state. Transfer all the
9261 // current state by calling NetworkCapabilities and LinkProperties callbacks
9262 // so that callers can be guaranteed to have as close to atomicity in state
9263 // transfer as can be supported by this current API.
9264 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009265 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009266 if (nri.mPendingIntent != null) {
9267 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9268 // Attempt no subsequent state pushes where intents are involved.
9269 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009270 }
Erik Kline99f301b2017-02-15 19:59:17 +09009271
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009272 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009273 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009274 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9275 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9276 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009277 }
9278
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009279 // Notify the requests on this NAI that the network is now lingered.
9280 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009281 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009282 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9283 }
9284
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009285 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9286 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9287 return vpnBlocked
9288 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9289 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9290 }
9291
9292 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9293 if (blockedReasons == BLOCKED_REASON_NONE) {
9294 mUidBlockedReasons.delete(uid);
9295 } else {
9296 mUidBlockedReasons.put(uid, blockedReasons);
9297 }
9298 }
9299
junyulaif2c67e42018-08-07 19:50:45 +08009300 /**
9301 * Notify of the blocked state apps with a registered callback matching a given NAI.
9302 *
9303 * Unlike other callbacks, blocked status is different between each individual uid. So for
9304 * any given nai, all requests need to be considered according to the uid who filed it.
9305 *
9306 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009307 * @param oldMetered True if the previous network capabilities were metered.
9308 * @param newMetered True if the current network capabilities are metered.
9309 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9310 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009311 */
9312 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009313 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9314 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009315
9316 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9317 NetworkRequest nr = nai.requestAt(i);
9318 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009319
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009320 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9321 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9322 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009323 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009324 : oldVpnBlocked;
9325
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009326 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9327 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9328 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009329 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009330 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009331 }
9332 }
9333 }
9334
9335 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009336 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009337 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009338 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009339 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009340 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009341 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009342 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009343 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009344
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009345 final int oldBlockedState = getBlockedState(
9346 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9347 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9348 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009349 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009350 }
junyulaif2c67e42018-08-07 19:50:45 +08009351 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9352 NetworkRequest nr = nai.requestAt(i);
9353 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009354 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009355 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9356 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009357 }
9358 }
9359 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009360 }
9361
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009362 @VisibleForTesting
9363 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009364 // The NetworkInfo we actually send out has no bearing on the real
9365 // state of affairs. For example, if the default connection is mobile,
9366 // and a request for HIPRI has just gone away, we need to pretend that
9367 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9368 // the state to DISCONNECTED, even though the network is of type MOBILE
9369 // and is still connected.
9370 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9371 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009372 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009373 if (state != DetailedState.DISCONNECTED) {
9374 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009375 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009376 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009377 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009378 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9379 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9380 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9381 if (info.isFailover()) {
9382 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9383 nai.networkInfo.setFailover(false);
9384 }
9385 if (info.getReason() != null) {
9386 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9387 }
9388 if (info.getExtraInfo() != null) {
9389 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9390 }
9391 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009392 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009393 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009394 if (newDefaultAgent != null) {
9395 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9396 newDefaultAgent.networkInfo);
9397 } else {
9398 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9399 }
9400 }
9401 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9402 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009403 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009404 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009405 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009406 }
9407 }
9408 }
9409
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009410 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009411 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009412 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009413 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009414 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009415 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9416 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009417 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9418 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009419 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009420 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009421 } else {
9422 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9423 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009424 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009425 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009426
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009427 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9428 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9429 }
9430
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009431 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009432 * Returns the list of all interfaces that could be used by network traffic that does not
9433 * explicitly specify a network. This includes the default network, but also all VPNs that are
9434 * currently connected.
9435 *
9436 * Must be called on the handler thread.
9437 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009438 @NonNull
9439 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009440 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009441 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009442 final Set<Integer> activeNetIds = new ArraySet<>();
9443 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9444 if (nri.isBeingSatisfied()) {
9445 activeNetIds.add(nri.getSatisfier().network().netId);
9446 }
9447 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009448 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009449 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009450 defaultNetworks.add(nai.network);
9451 }
9452 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009453 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009454 }
9455
9456 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009457 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9458 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009459 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009460 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009461 ensureRunningOnConnectivityServiceThread();
9462 String activeIface = null;
9463 LinkProperties activeLinkProperties = getActiveLinkProperties();
9464 if (activeLinkProperties != null) {
9465 activeIface = activeLinkProperties.getInterfaceName();
9466 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009467
junyulai2050bed2021-01-23 09:46:34 +08009468 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009469 try {
junyulaide41fc22021-01-22 22:46:01 +08009470 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009471 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009472 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9473 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009474 } catch (Exception ignored) {
9475 }
9476 }
9477
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009478 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009479 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009480 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009481 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009482 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009483
9484 if (!TextUtils.isEmpty(settingUrl)) {
9485 return settingUrl;
9486 }
9487
9488 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009489 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009490 if (!TextUtils.isEmpty(settingUrl)) {
9491 return settingUrl;
9492 }
9493
9494 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009495 }
9496
9497 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009498 public void startNattKeepalive(Network network, int intervalSeconds,
9499 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009500 enforceKeepalivePermission();
9501 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009502 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009503 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009504 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009505 }
9506
9507 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009508 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009509 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009510 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009511 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009512 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009513 mKeepaliveTracker.startNattKeepalive(
9514 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9515 intervalSeconds, cb,
9516 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9517 } finally {
9518 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9519 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009520 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9521 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009522 }
9523 }
junyulaid05a1922019-01-15 11:32:44 +08009524 }
9525
9526 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009527 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009528 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009529 try {
9530 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009531 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009532 mKeepaliveTracker.startTcpKeepalive(
9533 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9534 } finally {
9535 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9536 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009537 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9538 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009539 }
9540 }
junyulai0835a1e2019-01-08 20:04:33 +08009541 }
9542
9543 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009544 public void stopKeepalive(Network network, int slot) {
9545 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009546 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009547 }
9548
9549 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009550 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009551 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009552
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009553 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009554 final long token = Binder.clearCallingIdentity();
9555 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009556 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9557 UserHandle.getUserHandleForUid(uid))) {
9558 return;
9559 }
9560
Heemin Seogdb8489d2019-06-12 09:21:44 -07009561 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9562 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009563
9564 // Turn airplane mode off
9565 setAirplaneMode(false);
9566
9567 // restore private DNS settings to default mode (opportunistic)
9568 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9569 UserHandle.getUserHandleForUid(uid))) {
9570 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9571 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9572 }
9573
9574 Settings.Global.putString(mContext.getContentResolver(),
9575 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009576 } finally {
9577 Binder.restoreCallingIdentity(token);
9578 }
Stuart Scottd5463642015-04-02 18:00:02 -07009579 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009580
Ricky Wai7097cc92018-01-23 04:09:45 +00009581 @Override
9582 public byte[] getNetworkWatchlistConfigHash() {
9583 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9584 if (nwm == null) {
9585 loge("Unable to get NetworkWatchlistManager");
9586 return null;
9587 }
9588 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9589 return nwm.getWatchlistConfigHash();
9590 }
9591
Hugo Benichibe0c7652016-05-31 16:28:06 +09009592 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009593 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009594 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009595 }
Hugo Benichif4210292017-04-21 15:07:12 +09009596
9597 private static boolean toBool(int encodedBoolean) {
9598 return encodedBoolean != 0; // Only 0 means false.
9599 }
9600
9601 private static int encodeBool(boolean b) {
9602 return b ? 1 : 0;
9603 }
mswest4632928412018-03-12 10:34:34 -07009604
9605 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009606 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9607 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9608 @NonNull String[] args) {
9609 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9610 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009611 }
9612
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009613 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009614 @Override
9615 public int onCommand(String cmd) {
9616 if (cmd == null) {
9617 return handleDefaultCommands(cmd);
9618 }
9619 final PrintWriter pw = getOutPrintWriter();
9620 try {
9621 switch (cmd) {
9622 case "airplane-mode":
9623 final String action = getNextArg();
9624 if ("enable".equals(action)) {
9625 setAirplaneMode(true);
9626 return 0;
9627 } else if ("disable".equals(action)) {
9628 setAirplaneMode(false);
9629 return 0;
9630 } else if (action == null) {
9631 final ContentResolver cr = mContext.getContentResolver();
9632 final int enabled = Settings.Global.getInt(cr,
9633 Settings.Global.AIRPLANE_MODE_ON);
9634 pw.println(enabled == 0 ? "disabled" : "enabled");
9635 return 0;
9636 } else {
9637 onHelp();
9638 return -1;
9639 }
9640 default:
9641 return handleDefaultCommands(cmd);
9642 }
9643 } catch (Exception e) {
9644 pw.println(e);
9645 }
9646 return -1;
9647 }
9648
9649 @Override
9650 public void onHelp() {
9651 PrintWriter pw = getOutPrintWriter();
9652 pw.println("Connectivity service commands:");
9653 pw.println(" help");
9654 pw.println(" Print this help text.");
9655 pw.println(" airplane-mode [enable|disable]");
9656 pw.println(" Turn airplane mode on or off.");
9657 pw.println(" airplane-mode");
9658 pw.println(" Get airplane mode.");
9659 }
9660 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009661
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009662 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009663 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9664 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9665 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009666 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009667 }
9668
he_won.hwang881307a2022-03-15 21:23:52 +09009669 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9670 if (nai == null) return;
9671 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9672 final TransportInfo newInfo = nc.getTransportInfo();
9673 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9674 return;
9675 }
9676 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
9677 nai.lastRoamTimestamp = SystemClock.elapsedRealtime();
9678 }
9679 }
9680
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009681 /**
9682 * @param connectionInfo the connection to resolve.
9683 * @return {@code uid} if the connection is found and the app has permission to observe it
9684 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9685 * connection is not found.
9686 */
9687 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009688 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9689 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9690 }
9691
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009692 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009693 connectionInfo.local, connectionInfo.remote);
9694
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009695 if (uid == INVALID_UID) return uid; // Not found.
9696
9697 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9698 // VPN, if any, that applies to the UID that owns the connection.
9699 if (checkNetworkStackPermission()) return uid;
9700
9701 final NetworkAgentInfo vpn = getVpnForUid(uid);
9702 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009703 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009704 return INVALID_UID;
9705 }
9706
9707 return uid;
9708 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009709
Benedict Wong493e04b2018-11-09 14:45:34 -08009710 /**
9711 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9712 *
9713 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9714 */
9715 @Override
9716 public IBinder startOrGetTestNetworkService() {
9717 synchronized (mTNSLock) {
9718 TestNetworkService.enforceTestNetworkPermissions(mContext);
9719
9720 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009721 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009722 }
9723
9724 return mTNS;
9725 }
9726 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009727
Cody Kesting73708bf2019-12-18 10:57:50 -08009728 /**
9729 * Handler used for managing all Connectivity Diagnostics related functions.
9730 *
9731 * @see android.net.ConnectivityDiagnosticsManager
9732 *
9733 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9734 */
9735 @VisibleForTesting
9736 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009737 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9738
Cody Kesting73708bf2019-12-18 10:57:50 -08009739 /**
9740 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9741 * android.net.ConnectivityDiagnosticsManager}.
9742 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9743 * NetworkRequestInfo to be registered
9744 */
9745 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9746
9747 /**
9748 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9749 * android.net.ConnectivityDiagnosticsManager}.
9750 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9751 * arg1 = the uid of the caller
9752 */
9753 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9754
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009755 /**
9756 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009757 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009758 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9759 * NetworkMonitor.
9760 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009761 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009762 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009763
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009764 /**
9765 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9766 * been detected on the network.
9767 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9768 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9769 * arg2 = NetID.
9770 * data = PersistableBundle of extras passed from NetworkMonitor.
9771 */
9772 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9773
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009774 /**
9775 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9776 * the platform. This event will invoke {@link
9777 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9778 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009779 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009780 */
9781 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9782
Cody Kesting73708bf2019-12-18 10:57:50 -08009783 private ConnectivityDiagnosticsHandler(Looper looper) {
9784 super(looper);
9785 }
9786
9787 @Override
9788 public void handleMessage(Message msg) {
9789 switch (msg.what) {
9790 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9791 handleRegisterConnectivityDiagnosticsCallback(
9792 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9793 break;
9794 }
9795 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9796 handleUnregisterConnectivityDiagnosticsCallback(
9797 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9798 break;
9799 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009800 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009801 final ConnectivityReportEvent reportEvent =
9802 (ConnectivityReportEvent) msg.obj;
9803
Aaron Huang959d3642021-01-21 15:47:41 +08009804 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009805 break;
9806 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009807 case EVENT_DATA_STALL_SUSPECTED: {
9808 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009809 final Pair<Long, PersistableBundle> arg =
9810 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009811 if (nai == null) break;
9812
Aaron Huang959d3642021-01-21 15:47:41 +08009813 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009814 break;
9815 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009816 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009817 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009818 break;
9819 }
9820 default: {
9821 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9822 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009823 }
9824 }
9825 }
9826
9827 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9828 @VisibleForTesting
9829 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9830 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9831 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009832 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009833
9834 @VisibleForTesting
9835 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009836 @NonNull IConnectivityDiagnosticsCallback cb,
9837 @NonNull NetworkRequestInfo nri,
9838 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009839 mCb = cb;
9840 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009841 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009842 }
9843
9844 @Override
9845 public void binderDied() {
9846 log("ConnectivityDiagnosticsCallback IBinder died.");
9847 unregisterConnectivityDiagnosticsCallback(mCb);
9848 }
9849 }
9850
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009851 /**
9852 * Class used for sending information from {@link
9853 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9854 */
9855 private static class NetworkTestedResults {
9856 private final int mNetId;
9857 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009858 @Nullable private final String mRedirectUrl;
9859
9860 private NetworkTestedResults(
9861 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9862 mNetId = netId;
9863 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009864 mRedirectUrl = redirectUrl;
9865 }
9866 }
9867
9868 /**
9869 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9870 * ConnectivityDiagnosticsHandler}.
9871 */
9872 private static class ConnectivityReportEvent {
9873 private final long mTimestampMillis;
9874 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009875 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009876
Aaron Huang959d3642021-01-21 15:47:41 +08009877 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9878 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009879 mTimestampMillis = timestampMillis;
9880 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009881 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009882 }
9883 }
9884
Cody Kestingf1120be2020-08-03 18:01:40 -07009885 /**
9886 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9887 * ConnectivityDiagnosticsHandler}.
9888 */
9889 private static class ReportedNetworkConnectivityInfo {
9890 public final boolean hasConnectivity;
9891 public final boolean isNetworkRevalidating;
9892 public final int reporterUid;
9893 @NonNull public final NetworkAgentInfo nai;
9894
9895 private ReportedNetworkConnectivityInfo(
9896 boolean hasConnectivity,
9897 boolean isNetworkRevalidating,
9898 int reporterUid,
9899 @NonNull NetworkAgentInfo nai) {
9900 this.hasConnectivity = hasConnectivity;
9901 this.isNetworkRevalidating = isNetworkRevalidating;
9902 this.reporterUid = reporterUid;
9903 this.nai = nai;
9904 }
9905 }
9906
Cody Kesting73708bf2019-12-18 10:57:50 -08009907 private void handleRegisterConnectivityDiagnosticsCallback(
9908 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9909 ensureRunningOnConnectivityServiceThread();
9910
9911 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009912 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009913 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9914
James Mattis64b8b0f2020-11-24 17:40:49 -08009915 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9916 // confusing for these networks to change when an NRI is satisfied in another layer.
9917 if (nri.isMultilayerRequest()) {
9918 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9919 + "network requests.");
9920 }
9921
Cody Kesting73708bf2019-12-18 10:57:50 -08009922 // This means that the client registered the same callback multiple times. Do
9923 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009924 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009925 if (VDBG) log("Diagnostics callback is already registered");
9926
9927 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9928 // incremented when the NetworkRequestInfo is created as part of
9929 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009930 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -08009931 return;
9932 }
9933
Cody Kesting31f1ff62020-03-05 10:46:02 -08009934 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009935
9936 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009937 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009938 } catch (RemoteException e) {
9939 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009940 return;
9941 }
9942
9943 // Once registered, provide ConnectivityReports for matching Networks
9944 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9945 synchronized (mNetworkForNetId) {
9946 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9947 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009948 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9949 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009950 matchingNetworks.add(nai);
9951 }
9952 }
9953 }
9954 for (final NetworkAgentInfo nai : matchingNetworks) {
9955 final ConnectivityReport report = nai.getConnectivityReport();
9956 if (report == null) {
9957 continue;
9958 }
9959 if (!checkConnectivityDiagnosticsPermissions(
9960 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9961 continue;
9962 }
9963
9964 try {
9965 cb.onConnectivityReportAvailable(report);
9966 } catch (RemoteException e) {
9967 // Exception while sending the ConnectivityReport. Move on to the next network.
9968 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009969 }
9970 }
9971
9972 private void handleUnregisterConnectivityDiagnosticsCallback(
9973 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9974 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009975 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009976
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009977 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9978 mConnectivityDiagnosticsCallbacks.remove(iCb);
9979 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009980 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9981 return;
9982 }
9983
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009984 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009985
Cody Kesting70fa2b22020-12-02 12:16:56 -08009986 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9987 // (if the Binder died)
9988 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9989 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009990 return;
9991 }
9992
Cody Kesting46cb1672020-03-04 13:35:20 -08009993 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9994 // incremented when the NetworkRequestInfo is created as part of
9995 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009996 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -08009997
Cody Kesting31f1ff62020-03-05 10:46:02 -08009998 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009999 }
10000
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010001 private void handleNetworkTestedWithExtras(
10002 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10003 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010004 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010005 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010006 final ConnectivityReport report =
10007 new ConnectivityReport(
10008 reportEvent.mNai.network,
10009 reportEvent.mTimestampMillis,
10010 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010011 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010012 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010013 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010014
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010015 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010016 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010017 for (final IConnectivityDiagnosticsCallback cb : results) {
10018 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010019 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010020 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010021 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010022 }
10023 }
10024 }
10025
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010026 private void handleDataStallSuspected(
10027 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10028 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010029 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010030 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010031 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010032 new DataStallReport(
10033 nai.network,
10034 timestampMillis,
10035 detectionMethod,
10036 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010037 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010038 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010039 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010040 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010041 for (final IConnectivityDiagnosticsCallback cb : results) {
10042 try {
10043 cb.onDataStallSuspected(report);
10044 } catch (RemoteException ex) {
10045 loge("Error invoking onDataStallSuspected", ex);
10046 }
10047 }
10048 }
10049
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010050 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010051 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10052 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10053 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10054
10055 // If the Network is being re-validated as a result of this call to
10056 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10057 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010058 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010059 getMatchingPermissionedCallbacks(
10060 nai,
10061 reportedNetworkConnectivityInfo.isNetworkRevalidating
10062 ? Process.INVALID_UID
10063 : reportedNetworkConnectivityInfo.reporterUid);
10064
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010065 for (final IConnectivityDiagnosticsCallback cb : results) {
10066 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010067 cb.onNetworkConnectivityReported(
10068 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010069 } catch (RemoteException ex) {
10070 loge("Error invoking onNetworkConnectivityReported", ex);
10071 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010072
10073 // If the Network isn't re-validating, also provide the cached report. If there is no
10074 // cached report, the Network is still being validated and a report will be sent once
10075 // validation is complete. Note that networks which never undergo validation will still
10076 // have a cached ConnectivityReport with RESULT_SKIPPED.
10077 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10078 try {
10079 cb.onConnectivityReportAvailable(cachedReport);
10080 } catch (RemoteException ex) {
10081 loge("Error invoking onConnectivityReportAvailable", ex);
10082 }
10083 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010084 }
10085 }
10086
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010087 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010088 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10089 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010090 sanitized.setUids(null);
10091 sanitized.setAdministratorUids(new int[0]);
10092 sanitized.setOwnerUid(Process.INVALID_UID);
10093 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010094 }
10095
Cody Kestingf1120be2020-08-03 18:01:40 -070010096 /**
10097 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10098 *
10099 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10100 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010101 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010102 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010103 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010104 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010105 mConnectivityDiagnosticsCallbacks.entrySet()) {
10106 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10107 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010108
James Mattis64b8b0f2020-11-24 17:40:49 -080010109 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010110 if (!nai.satisfies(nri.mRequests.get(0))) {
10111 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010112 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010113
10114 // UID for this callback must either be:
10115 // - INVALID_UID (which sends callbacks to all UIDs), or
10116 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10117 // notified as a result)
10118 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10119 continue;
10120 }
10121
10122 if (!checkConnectivityDiagnosticsPermissions(
10123 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10124 continue;
10125 }
10126
10127 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010128 }
10129 return results;
10130 }
10131
Cody Kesting7474f672021-05-11 14:22:40 -070010132 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10133 @NonNull NetworkAgentInfo nai) {
10134 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10135 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10136 }
10137
Cody Kesting160ef392021-05-05 13:17:22 -070010138 private boolean hasLocationPermission(String packageName, int uid) {
10139 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10140 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10141 // call in a try-catch.
10142 try {
10143 if (!mLocationPermissionChecker.checkLocationPermission(
10144 packageName, null /* featureId */, uid, null /* message */)) {
10145 return false;
10146 }
10147 } catch (SecurityException e) {
10148 return false;
10149 }
10150
10151 return true;
10152 }
10153
10154 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10155 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010156 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010157 && virtual.networkCapabilities.getOwnerUid() == uid
10158 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10159 return true;
10160 }
10161 }
10162
10163 return false;
10164 }
10165
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010166 @VisibleForTesting
10167 boolean checkConnectivityDiagnosticsPermissions(
10168 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10169 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10170 return true;
10171 }
10172
Cody Kesting160ef392021-05-05 13:17:22 -070010173 // Administrator UIDs also contains the Owner UID
10174 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10175 if (!CollectionUtils.contains(administratorUids, callbackUid)
10176 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010177 return false;
10178 }
10179
Cody Kesting7474f672021-05-11 14:22:40 -070010180 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10181 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010182 }
10183
Cody Kestingd199a9d2019-12-17 12:55:28 -080010184 @Override
10185 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010186 @NonNull IConnectivityDiagnosticsCallback callback,
10187 @NonNull NetworkRequest request,
10188 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010189 Objects.requireNonNull(callback, "callback must not be null");
10190 Objects.requireNonNull(request, "request must not be null");
10191 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10192
Cody Kesting73708bf2019-12-18 10:57:50 -080010193 if (request.legacyType != TYPE_NONE) {
10194 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10195 + " Please use NetworkCapabilities instead.");
10196 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010197 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010198 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010199
10200 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10201 // and administrator uids to be safe.
10202 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010203 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010204
10205 final NetworkRequest requestWithId =
10206 new NetworkRequest(
10207 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10208
10209 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10210 //
10211 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10212 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10213 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010214 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010215 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010216 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010217
10218 mConnectivityDiagnosticsHandler.sendMessage(
10219 mConnectivityDiagnosticsHandler.obtainMessage(
10220 ConnectivityDiagnosticsHandler
10221 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10222 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010223 }
10224
10225 @Override
10226 public void unregisterConnectivityDiagnosticsCallback(
10227 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010228 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010229 mConnectivityDiagnosticsHandler.sendMessage(
10230 mConnectivityDiagnosticsHandler.obtainMessage(
10231 ConnectivityDiagnosticsHandler
10232 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010233 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010234 0,
10235 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010236 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010237
10238 @Override
10239 public void simulateDataStall(int detectionMethod, long timestampMillis,
10240 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010241 Objects.requireNonNull(network, "network must not be null");
10242 Objects.requireNonNull(extras, "extras must not be null");
10243
paulhu3ffffe72021-09-16 10:15:22 +080010244 enforceAnyPermissionOf(mContext,
10245 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010246 android.Manifest.permission.NETWORK_STACK);
10247 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10248 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010249 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010250 }
10251
10252 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010253 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010254 throw new SecurityException("Data Stall simulation is only possible for network "
10255 + "creators");
10256 }
10257
Cody Kesting652e3ec2020-05-21 12:08:21 -070010258 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10259 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10260 // Data Stall information as a DataStallReportParcelable and passing to
10261 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10262 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010263 final DataStallReportParcelable p = new DataStallReportParcelable();
10264 p.timestampMillis = timestampMillis;
10265 p.detectionMethod = detectionMethod;
10266
10267 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10268 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10269 }
10270 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10271 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10272 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10273 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10274 }
10275
Serik Beketayevec8ad212020-12-07 22:43:07 -080010276 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010277 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010278
lucaslin66f44212021-02-23 01:12:55 +080010279 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10280 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010281 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010282 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010283 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010284 }
lucaslin37a16d92021-01-21 19:48:09 +080010285
10286 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010287 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010288 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010289 nai.clatd.interfaceLinkStateChanged(iface, up);
10290 }
10291 }
10292
10293 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010294 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010295 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010296 nai.clatd.interfaceRemoved(iface);
10297 }
lucaslin66f44212021-02-23 01:12:55 +080010298 }
10299 }
10300
lucaslin1a8b4c62021-01-21 02:02:55 +080010301 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10302
10303 /**
10304 * Class used for updating network activity tracking with netd and notify network activity
10305 * changes.
10306 */
10307 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010308 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010309 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010310 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010311 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10312 new RemoteCallbackList<>();
10313 // Indicate the current system default network activity is active or not.
10314 @GuardedBy("mActiveIdleTimers")
10315 private boolean mNetworkActive;
10316 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010317 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010318 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010319
Chalard Jean46bfbf02022-02-02 00:56:25 +090010320 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010321 public final int timeout;
10322 public final int transportType;
10323
10324 IdleTimerParams(int timeout, int transport) {
10325 this.timeout = timeout;
10326 this.transportType = transport;
10327 }
10328 }
10329
10330 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010331 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010332 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010333 mNetd = netd;
10334 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010335 }
10336
lucaslin66f44212021-02-23 01:12:55 +080010337 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10338 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10339 synchronized (mActiveIdleTimers) {
10340 mNetworkActive = active;
10341 // If there are no idle timers, it means that system is not monitoring
10342 // activity, so the system default network for those default network
10343 // unspecified apps is always considered active.
10344 //
10345 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10346 // any network activity change event. Whenever this event is received,
10347 // the mActiveIdleTimers should be always not empty. The legacy behavior
10348 // is no-op. Remove to refer to mNetworkActive only.
10349 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10350 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10351 }
10352 }
10353 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010354
lucaslin1193a5d2021-01-21 02:04:15 +080010355 // The network activity should only be updated from ConnectivityService handler thread
10356 // when mActiveIdleTimers lock is held.
10357 @GuardedBy("mActiveIdleTimers")
10358 private void reportNetworkActive() {
10359 final int length = mNetworkActivityListeners.beginBroadcast();
10360 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10361 try {
10362 for (int i = 0; i < length; i++) {
10363 try {
10364 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10365 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010366 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010367 }
10368 }
10369 } finally {
10370 mNetworkActivityListeners.finishBroadcast();
10371 }
10372 }
10373
10374 @GuardedBy("mActiveIdleTimers")
10375 public void handleReportNetworkActivity() {
10376 synchronized (mActiveIdleTimers) {
10377 reportNetworkActive();
10378 }
10379 }
10380
lucaslin1a8b4c62021-01-21 02:02:55 +080010381 // This is deprecated and only to support legacy use cases.
10382 private int transportTypeToLegacyType(int type) {
10383 switch (type) {
10384 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010385 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010386 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010387 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010388 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010389 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010390 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010391 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010392 default:
10393 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10394 }
10395 return ConnectivityManager.TYPE_NONE;
10396 }
10397
10398 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10399 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10400 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10401 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10402 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10403 final long ident = Binder.clearCallingIdentity();
10404 try {
10405 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10406 RECEIVE_DATA_ACTIVITY_CHANGE,
10407 null /* resultReceiver */,
10408 null /* scheduler */,
10409 0 /* initialCode */,
10410 null /* initialData */,
10411 null /* initialExtra */);
10412 } finally {
10413 Binder.restoreCallingIdentity(ident);
10414 }
10415 }
10416
10417 /**
10418 * Setup data activity tracking for the given network.
10419 *
10420 * Every {@code setupDataActivityTracking} should be paired with a
10421 * {@link #removeDataActivityTracking} for cleanup.
10422 */
10423 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10424 final String iface = networkAgent.linkProperties.getInterfaceName();
10425
10426 final int timeout;
10427 final int type;
10428
10429 if (networkAgent.networkCapabilities.hasTransport(
10430 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10431 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010432 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010433 10);
10434 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10435 } else if (networkAgent.networkCapabilities.hasTransport(
10436 NetworkCapabilities.TRANSPORT_WIFI)) {
10437 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010438 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010439 15);
10440 type = NetworkCapabilities.TRANSPORT_WIFI;
10441 } else {
10442 return; // do not track any other networks
10443 }
10444
lucaslinb961efc2021-01-21 02:03:17 +080010445 updateRadioPowerState(true /* isActive */, type);
10446
lucaslin1a8b4c62021-01-21 02:02:55 +080010447 if (timeout > 0 && iface != null) {
10448 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010449 synchronized (mActiveIdleTimers) {
10450 // Networks start up.
10451 mNetworkActive = true;
10452 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10453 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10454 reportNetworkActive();
10455 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010456 } catch (Exception e) {
10457 // You shall not crash!
10458 loge("Exception in setupDataActivityTracking " + e);
10459 }
10460 }
10461 }
10462
10463 /**
10464 * Remove data activity tracking when network disconnects.
10465 */
10466 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10467 final String iface = networkAgent.linkProperties.getInterfaceName();
10468 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10469
lucaslinb961efc2021-01-21 02:03:17 +080010470 if (iface == null) return;
10471
10472 final int type;
10473 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10474 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10475 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10476 type = NetworkCapabilities.TRANSPORT_WIFI;
10477 } else {
10478 return; // do not track any other networks
10479 }
10480
10481 try {
10482 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010483 synchronized (mActiveIdleTimers) {
10484 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10485 // The call fails silently if no idle timer setup for this interface
10486 mNetd.idletimerRemoveInterface(iface, params.timeout,
10487 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010488 }
lucaslinb961efc2021-01-21 02:03:17 +080010489 } catch (Exception e) {
10490 // You shall not crash!
10491 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010492 }
10493 }
10494
10495 /**
10496 * Update data activity tracking when network state is updated.
10497 */
10498 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10499 NetworkAgentInfo oldNetwork) {
10500 if (newNetwork != null) {
10501 setupDataActivityTracking(newNetwork);
10502 }
10503 if (oldNetwork != null) {
10504 removeDataActivityTracking(oldNetwork);
10505 }
10506 }
lucaslinb961efc2021-01-21 02:03:17 +080010507
10508 private void updateRadioPowerState(boolean isActive, int transportType) {
10509 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10510 switch (transportType) {
10511 case NetworkCapabilities.TRANSPORT_CELLULAR:
10512 bs.reportMobileRadioPowerState(isActive, NO_UID);
10513 break;
10514 case NetworkCapabilities.TRANSPORT_WIFI:
10515 bs.reportWifiRadioPowerState(isActive, NO_UID);
10516 break;
10517 default:
10518 logw("Untracked transport type:" + transportType);
10519 }
10520 }
lucaslin1193a5d2021-01-21 02:04:15 +080010521
10522 public boolean isDefaultNetworkActive() {
10523 synchronized (mActiveIdleTimers) {
10524 // If there are no idle timers, it means that system is not monitoring activity,
10525 // so the default network is always considered active.
10526 //
10527 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10528 // tracking is disabled (negative idle timer value configured), or no active default
10529 // network. In the latter case, this reports active but it should report inactive.
10530 return mNetworkActive || mActiveIdleTimers.isEmpty();
10531 }
10532 }
10533
10534 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10535 mNetworkActivityListeners.register(l);
10536 }
10537
10538 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10539 mNetworkActivityListeners.unregister(l);
10540 }
lucaslin012f7a12021-01-21 02:04:35 +080010541
10542 public void dump(IndentingPrintWriter pw) {
10543 synchronized (mActiveIdleTimers) {
10544 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10545 pw.println("Idle timers:");
10546 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10547 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10548 final IdleTimerParams params = ent.getValue();
10549 pw.print(" timeout="); pw.print(params.timeout);
10550 pw.print(" type="); pw.println(params.transportType);
10551 }
10552 }
10553 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010554 }
James Mattis47db0582021-01-01 14:13:35 -080010555
Daniel Brightf9e945b2020-06-15 16:10:01 -070010556 /**
10557 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10558 *
10559 * @param socketInfo the socket information
10560 * @param callback the callback to register
10561 */
10562 @Override
10563 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10564 @NonNull final IQosCallback callback) {
10565 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10566 if (nai == null || nai.networkCapabilities == null) {
10567 try {
10568 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10569 } catch (final RemoteException ex) {
10570 loge("registerQosCallbackInternal: RemoteException", ex);
10571 }
10572 return;
10573 }
10574 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10575 }
10576
10577 /**
10578 * Register a {@link IQosCallback} with base {@link QosFilter}.
10579 *
10580 * @param filter the filter to register
10581 * @param callback the callback to register
10582 * @param nai the agent information related to the filter's network
10583 */
10584 @VisibleForTesting
10585 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10586 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010587 Objects.requireNonNull(filter, "filter must be non-null");
10588 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010589
10590 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010591 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10592 // on this network is unregistered when the app loses permission or b) no QoS
10593 // callbacks are sent for restricted networks unless the app currently has permission
10594 // to access restricted networks.
10595 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010596 }
10597 mQosCallbackTracker.registerCallback(callback, filter, nai);
10598 }
10599
10600 /**
10601 * Unregisters the given callback.
10602 *
10603 * @param callback the callback to unregister
10604 */
10605 @Override
10606 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010607 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010608 mQosCallbackTracker.unregisterCallback(callback);
10609 }
James Mattis47db0582021-01-01 14:13:35 -080010610
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010611 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10612 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10613 // Enterprise device can be fully managed like device owner and such use case
10614 // also should be supported. Calling app check for work profile and fully managed device
10615 // is already done in DevicePolicyManager.
10616 // This check is an extra caution to be sure device is fully managed or not.
10617 final UserManager um = mContext.getSystemService(UserManager.class);
10618 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10619 if (um.isManagedProfile(profile.getIdentifier())) {
10620 return true;
10621 }
10622 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10623 return false;
10624 }
10625
James Mattis45d81842021-01-10 14:24:24 -080010626 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010627 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010628 *
10629 * See the documentation for the individual preferences for a description of the supported
10630 * behaviors.
10631 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010632 * @param profile If the device owner is set, any profile is allowed.
10633 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010634 * @param preferences the list of profile network preferences for the
10635 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010636 * @param listener an optional listener to listen for completion of the operation.
10637 */
10638 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010639 public void setProfileNetworkPreferences(
10640 @NonNull final UserHandle profile,
10641 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010642 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010643 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010644 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010645
10646 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010647 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10648 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10649 .build();
10650 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010651 }
10652
paulhu3ffffe72021-09-16 10:15:22 +080010653 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010654 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010655 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010656 }
10657 if (profile.getIdentifier() < 0) {
10658 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10659 + "UserHandle.CURRENT not supported)");
10660 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010661 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10662 throw new IllegalArgumentException("Profile must be a managed profile "
10663 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010664 }
paulhuaa0743d2021-05-26 21:56:03 +080010665
Chalard Jean46bfbf02022-02-02 00:56:25 +090010666 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010667 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010668 for (final ProfileNetworkPreference preference : preferences) {
10669 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010670 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010671 switch (preference.getPreference()) {
10672 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10673 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010674 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010675 if (preference.getPreferenceEnterpriseId() != 0) {
10676 throw new IllegalArgumentException(
10677 "Invalid enterprise identifier in setProfileNetworkPreferences");
10678 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010679 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010680 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10681 allowFallback = false;
10682 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010683 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010684 // This code is needed even though there is a check later on,
10685 // because isRangeAlreadyInPreferenceList assumes that every preference
10686 // has a UID list.
10687 if (hasDefaultPreference) {
10688 throw new IllegalArgumentException(
10689 "Default profile preference should not be set along with other "
10690 + "preference");
10691 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010692 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10693 throw new IllegalArgumentException(
10694 "Invalid enterprise identifier in setProfileNetworkPreferences");
10695 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010696 final Set<UidRange> uidRangeSet =
10697 getUidListToBeAppliedForNetworkPreference(profile, preference);
10698 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10699 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10700 } else {
10701 throw new IllegalArgumentException(
10702 "Overlapping uid range in setProfileNetworkPreferences");
10703 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010704 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010705 nc.addEnterpriseId(
10706 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010707 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10708 break;
10709 default:
10710 throw new IllegalArgumentException(
10711 "Invalid preference in setProfileNetworkPreferences");
10712 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010713 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10714 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010715 if (hasDefaultPreference && preferenceList.size() > 1) {
10716 throw new IllegalArgumentException(
10717 "Default profile preference should not be set along with other preference");
10718 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010719 }
10720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010721 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010722 }
10723
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010724 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10725 @NonNull final UserHandle profile,
10726 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10727 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010728 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10729 profileNetworkPreference.getIncludedUids());
10730
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010731 if (uidRangeSet.size() > 0) {
10732 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10733 throw new IllegalArgumentException(
10734 "Allow uid range is outside the uid range of profile.");
10735 }
10736 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010737 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010738 profileNetworkPreference.getExcludedUids());
10739 if (disallowUidRangeSet.size() > 0) {
10740 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10741 throw new IllegalArgumentException(
10742 "disallow uid range is outside the uid range of profile.");
10743 }
10744 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10745 disallowUidRangeSet);
10746 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010747 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010748 uidRangeSet.add(profileUids);
10749 }
10750 }
10751 return uidRangeSet;
10752 }
10753
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010754 private boolean isEnterpriseIdentifierValid(
10755 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010756 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010757 return true;
10758 }
10759 return false;
10760 }
10761
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010762 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010763 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010764 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010765 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010766 // The NRI for a user should contain the request for capabilities.
10767 // If fallback to default network is needed then NRI should include
10768 // the request for the default network. Create an image of it to
10769 // have the correct UIDs in it (also a request can only be part of one NRI, because
10770 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010771 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10772 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010773 if (pref.allowFallback) {
10774 nrs.add(createDefaultInternetRequestForTransport(
10775 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10776 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010777 if (VDBG) {
10778 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10779 pref.capabilities.getUids()));
10780 }
10781
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010782 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010783 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010784 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010785 result.add(nri);
10786 }
10787 return result;
10788 }
10789
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010790 /**
10791 * Compare if the given UID range sets have the same UIDs.
10792 *
10793 */
10794 private boolean isRangeAlreadyInPreferenceList(
10795 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10796 @NonNull Set<UidRange> uidRangeSet) {
10797 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10798 return false;
10799 }
10800 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10801 if (UidRangeUtils.doesRangeSetOverlap(
10802 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10803 return true;
10804 }
10805 }
10806 return false;
10807 }
10808
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010809 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010810 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010811 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010812 /*
10813 * handleSetProfileNetworkPreference is always called for single user.
10814 * preferenceList only contains preferences for different uids within the same user
10815 * (enforced by getUidListToBeAppliedForNetworkPreference).
10816 * Clear all the existing preferences for the user before applying new preferences.
10817 *
10818 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010819 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010820 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010821 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010822 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10823 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010824
paulhu74128522021-09-28 02:29:03 +000010825 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10826 addPerAppDefaultNetworkRequests(
10827 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010828
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010829 // Finally, rematch.
10830 rematchAllNetworksAndRequests();
10831
10832 if (null != listener) {
10833 try {
10834 listener.onComplete();
10835 } catch (RemoteException e) {
10836 loge("Listener for setProfileNetworkPreference has died");
10837 }
10838 }
10839 }
10840
paulhu51f77dc2021-06-07 02:34:20 +000010841 @VisibleForTesting
10842 @NonNull
10843 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10844 @NonNull final Set<Integer> uids) {
10845 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10846 if (uids.size() == 0) {
10847 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10848 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10849 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10850 return nris;
10851 }
10852
10853 final List<NetworkRequest> requests = new ArrayList<>();
10854 // The NRI should be comprised of two layers:
10855 // - The request for the mobile network preferred.
10856 // - The request for the default network, for fallback.
10857 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010858 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010859 requests.add(createDefaultInternetRequestForTransport(
10860 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10861 final Set<UidRange> ranges = new ArraySet<>();
10862 for (final int uid : uids) {
10863 ranges.add(new UidRange(uid, uid));
10864 }
10865 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010866 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010867 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010868 return nris;
10869 }
10870
10871 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010872 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010873 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10874 addPerAppDefaultNetworkRequests(
10875 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010876 // Finally, rematch.
10877 rematchAllNetworksAndRequests();
10878 }
10879
Patrick Rohr2857ac42022-01-21 14:58:16 +010010880 private void handleIngressRateLimitChanged() {
10881 final long oldIngressRateLimit = mIngressRateLimit;
10882 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10883 mContext);
10884 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10885 if (canNetworkBeRateLimited(networkAgent)) {
10886 // If rate limit has previously been enabled, remove the old limit first.
10887 if (oldIngressRateLimit >= 0) {
10888 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10889 }
10890 if (mIngressRateLimit >= 0) {
10891 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10892 mIngressRateLimit);
10893 }
10894 }
10895 }
10896 }
10897
10898 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010899 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10900 if (!SdkLevel.isAtLeastT()) return false;
10901
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010902 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10903 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10904 // internet connectivity can be rate limited.
10905 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10906 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010907 return false;
10908 }
10909
10910 final String iface = networkAgent.linkProperties.getInterfaceName();
10911 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010010912 // This may happen in tests, but if there is no interface then there is nothing that
10913 // can be rate limited.
10914 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010010915 return false;
10916 }
10917 return true;
10918 }
10919
James Mattis45d81842021-01-10 14:24:24 -080010920 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010921 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10922 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010923 }
10924
10925 /**
10926 * Used by automotive devices to set the network preferences used to direct traffic at an
10927 * application level as per the given OemNetworkPreferences. An example use-case would be an
10928 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10929 * vehicle via a particular network.
10930 *
10931 * Calling this will overwrite the existing preference.
10932 *
James Mattisda32cfe2021-01-26 16:23:52 -080010933 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010934 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010935 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010936 */
James Mattis47db0582021-01-01 14:13:35 -080010937 @Override
James Mattis45d81842021-01-10 14:24:24 -080010938 public void setOemNetworkPreference(
10939 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010940 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010941
James Mattisfa270db2021-05-31 17:11:10 -070010942 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10943 // Only bypass the permission/device checks if this is a valid test request.
10944 if (isValidTestOemNetworkPreference(preference)) {
10945 enforceManageTestNetworksPermission();
10946 } else {
10947 enforceAutomotiveDevice();
10948 enforceOemNetworkPreferencesPermission();
10949 validateOemNetworkPreferences(preference);
10950 }
James Mattis45d81842021-01-10 14:24:24 -080010951
James Mattis45d81842021-01-10 14:24:24 -080010952 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10953 new Pair<>(preference, listener)));
10954 }
10955
James Mattisfa270db2021-05-31 17:11:10 -070010956 /**
10957 * Check the validity of an OEM network preference to be used for testing purposes.
10958 * @param preference the preference to validate
10959 * @return true if this is a valid OEM network preference test request.
10960 */
10961 private boolean isValidTestOemNetworkPreference(
10962 @NonNull final OemNetworkPreferences preference) {
10963 // Allow for clearing of an existing OemNetworkPreference used for testing.
10964 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10965 // changes after this check is complete. This is an unlikely scenario as calling of this API
10966 // is controlled by the OEM therefore the added complexity is not worth adding given those
10967 // circumstances. That said, it is an edge case to be aware of hence this comment.
10968 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10969 && isTestOemNetworkPreference(mOemNetworkPreferences);
10970 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10971 }
10972
10973 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10974 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10975 return prefMap.size() == 1
10976 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10977 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10978 }
10979
James Mattis45d81842021-01-10 14:24:24 -080010980 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10981 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10982 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010983 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10984 throw new IllegalArgumentException(
10985 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10986 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010987 }
10988 }
10989 }
10990
10991 private void handleSetOemNetworkPreference(
10992 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010993 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010994 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10995 if (DBG) {
10996 log("set OEM network preferences :" + preference.toString());
10997 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010998
James Mattiscb1e0362021-04-06 17:07:42 -070010999 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011000 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11001 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11002 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011003 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011004
11005 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011006 try {
11007 listener.onComplete();
11008 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011009 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011010 }
James Mattis45d81842021-01-10 14:24:24 -080011011 }
11012 }
11013
paulhu74128522021-09-28 02:29:03 +000011014 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011015 // Skip the requests which are set by other network preference. Because the uid range rules
11016 // should stay in netd.
11017 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011018 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011019 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011020 }
11021
James Mattis3ce3d3c2021-02-09 18:18:28 -080011022 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11023 ensureRunningOnConnectivityServiceThread();
11024 mDefaultNetworkRequests.addAll(nris);
11025 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11026 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011027 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011028 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11029 nrisToRegister.addAll(
11030 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11031 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011032 }
11033
11034 /**
11035 * All current requests that are tracking the default network need to be assessed as to whether
11036 * or not the current set of per-application default requests will be changing their default
11037 * network. If so, those requests will need to be updated so that they will send callbacks for
11038 * default network changes at the appropriate time. Additionally, those requests tracking the
11039 * default that were previously updated by this flow will need to be reassessed.
11040 * @return the nris which will need to be updated.
11041 */
11042 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11043 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11044 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11045 // same nri in the map's values for each of its NetworkRequest objects.
11046 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011047 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011048 // Include this nri if it is currently being tracked.
11049 if (isPerAppTrackedNri(nri)) {
11050 defaultCallbackRequests.add(nri);
11051 continue;
11052 }
11053 // We only track callbacks for requests tracking the default.
11054 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11055 continue;
11056 }
11057 // Include this nri if it will be tracked by the new per-app default requests.
11058 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011059 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011060 if (isNriGoingToBeTracked) {
11061 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011062 }
11063 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011064 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011065 }
11066
James Mattis3ce3d3c2021-02-09 18:18:28 -080011067 /**
11068 * Create nris for those network requests that are currently tracking the default network that
11069 * are being controlled by a per-application default.
11070 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11071 * foundation when creating the nri. Important items include the calling uid's original
11072 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11073 * requests are assumed to have already been validated as needing to be updated.
11074 * @return the Set of nris to use when registering network requests.
11075 */
11076 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11077 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11078 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11079 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11080 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011081 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011082
Chalard Jean9473c982021-07-29 20:03:04 +090011083 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011084 if (trackingNri == mDefaultRequest) {
11085 callbackRequestsToRegister.add(new NetworkRequestInfo(
11086 callbackRequest,
11087 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11088 continue;
11089 }
11090
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011091 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011092 callbackRequestsToRegister.add(new NetworkRequestInfo(
11093 callbackRequest,
11094 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011095 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011096 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011097 }
11098 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011099 }
11100
Chalard Jean17215832021-03-01 14:06:28 +090011101 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11102 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011103 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011104 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011105 }
11106 }
11107
James Mattis45d81842021-01-10 14:24:24 -080011108 /**
11109 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11110 */
11111 @VisibleForTesting
11112 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011113 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011114 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011115 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011116 final SparseArray<Set<Integer>> uids =
11117 createUidsFromOemNetworkPreferences(preference);
11118 for (int i = 0; i < uids.size(); i++) {
11119 final int key = uids.keyAt(i);
11120 final Set<Integer> value = uids.valueAt(i);
11121 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11122 // No need to add an nri without any requests.
11123 if (0 == nri.mRequests.size()) {
11124 continue;
11125 }
11126 nris.add(nri);
11127 }
11128
11129 return nris;
11130 }
11131
11132 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11133 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011134 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011135 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011136 final List<UserHandle> users =
11137 mContext.getSystemService(UserManager.class).getUserHandles(true);
11138 if (null == users || users.size() == 0) {
11139 if (VDBG || DDBG) {
11140 log("No users currently available for setting the OEM network preference.");
11141 }
James Mattisb6b6a432021-06-01 22:30:36 -070011142 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011143 }
James Mattis45d81842021-01-10 14:24:24 -080011144 for (final Map.Entry<String, Integer> entry :
11145 preference.getNetworkPreferences().entrySet()) {
11146 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011147 // Add the rules for all users as this policy is device wide.
11148 for (final UserHandle user : users) {
11149 try {
11150 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11151 if (!prefToUids.contains(pref)) {
11152 prefToUids.put(pref, new ArraySet<>());
11153 }
11154 prefToUids.get(pref).add(uid);
11155 } catch (PackageManager.NameNotFoundException e) {
11156 // Although this may seem like an error scenario, it is ok that uninstalled
11157 // packages are sent on a network preference as the system will watch for
11158 // package installations associated with this network preference and update
11159 // accordingly. This is done to minimize race conditions on app install.
11160 continue;
James Mattis45d81842021-01-10 14:24:24 -080011161 }
James Mattis45d81842021-01-10 14:24:24 -080011162 }
11163 }
James Mattisb6b6a432021-06-01 22:30:36 -070011164 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011165 }
11166
11167 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11168 @OemNetworkPreferences.OemNetworkPreference final int preference,
11169 @NonNull final Set<Integer> uids) {
11170 final List<NetworkRequest> requests = new ArrayList<>();
11171 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11172 switch (preference) {
11173 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11174 requests.add(createUnmeteredNetworkRequest());
11175 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011176 requests.add(createDefaultInternetRequestForTransport(
11177 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011178 break;
11179 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11180 requests.add(createUnmeteredNetworkRequest());
11181 requests.add(createOemPaidNetworkRequest());
11182 break;
11183 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11184 requests.add(createOemPaidNetworkRequest());
11185 break;
11186 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11187 requests.add(createOemPrivateNetworkRequest());
11188 break;
James Mattisfa270db2021-05-31 17:11:10 -070011189 case OEM_NETWORK_PREFERENCE_TEST:
11190 requests.add(createUnmeteredNetworkRequest());
11191 requests.add(createTestNetworkRequest());
11192 requests.add(createDefaultRequest());
11193 break;
11194 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11195 requests.add(createTestNetworkRequest());
11196 break;
James Mattis45d81842021-01-10 14:24:24 -080011197 default:
11198 // This should never happen.
11199 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11200 + " called with invalid preference of " + preference);
11201 }
11202
James Mattisfa270db2021-05-31 17:11:10 -070011203 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011204 for (final int uid : uids) {
11205 ranges.add(new UidRange(uid, uid));
11206 }
11207 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011208 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011209 }
11210
11211 private NetworkRequest createUnmeteredNetworkRequest() {
11212 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11213 .addCapability(NET_CAPABILITY_NOT_METERED)
11214 .addCapability(NET_CAPABILITY_VALIDATED);
11215 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11216 }
11217
11218 private NetworkRequest createOemPaidNetworkRequest() {
11219 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11220 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11221 .addCapability(NET_CAPABILITY_OEM_PAID)
11222 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11223 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11224 }
11225
11226 private NetworkRequest createOemPrivateNetworkRequest() {
11227 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11228 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11229 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11230 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11231 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11232 }
11233
11234 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011235 final NetworkCapabilities netcap = new NetworkCapabilities();
11236 netcap.addCapability(NET_CAPABILITY_INTERNET);
11237 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11238 return netcap;
11239 }
11240
11241 private NetworkRequest createTestNetworkRequest() {
11242 final NetworkCapabilities netcap = new NetworkCapabilities();
11243 netcap.clearAll();
11244 netcap.addTransportType(TRANSPORT_TEST);
11245 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011246 }
James Mattis47db0582021-01-01 14:13:35 -080011247 }
markchien738ad912021-12-09 18:15:45 +080011248
11249 @Override
11250 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11251 enforceNetworkStackOrSettingsPermission();
11252
11253 try {
11254 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011255 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011256 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011257 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011258 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011259 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011260 throw new IllegalStateException(e);
11261 }
11262 }
11263
11264 @Override
11265 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11266 enforceNetworkStackOrSettingsPermission();
11267
11268 try {
11269 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011270 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011271 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011272 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011273 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011274 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011275 throw new IllegalStateException(e);
11276 }
11277 }
markchiene1561fa2021-12-09 22:00:56 +080011278
11279 @Override
markchien3c04e662022-03-22 16:29:56 +080011280 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011281 enforceNetworkStackOrSettingsPermission();
11282
markchien3c04e662022-03-22 16:29:56 +080011283 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11284 int firewallRule = getFirewallRuleType(chain, rule);
11285
11286 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11287 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11288 }
11289
markchiene1561fa2021-12-09 22:00:56 +080011290 try {
markchien3c04e662022-03-22 16:29:56 +080011291 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011292 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011293 throw new IllegalStateException(e);
11294 }
11295 }
markchien98a6f952022-01-13 23:43:53 +080011296
markchien3c04e662022-03-22 16:29:56 +080011297 private int getFirewallRuleType(int chain, int rule) {
11298 final int defaultRule;
11299 switch (chain) {
11300 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011301 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11302 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011303 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011304 defaultRule = FIREWALL_RULE_ALLOW;
11305 break;
11306 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11307 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11308 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11309 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11310 defaultRule = FIREWALL_RULE_DENY;
11311 break;
11312 default:
11313 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11314 }
11315 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11316
11317 return rule;
11318 }
11319
markchien98a6f952022-01-13 23:43:53 +080011320 @Override
11321 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11322 enforceNetworkStackOrSettingsPermission();
11323
11324 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011325 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011326 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011327 throw new IllegalStateException(e);
11328 }
11329 }
11330
markchien00a0bed2022-01-13 23:46:13 +080011331 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011332 public boolean getFirewallChainEnabled(final int chain) {
11333 enforceNetworkStackOrSettingsPermission();
11334
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011335 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011336 }
11337
11338 @Override
markchien00a0bed2022-01-13 23:46:13 +080011339 public void replaceFirewallChain(final int chain, final int[] uids) {
11340 enforceNetworkStackOrSettingsPermission();
11341
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011342 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011343 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011344}