blob: cb209e8ae7b21254801579e766f33a609de910e0 [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
Chalard Jean5fb43c72022-09-08 19:03:14 +0900356 // How long to wait before considering that a network is bad in the absence of any form
357 // of connectivity (valid, partial, captive portal). If none has been detected after this
358 // delay, the stack considers this network bad, which may affect how it's handled in ranking
359 // according to config_networkAvoidBadWifi.
360 private static final int INITIAL_EVALUATION_TIMEOUT_MS = 20 * 1000;
361
junyulai0ac374f2020-12-14 18:41:52 +0800362 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900363 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
364 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800365 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700366
he_won.hwang881307a2022-03-15 21:23:52 +0900367 // The maximum value for the blocking validation result, in milliseconds.
368 public static final int MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS = 10000;
369
Daniel Brightf9e945b2020-06-15 16:10:01 -0700370 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900371 @VisibleForTesting
372 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700373
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900374 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700375 @VisibleForTesting
376 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900377
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900378 @VisibleForTesting
379 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800380 @VisibleForTesting
381 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900382 // True if the cell radio of the device is capable of time-sharing.
383 @VisibleForTesting
384 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900385
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800386 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800387 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800388 private final int mReleasePendingIntentDelayMs;
389
Chalard Jean46bfbf02022-02-02 00:56:25 +0900390 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900391
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000392 @VisibleForTesting
393 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700394
Chalard Jean9473c982021-07-29 20:03:04 +0900395 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800396 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700397 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800398 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700399
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900400 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700401
junyulaif2c67e42018-08-07 19:50:45 +0800402 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000403 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
404 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800405 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900406 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800407
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900408 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900409 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000410 // The Context is created for UserHandle.ALL.
411 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900412 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900413 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700414 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700415 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800416
Chenbo Feng15416292018-11-08 17:36:21 -0800417 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800418 protected IDnsResolver mDnsResolver;
419 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800420 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700421 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900422 private final NetworkStatsManager mStatsManager;
423 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800424 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700425
Benedict Wong493e04b2018-11-09 14:45:34 -0800426 /**
427 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
428 * instances.
429 */
430 @GuardedBy("mTNSLock")
431 private TestNetworkService mTNS;
432
433 private final Object mTNSLock = new Object();
434
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700435 private String mCurrentTcpBufferSizes;
436
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900437 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800438 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900439
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500440 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400441 // Tear down networks that have no chance (e.g. even if validated) of becoming
442 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500443 // all networks have been rematched against all NetworkRequests.
444 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400445 // Don't reap networks. This should be passed when some networks have not yet been
446 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500447 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900448 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500449
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900450 private enum UnneededFor {
451 LINGER, // Determine whether this network is unneeded and should be lingered.
452 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
453 }
454
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700455 /**
paulhuaa0743d2021-05-26 21:56:03 +0800456 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800457 * should have priority. The order is passed to netd which will use it together
458 * with UID ranges to generate the corresponding IP rule. This serves to
459 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800460 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800461 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000462 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800463 *
paulhu48291862021-07-14 14:53:57 +0800464 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
465 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800466 */
paulhu48291862021-07-14 14:53:57 +0800467 // Used when sending to netd to code for "no order".
468 static final int PREFERENCE_ORDER_NONE = 0;
469 // Order for requests that don't code for a per-app preference. As it is
470 // out of the valid range, the corresponding order should be
471 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800472 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800473 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800474 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800475 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
476 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800477 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800478 static final int PREFERENCE_ORDER_OEM = 10;
479 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800480 // See {@link #setProfileNetworkPreference}.
481 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800482 static final int PREFERENCE_ORDER_PROFILE = 20;
483 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800484 // better scores are connected.
485 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800486 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800487 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900488 // Preference order that signifies the network shouldn't be set as a default network for
489 // the UIDs, only give them access to it. TODO : replace this with a boolean
490 // in NativeUidRangeConfig
491 @VisibleForTesting
492 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
493 // Bound for the lowest valid preference order.
494 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800495
496 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700497 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700498 * from one net to another. Clear happens when we get a new
499 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
500 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700501 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700502 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700503
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700504 /**
505 * used internally to reload global proxy settings
506 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700507 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700508
Robert Greenwalt34848c02011-03-25 13:09:25 -0700509 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400510 * PAC manager has received new port.
511 */
512 private static final int EVENT_PROXY_HAS_CHANGED = 16;
513
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700514 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900515 * used internally when registering NetworkProviders
516 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700517 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900518 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700519
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700520 /**
521 * used internally when registering NetworkAgents
522 * obj = Messenger
523 */
524 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
525
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700526 /**
527 * used to add a network request
528 * includes a NetworkRequestInfo
529 */
530 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
531
532 /**
533 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900534 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700535 * cancel it.
536 * includes a NetworkRequestInfo
537 */
538 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
539
540 /**
541 * used to add a network listener - no request
542 * includes a NetworkRequestInfo
543 */
544 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
545
546 /**
547 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400548 * arg1 = UID of caller
549 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700550 */
551 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
552
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700553 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900554 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700555 * obj = Messenger
556 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900557 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700558
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700559 /**
560 * used internally to expire a wakelock when transitioning
561 * from one net to another. Expire happens when we fail to find
562 * a new network (typically after 1 minute) -
563 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
564 * a replacement network.
565 */
566 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
567
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700568 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800569 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400570 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800571 */
572 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
573
574 /**
575 * used to remove a pending intent and its associated network request.
576 * arg1 = UID of caller
577 * obj = PendingIntent
578 */
579 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
580
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900581 /**
582 * used to specify whether a network should be used even if unvalidated.
583 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
584 * arg2 = whether to remember this choice in the future (1 or 0)
585 * obj = network
586 */
587 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
588
589 /**
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 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900728 * The initial evaluation period is over for this network.
729 *
730 * If no form of connectivity has been found on this network (valid, partial, captive portal)
731 * then the stack will now consider it to have been determined bad.
732 */
733 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
734
735 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900736 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
737 * should be shown.
738 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900739 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900740
741 /**
742 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
743 * should be hidden.
744 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900745 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900746
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800747 /**
748 * The maximum alive time to allow bad wifi configuration for testing.
749 */
750 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
751
Patrick Rohr2857ac42022-01-21 14:58:16 +0100752 /**
753 * The priority of the tc police rate limiter -- smaller value is higher priority.
754 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
755 */
756 private static final short TC_PRIO_POLICE = 1;
757
758 /**
759 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
760 */
761 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700762 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100763
Hugo Benichi47011212017-03-30 10:46:05 +0900764 private static String eventName(int what) {
765 return sMagicDecoderRing.get(what, Integer.toString(what));
766 }
767
paulhua10d8212020-11-10 15:32:56 +0800768 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900769 final DnsResolverServiceManager dsm = context.getSystemService(
770 DnsResolverServiceManager.class);
771 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800772 }
773
Cody Kesting73708bf2019-12-18 10:57:50 -0800774 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900775 @VisibleForTesting
776 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700777 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700778 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700779 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700780 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800781 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
782 @VisibleForTesting
783 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
784
Erik Kline32120082017-12-13 19:40:49 +0900785 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900786 @VisibleForTesting
787 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700788
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400789 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800790 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400791
Chalard Jean46bfbf02022-02-02 00:56:25 +0900792 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800793 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700794
Chalard Jean5d70ba42018-06-07 16:44:04 +0900795 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
796 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000797 @VisibleForTesting
798 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400799
Erik Kline05f2b402015-04-30 12:58:40 +0900800 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700801
Chalard Jean46bfbf02022-02-02 00:56:25 +0900802 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400803
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700804 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900805 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700806
Valentin Iftime9fa35092019-09-24 13:32:13 +0200807 private Set<String> mWolSupportedInterfaces;
808
Roshan Pius08c94fb2020-01-16 12:17:17 -0800809 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800810 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800811 private final AppOpsManager mAppOpsManager;
812
813 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400814
Chalard Jean46bfbf02022-02-02 00:56:25 +0900815 private final KeepaliveTracker mKeepaliveTracker;
816 private final QosCallbackTracker mQosCallbackTracker;
817 private final NetworkNotificationManager mNotifier;
818 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900819
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700820 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800821 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700822
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900823 // Sequence number for NetworkProvider IDs.
824 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
825 NetworkProvider.FIRST_PROVIDER_ID);
826
Erik Klineedf878b2015-07-09 18:24:03 +0900827 // NetworkRequest activity String log entries.
828 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
829 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
830
Hugo Benichid159fdd2016-07-11 11:05:12 +0900831 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900832 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900833 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
834
Hugo Benichi47011212017-03-30 10:46:05 +0900835 private static final int MAX_WAKELOCK_LOGS = 20;
836 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900837 private int mTotalWakelockAcquisitions = 0;
838 private int mTotalWakelockReleases = 0;
839 private long mTotalWakelockDurationMs = 0;
840 private long mMaxWakelockDurationMs = 0;
841 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900842
Hugo Benichi208c0102016-07-28 17:53:06 +0900843 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900844
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700845 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900846 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700847
Erik Kline95ecfee2016-10-02 18:02:14 +0900848 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900849 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900850
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900851 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800852 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
853 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800854
Patrick Rohr2857ac42022-01-21 14:58:16 +0100855 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
856 // configured via {@link
857 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
858 // Only the handler thread is allowed to access this field.
859 private long mIngressRateLimit = -1;
860
Robert Greenwalt802c1102014-06-02 15:32:02 -0700861 /**
862 * Implements support for the legacy "one network per network type" model.
863 *
864 * We used to have a static array of NetworkStateTrackers, one for each
865 * network type, but that doesn't work any more now that we can have,
866 * for example, more that one wifi network. This class stores all the
867 * NetworkAgentInfo objects that support a given type, but the legacy
868 * API will only see the first one.
869 *
870 * It serves two main purposes:
871 *
872 * 1. Provide information about "the network for a given type" (since this
873 * API only supports one).
874 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
875 * the first network for a given type changes, or if the default network
876 * changes.
877 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900878 @VisibleForTesting
879 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900880
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900881 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900882 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900883
Robert Greenwalt802c1102014-06-02 15:32:02 -0700884 /**
885 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
886 * Each list holds references to all NetworkAgentInfos that are used to
887 * satisfy requests for that network type.
888 *
889 * This array is built out at startup such that an unsupported network
890 * doesn't get an ArrayList instance, making this a tristate:
891 * unsupported, supported but not active and active.
892 *
893 * The actual lists are populated when we scan the network types that
894 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900895 *
896 * Threading model:
897 * - addSupportedType() is only called in the constructor
898 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
899 * They are therefore not thread-safe with respect to each other.
900 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
901 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900902 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900903 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700904 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900905 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900906 @NonNull
907 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700908
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900909 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
910 // an entry have no timer (equivalent to -1). Lazily loaded.
911 @NonNull
912 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
913
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900914 LegacyTypeTracker(@NonNull ConnectivityService service) {
915 mService = service;
916 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700917 }
918
Chiachang Wang3bc52762021-11-25 14:17:57 +0800919 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
920 // addressed.
921 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900922 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
923 final PackageManager pm = ctx.getPackageManager();
924 if (pm.hasSystemFeature(FEATURE_WIFI)) {
925 addSupportedType(TYPE_WIFI);
926 }
927 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
928 addSupportedType(TYPE_WIFI_P2P);
929 }
930 if (tm.isDataCapable()) {
931 // Telephony does not have granular support for these types: they are either all
932 // supported, or none is supported
933 addSupportedType(TYPE_MOBILE);
934 addSupportedType(TYPE_MOBILE_MMS);
935 addSupportedType(TYPE_MOBILE_SUPL);
936 addSupportedType(TYPE_MOBILE_DUN);
937 addSupportedType(TYPE_MOBILE_HIPRI);
938 addSupportedType(TYPE_MOBILE_FOTA);
939 addSupportedType(TYPE_MOBILE_IMS);
940 addSupportedType(TYPE_MOBILE_CBS);
941 addSupportedType(TYPE_MOBILE_IA);
942 addSupportedType(TYPE_MOBILE_EMERGENCY);
943 }
944 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
945 addSupportedType(TYPE_BLUETOOTH);
946 }
947 if (pm.hasSystemFeature(FEATURE_WATCH)) {
948 // TYPE_PROXY is only used on Wear
949 addSupportedType(TYPE_PROXY);
950 }
951 // Ethernet is often not specified in the configs, although many devices can use it via
952 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000953 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900954 addSupportedType(TYPE_ETHERNET);
955 }
956
957 // Always add TYPE_VPN as a supported type
958 addSupportedType(TYPE_VPN);
959 }
960
961 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700962 if (mTypeLists[type] != null) {
963 throw new IllegalStateException(
964 "legacy list for type " + type + "already initialized");
965 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900966 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700967 }
968
Robert Greenwalt802c1102014-06-02 15:32:02 -0700969 public boolean isTypeSupported(int type) {
970 return isNetworkTypeValid(type) && mTypeLists[type] != null;
971 }
972
973 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900974 synchronized (mTypeLists) {
975 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
976 return mTypeLists[type].get(0);
977 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700978 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900979 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700980 }
981
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900982 public int getRestoreTimerForType(int type) {
983 synchronized (mTypeLists) {
984 if (mRestoreTimers == null) {
985 mRestoreTimers = loadRestoreTimers();
986 }
987 return mRestoreTimers.getOrDefault(type, -1);
988 }
989 }
990
991 private ArrayMap<Integer, Integer> loadRestoreTimers() {
992 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900993 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900994 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
995 for (final String config : configs) {
996 final String[] splits = TextUtils.split(config, ",");
997 if (splits.length != 2) {
998 logwtf("Invalid restore timer token count: " + config);
999 continue;
1000 }
1001 try {
1002 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1003 } catch (NumberFormatException e) {
1004 logwtf("Invalid restore timer number format: " + config, e);
1005 }
1006 }
1007 return ret;
1008 }
1009
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001010 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001011 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001012 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001013 log("Sending " + state
1014 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001015 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001016 }
1017 }
1018
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001019 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1020 // network type, to preserve previous behaviour.
1021 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1022 if (vpnNai != mService.getLegacyLockdownNai()) return;
1023
1024 if (vpnNai.declaredUnderlyingNetworks == null
1025 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1026 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1027 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1028 return;
1029 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001030 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001031 vpnNai.declaredUnderlyingNetworks[0]);
1032 if (underlyingNai == null) return;
1033
1034 final int type = underlyingNai.networkInfo.getType();
1035 final DetailedState state = DetailedState.CONNECTED;
1036 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1037 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1038 }
1039
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001040 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001041 public void add(int type, NetworkAgentInfo nai) {
1042 if (!isTypeSupported(type)) {
1043 return; // Invalid network type.
1044 }
1045 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1046
1047 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1048 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001049 return;
1050 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001051 synchronized (mTypeLists) {
1052 list.add(nai);
1053 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001054
Chalard Jean5b409c72021-02-04 13:12:59 +09001055 // Send a broadcast if this is the first network of its type or if it's the default.
1056 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001057
1058 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1059 // to preserve previous behaviour.
1060 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001061 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001062 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1063 mService.sendLegacyNetworkBroadcast(nai, state, type);
1064 }
1065
1066 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1067 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001068 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001069 }
1070
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001071 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001072 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001073 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1074 if (list == null || list.isEmpty()) {
1075 return;
1076 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001077 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001078
Hugo Benichi389633f2016-06-21 09:48:07 +09001079 synchronized (mTypeLists) {
1080 if (!list.remove(nai)) {
1081 return;
1082 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001083 }
1084
Lorenzo Colitti49767722015-05-01 00:30:10 +09001085 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001086 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1087 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001088 }
1089
1090 if (!list.isEmpty() && wasFirstNetwork) {
1091 if (DBG) log("Other network available for type " + type +
1092 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001093 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001094 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001095 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001096 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001097 }
1098 }
1099
1100 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001101 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1102 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001103 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001104 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001105 }
1106 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001107
Chalard Jean46bfbf02022-02-02 00:56:25 +09001108 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001109 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001110 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001111 final DetailedState state = nai.networkInfo.getDetailedState();
1112 for (int type = 0; type < mTypeLists.length; type++) {
1113 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001114 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001115 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001116 if (isFirst || contains && isDefault) {
1117 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001118 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001119 }
1120 }
1121 }
1122
Robert Greenwalt94e22142014-07-30 16:31:24 -07001123 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001124 pw.println("mLegacyTypeTracker:");
1125 pw.increaseIndent();
1126 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001127 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001128 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001129 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001130 pw.println();
1131 pw.println("Current state:");
1132 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001133 synchronized (mTypeLists) {
1134 for (int type = 0; type < mTypeLists.length; type++) {
1135 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1136 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001137 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001138 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001139 }
1140 }
1141 pw.decreaseIndent();
1142 pw.decreaseIndent();
1143 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001144 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001145 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001146 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001147
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001148 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001149 /**
1150 * Helper class which parses out priority arguments and dumps sections according to their
1151 * priority. If priority arguments are omitted, function calls the legacy dump command.
1152 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001153 private class LocalPriorityDump {
1154 private static final String PRIORITY_ARG = "--dump-priority";
1155 private static final String PRIORITY_ARG_HIGH = "HIGH";
1156 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1157
1158 LocalPriorityDump() {}
1159
1160 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1161 doDump(fd, pw, new String[] {DIAG_ARG});
1162 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001163 }
1164
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001165 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1166 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001167 }
1168
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001169 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1170 if (args == null) {
1171 dumpNormal(fd, pw, args);
1172 return;
1173 }
1174
1175 String priority = null;
1176 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1177 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1178 argIndex++;
1179 priority = args[argIndex];
1180 }
1181 }
1182
1183 if (PRIORITY_ARG_HIGH.equals(priority)) {
1184 dumpHigh(fd, pw);
1185 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1186 dumpNormal(fd, pw, args);
1187 } else {
1188 // ConnectivityService publishes binder service using publishBinderService() with
1189 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001190 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1191 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001192 // TODO: Integrate into signal dump.
1193 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001194 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001195 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001196 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001197
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001198 /**
1199 * Dependencies of ConnectivityService, for injection in tests.
1200 */
1201 @VisibleForTesting
1202 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001203 public int getCallingUid() {
1204 return Binder.getCallingUid();
1205 }
1206
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001207 /**
1208 * Get system properties to use in ConnectivityService.
1209 */
1210 public MockableSystemProperties getSystemProperties() {
1211 return new MockableSystemProperties();
1212 }
1213
1214 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001215 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1216 */
1217 public ConnectivityResources getResources(@NonNull Context ctx) {
1218 return new ConnectivityResources(ctx);
1219 }
1220
1221 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001222 * Create a HandlerThread to use in ConnectivityService.
1223 */
1224 public HandlerThread makeHandlerThread() {
1225 return new HandlerThread("ConnectivityServiceThread");
1226 }
1227
1228 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001229 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001230 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001231 public NetworkStackClientBase getNetworkStack() {
1232 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001233 }
1234
1235 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001236 * @see ProxyTracker
1237 */
1238 public ProxyTracker makeProxyTracker(@NonNull Context context,
1239 @NonNull Handler connServiceHandler) {
1240 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1241 }
1242
1243 /**
1244 * @see NetIdManager
1245 */
1246 public NetIdManager makeNetIdManager() {
1247 return new NetIdManager();
1248 }
1249
1250 /**
1251 * @see NetworkUtils#queryUserAccess(int, int)
1252 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001253 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1254 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001255 }
1256
1257 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001258 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1259 * requires CAP_NET_ADMIN, which the unit tests do not have.
1260 */
1261 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1262 InetSocketAddress remote) {
1263 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1264 }
1265
1266 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001267 * @see MultinetworkPolicyTracker
1268 */
1269 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1270 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1271 return new MultinetworkPolicyTracker(c, h, r);
1272 }
1273
Aaron Huang330a4c02020-10-27 03:36:19 +08001274 /**
1275 * @see BatteryStatsManager
1276 */
1277 public void reportNetworkInterfaceForTransports(Context context, String iface,
1278 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001279 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001280 context.getSystemService(BatteryStatsManager.class);
1281 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1282 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001283
1284 public boolean getCellular464XlatEnabled() {
1285 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1286 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001287
1288 /**
1289 * @see PendingIntent#intentFilterEquals
1290 */
1291 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1292 return a.intentFilterEquals(b);
1293 }
1294
1295 /**
1296 * @see LocationPermissionChecker
1297 */
1298 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1299 return new LocationPermissionChecker(context);
1300 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001301
1302 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001303 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001304 *
1305 * This method returns null in versions before T, where carrier privilege
1306 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001307 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001308 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001309 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1310 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1311 if (SdkLevel.isAtLeastT()) {
1312 return new CarrierPrivilegeAuthenticator(context, tm);
1313 } else {
1314 return null;
1315 }
1316 }
1317
1318 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001319 * @see DeviceConfigUtils#isFeatureEnabled
1320 */
1321 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1322 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1323 TETHERING_MODULE_NAME, defaultEnabled);
1324 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001325
1326 /**
1327 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001328 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001329 * @return BpfNetMaps implementation.
1330 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001331 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1332 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001333 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001334
1335 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001336 * @see ClatCoordinator
1337 */
1338 public ClatCoordinator getClatCoordinator(INetd netd) {
1339 return new ClatCoordinator(
1340 new ClatCoordinator.Dependencies() {
1341 @NonNull
1342 public INetd getNetd() {
1343 return netd;
1344 }
1345 });
1346 }
1347
1348 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001349 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1350 */
1351 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1352 final InterfaceParams params = InterfaceParams.getByName(iface);
1353 if (params == null) {
1354 // the interface might have disappeared.
1355 logw("Failed to get interface params for interface " + iface);
1356 return;
1357 }
1358 try {
1359 // converting rateInBytesPerSecond from long to int is safe here because the
1360 // setting's range is limited to INT_MAX.
1361 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001362 Log.i(TAG,
1363 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001364 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1365 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1366 } catch (IOException e) {
1367 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1368 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1369 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1370 + ") failure: ", e);
1371 }
1372 }
1373
1374 /**
1375 * Wraps {@link TcUtils#tcFilterDelDev}
1376 */
1377 public void disableIngressRateLimit(String iface) {
1378 final InterfaceParams params = InterfaceParams.getByName(iface);
1379 if (params == null) {
1380 // the interface might have disappeared.
1381 logw("Failed to get interface params for interface " + iface);
1382 return;
1383 }
1384 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001385 Log.i(TAG,
1386 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001387 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1388 } catch (IOException e) {
1389 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1390 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1391 }
1392 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001393 }
1394
junyulaie7c7d2a2021-01-26 15:29:15 +08001395 public ConnectivityService(Context context) {
1396 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001397 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1398 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001399 }
1400
1401 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001402 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1403 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001404 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001405
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001406 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001407 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001408 mSystemProperties = mDeps.getSystemProperties();
1409 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001410 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001411 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001412 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1413 // Pass limit - 1 to maintain backward compatibility.
1414 // TODO: Remove the workaround.
1415 mNetworkRequestCounter =
1416 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1417 mSystemNetworkRequestCounter =
1418 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001419
Hugo Benichi208c0102016-07-28 17:53:06 +09001420 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001421 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1422 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001423 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001424 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001425 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001426 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1427 mDefaultNetworkRequests.add(mDefaultRequest);
1428 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001429
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001430 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001431 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001432
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001433 // The default WiFi request is a background request so that apps using WiFi are
1434 // migrated to a better network (typically ethernet) when one comes up, instead
1435 // of staying on WiFi forever.
1436 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1437 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1438
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001439 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1440 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1441 NetworkRequest.Type.BACKGROUND_REQUEST);
1442
Chalard Jean0702f982021-09-16 21:50:07 +09001443 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1444 // TODO: Consider making the timer customizable.
1445 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1446 mCellularRadioTimesharingCapable =
1447 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1448
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001449 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001450 mHandlerThread.start();
1451 mHandler = new InternalHandler(mHandlerThread.getLooper());
1452 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001453 mConnectivityDiagnosticsHandler =
1454 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001455
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001456 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001457 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001458
junyulaie7c7d2a2021-01-26 15:29:15 +08001459 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001460 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001461 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001462 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001463
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001464 mNetd = netd;
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001465 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001466 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001467 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001468 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001469 mCarrierPrivilegeAuthenticator =
1470 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001471
Sudheer Shanka9967d462021-03-18 19:09:25 +00001472 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001473 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1474 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001475 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001476
1477 final PowerManager powerManager = (PowerManager) context.getSystemService(
1478 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001479 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001480 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001481
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001482 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1483 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001484 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001485 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001486 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001487 mProtectedNetworks.add(p);
1488 } else {
1489 if (DBG) loge("Ignoring protectedNetwork " + p);
1490 }
1491 }
1492
soma, kawata29444ae2019-05-23 09:30:40 +09001493 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1494
Wayne Ma2fde98c2022-01-17 18:04:05 +08001495 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001496
James Mattis02220e22021-03-13 19:27:21 -08001497 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001498 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001499 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001500 final IntentFilter userIntentFilter = new IntentFilter();
1501 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1502 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1503 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1504 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001505
James Mattis02220e22021-03-13 19:27:21 -08001506 // Listen to package add/removes for netd
1507 final IntentFilter packageIntentFilter = new IntentFilter();
1508 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1509 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1510 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1511 packageIntentFilter.addDataScheme("package");
1512 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001513 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001514
lucaslind5c2d072021-02-20 18:59:47 +08001515 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001516
Chalard Jean46bfbf02022-02-02 00:56:25 +09001517 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001518 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001519 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001520 } catch (RemoteException | ServiceSpecificException e) {
1521 loge("Error registering event listener :" + e);
1522 }
1523
Erik Kline05f2b402015-04-30 12:58:40 +09001524 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1525 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001526
junyulai7e06ad42019-03-04 22:45:36 +08001527 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001528 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001529 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001530
1531 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001532 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001533 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1534 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001535 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001536 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1537 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001538
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001539 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001540 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001541 mNetworkRanker =
1542 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1543
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001544 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001545
Chiachang Wangc1215d32020-10-20 15:38:58 +08001546 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001547 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001548
Chalard Jean28018572020-12-21 18:36:52 +09001549 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1550 // request that doesn't allow fallback to the default network. It should never be visible
1551 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1552 // arguments like the handler or the DnsResolver.
1553 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001554 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001555 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001556 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001557 new LinkProperties(), new NetworkCapabilities(),
1558 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001559 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1560 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001561
1562 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001563 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1564 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1565 // Even if it could, running on S would at least require mocking out the BPF map,
1566 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1567 // the bpf syscall. http://aosp/1907693
1568 if (SdkLevel.isAtLeastT()) {
1569 mDscpPolicyTracker = new DscpPolicyTracker();
1570 }
Tyler Wear72388212021-09-09 14:49:02 -07001571 } catch (ErrnoException e) {
1572 loge("Unable to create DscpPolicyTracker");
1573 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001574
1575 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1576 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001577 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001578
Xiao Ma0a171c02022-01-23 16:14:51 +00001579 /**
1580 * Check whether or not the device supports Ethernet transport.
1581 */
1582 public static boolean deviceSupportsEthernet(final Context context) {
1583 final PackageManager pm = context.getPackageManager();
1584 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1585 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1586 }
1587
Chalard Jean46adcf32018-04-18 20:18:38 +09001588 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001589 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1590 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001591 }
1592
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001593 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1594 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001595 final NetworkCapabilities netCap = new NetworkCapabilities();
1596 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001597 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001598 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001599 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001600 return netCap;
1601 }
1602
James Mattis45d81842021-01-10 14:24:24 -08001603 private NetworkRequest createDefaultRequest() {
1604 return createDefaultInternetRequestForTransport(
1605 TYPE_NONE, NetworkRequest.Type.REQUEST);
1606 }
1607
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001608 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001609 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001610 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001611 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001612 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001613 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001614 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001615 netCap.addTransportType(transportType);
1616 }
James Mattis45d81842021-01-10 14:24:24 -08001617 return createNetworkRequest(type, netCap);
1618 }
1619
1620 private NetworkRequest createNetworkRequest(
1621 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001622 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001623 }
1624
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001625 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1626 NetworkRequest.Type type) {
1627 final NetworkCapabilities netCap = new NetworkCapabilities();
1628 netCap.clearAll();
1629 netCap.addCapability(capability);
1630 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1631 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1632 }
1633
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001634 // Used only for testing.
1635 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001636 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001637 // changing ContentResolver to make registerContentObserver non-final).
1638 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1639 // by subclassing SettingsObserver.
1640 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001641 void updateAlwaysOnNetworks() {
1642 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001643 }
1644
Erik Kline9a62f012018-03-21 07:18:33 -07001645 // See FakeSettingsProvider comment above.
1646 @VisibleForTesting
1647 void updatePrivateDnsSettings() {
1648 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1649 }
1650
paulhu51f77dc2021-06-07 02:34:20 +00001651 @VisibleForTesting
1652 void updateMobileDataPreferredUids() {
1653 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1654 }
1655
Patrick Rohr2857ac42022-01-21 14:58:16 +01001656 @VisibleForTesting
1657 void updateIngressRateLimit() {
1658 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1659 }
1660
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001661 private void handleAlwaysOnNetworkRequest(
1662 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001663 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001664 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001665 handleAlwaysOnNetworkRequest(networkRequest, enable);
1666 }
1667
1668 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001669 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001670 if (enable == isEnabled) {
1671 return; // Nothing to do.
1672 }
1673
1674 if (enable) {
1675 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001676 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001677 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001678 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001679 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001680 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1681 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001682 }
1683 }
1684
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001685 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001686 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1687 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1688 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1689 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001690 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1691 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001692 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001693 }
1694
paulhu51f77dc2021-06-07 02:34:20 +00001695 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001696 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001697 private void registerSettingsCallbacks() {
1698 // Watch for global HTTP proxy changes.
1699 mSettingsObserver.observe(
1700 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1701 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1702
Chalard Jean46bfbf02022-02-02 00:56:25 +09001703 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001704 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001705 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001706 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1707
Chalard Jean46bfbf02022-02-02 00:56:25 +09001708 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001709 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001710 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001711 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001712
1713 // Watch for mobile data preferred uids changes.
1714 mSettingsObserver.observe(
1715 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1716 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001717
1718 // Watch for ingress rate limit changes.
1719 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001720 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001721 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1722 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001723 }
1724
Erik Kline31b4a9e2018-01-11 21:07:29 +09001725 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001726 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1727 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001728 }
1729 }
1730
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001731 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001732 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1733 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001734 return mNextNetworkRequestId++;
1735 }
1736
junyulai74f9a8b2018-06-13 15:00:37 +08001737 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001738 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001739 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001740 if (network == null) {
1741 return null;
1742 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001743 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001744 }
1745
1746 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001747 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001748 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001749 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001750 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001751
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001752 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001753 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001754 private NetworkAgentInfo getVpnForUid(int uid) {
1755 synchronized (mNetworkForNetId) {
1756 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1757 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001758 if (nai.isVPN() && nai.everConnected()
1759 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001760 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001761 }
1762 }
1763 }
1764 return null;
1765 }
1766
Chalard Jean46bfbf02022-02-02 00:56:25 +09001767 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001768 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001769 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001770 final NetworkAgentInfo nai = getVpnForUid(uid);
1771 if (nai != null) return nai.declaredUnderlyingNetworks;
1772 return null;
1773 }
1774
Lorenzo Colittia7574052021-01-19 01:33:05 +09001775 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001776 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001777
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001778 final Network[] networks = getVpnUnderlyingNetworks(uid);
1779 if (networks != null) {
1780 // getUnderlyingNetworks() returns:
1781 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1782 // empty array => the VPN explicitly said "no default network".
1783 // non-empty array => the VPN specified one or more default networks; we use the
1784 // first one.
1785 if (networks.length > 0) {
1786 nai = getNetworkAgentInfoForNetwork(networks[0]);
1787 } else {
1788 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001789 }
1790 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001791 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001792 }
1793
1794 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001795 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001796 */
paulhu7aeba372020-12-30 00:42:19 +08001797 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1798 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001799 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001800 if (ignoreBlocked) {
1801 return false;
1802 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001803 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001804 final long ident = Binder.clearCallingIdentity();
1805 try {
1806 final boolean metered = nc == null ? true : nc.isMetered();
1807 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1808 } finally {
1809 Binder.restoreCallingIdentity(ident);
1810 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001811 }
1812
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001813 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001814 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1815 return;
1816 }
Hugo Benichi47011212017-03-30 10:46:05 +09001817 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001818 synchronized (mBlockedAppUids) {
1819 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001820 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001821 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001822 blocked = false;
1823 } else {
1824 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001825 }
1826 }
Hugo Benichi47011212017-03-30 10:46:05 +09001827 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1828 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1829 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001830 }
1831
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001832 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001833 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1834 return;
1835 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001836 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001837 final int requestId = nri.getActiveRequest() != null
1838 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001839 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001840 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001841 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001842 }
1843
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001844 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001845 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001846 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001847 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001848 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001849 @NonNull
1850 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1851 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001852 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1853 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1854 // but only exists if an app asks about them or requests them. Ensure the requesting app
1855 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001856 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001857 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1858 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1859 null /* extraInfo */);
1860 }
1861 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001862 return filtered;
1863 }
1864
1865 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1866 boolean ignoreBlocked) {
1867 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1868 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001869 }
1870
1871 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001872 * Return NetworkInfo for the active (i.e., connected) network interface.
1873 * It is assumed that at most one network is active at a time. If more
1874 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001875 * @return the info for the active network, or {@code null} if none is
1876 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001877 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001878 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001879 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001880 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001881 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001882 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001883 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1884 if (nai == null) return null;
1885 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1886 maybeLogBlockedNetworkInfo(networkInfo, uid);
1887 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001888 }
1889
Paul Jensen1f567382015-02-13 14:18:39 -05001890 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001891 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001892 public Network getActiveNetwork() {
1893 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001894 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001895 }
1896
1897 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001898 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001899 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001900 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001901 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001902 }
1903
Chalard Jean46bfbf02022-02-02 00:56:25 +09001904 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001905 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001906 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1907 if (vpnNai != null) {
1908 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1909 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1910 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001911 }
Paul Jensen1f567382015-02-13 14:18:39 -05001912 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001913
James Mattis2516da32021-01-31 17:06:19 -08001914 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001915 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1916 ignoreBlocked)) {
1917 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001918 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001919 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001920 }
1921
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001922 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001923 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001924 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001925 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001926 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1927 if (nai == null) return null;
1928 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001929 }
1930
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001931 /** Returns a NetworkInfo object for a network that doesn't exist. */
1932 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1933 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1934 getNetworkTypeName(networkType), "" /* subtypeName */);
1935 info.setIsAvailable(true);
1936 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1937 // background data is restricted.
1938 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1939 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1940 ? DetailedState.BLOCKED
1941 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001942 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1943 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001944 return info;
1945 }
1946
Lorenzo Colittia7574052021-01-19 01:33:05 +09001947 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001948 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1949 return null;
1950 }
1951 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001952 if (nai == null) {
1953 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001954 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001955 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1956 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001957 }
1958
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001959 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001960 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001961 public NetworkInfo getNetworkInfo(int networkType) {
1962 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001963 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001964 if (getVpnUnderlyingNetworks(uid) != null) {
1965 // A VPN is active, so we may need to return one of its underlying networks. This
1966 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001967 // getNetworkAgentInfoForUid.
1968 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1969 if (nai == null) return null;
1970 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1971 if (networkInfo.getType() == networkType) {
1972 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001973 }
1974 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001975 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001976 }
1977
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001978 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001979 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001980 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001981 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001982 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001983 if (nai == null) return null;
1984 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001985 }
1986
1987 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001988 public NetworkInfo[] getAllNetworkInfo() {
1989 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001990 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001991 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1992 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001993 NetworkInfo info = getNetworkInfo(networkType);
1994 if (info != null) {
1995 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001996 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001997 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001998 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001999 }
2000
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002001 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002002 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002003 public Network getNetworkForType(int networkType) {
2004 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002005 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2006 return null;
2007 }
2008 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2009 if (nai == null) {
2010 return null;
2011 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002012 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002013 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2014 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002015 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002016 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002017 }
2018
2019 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002020 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002021 public Network[] getAllNetworks() {
2022 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002023 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002024 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002025 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002026 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002027 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002028 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002029 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002030 }
2031
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002032 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002033 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002034 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002035 // The basic principle is: if an app's traffic could possibly go over a
2036 // network, without the app doing anything multinetwork-specific,
2037 // (hence, by "default"), then include that network's capabilities in
2038 // the array.
2039 //
2040 // In the normal case, app traffic only goes over the system's default
2041 // network connection, so that's the only network returned.
2042 //
2043 // With a VPN in force, some app traffic may go into the VPN, and thus
2044 // over whatever underlying networks the VPN specifies, while other app
2045 // traffic may go over the system default network (e.g.: a split-tunnel
2046 // VPN, or an app disallowed by the VPN), so the set of networks
2047 // returned includes the VPN's underlying networks and the system
2048 // default.
2049 enforceAccessPermission();
2050
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002051 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002052
James Mattis2516da32021-01-31 17:06:19 -08002053 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2054 if (!nri.isBeingSatisfied()) {
2055 continue;
2056 }
2057 final NetworkAgentInfo nai = nri.getSatisfier();
2058 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2059 if (null != nc
2060 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2061 && !result.containsKey(nai.network)) {
2062 result.put(
2063 nai.network,
2064 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002065 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002066 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2067 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002068 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002069 }
2070
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002071 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002072 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002073 if (null != networks) {
2074 for (final Network network : networks) {
2075 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2076 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002077 result.put(
2078 network,
2079 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002080 nc,
2081 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002082 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002083 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002084 }
2085 }
2086 }
2087
2088 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2089 out = result.values().toArray(out);
2090 return out;
2091 }
2092
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002093 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002094 public boolean isNetworkSupported(int networkType) {
2095 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002096 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002097 }
2098
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002099 /**
2100 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002101 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002102 * @return the ip properties for the active network, or {@code null} if
2103 * none is active
2104 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002105 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002106 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002107 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002108 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002109 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2110 if (nai == null) return null;
2111 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002112 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002113 }
2114
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002115 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002116 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002117 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002118 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002119 final LinkProperties lp = getLinkProperties(nai);
2120 if (lp == null) return null;
2121 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002122 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002123 }
2124
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002125 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002126 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002127 public LinkProperties getLinkProperties(Network network) {
2128 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002129 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2130 if (lp == null) return null;
2131 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002132 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002133 }
2134
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002135 @Nullable
2136 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002137 if (nai == null) {
2138 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002139 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002140 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002141 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002142 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002143 }
2144
lucaslinc582d502022-01-27 09:07:00 +08002145 @Override
2146 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002147 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002148 @NonNull String packageName, @Nullable String callingAttributionTag) {
2149 Objects.requireNonNull(packageName);
2150 Objects.requireNonNull(lp);
2151 enforceNetworkStackOrSettingsPermission();
2152 if (!checkAccessPermission(-1 /* pid */, uid)) {
2153 return null;
2154 }
2155 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2156 }
2157
Qingxi Lib2748102020-01-08 12:51:49 -08002158 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2159 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2160 }
2161
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002162 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002163 if (nai == null) return null;
2164 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002165 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002166 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002167 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002168 }
2169
2170 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002171 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2172 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002173 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002174 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002175 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002176 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002177 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002178 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002179 }
2180
lucaslinc582d502022-01-27 09:07:00 +08002181 @Override
lucaslind2b06132022-03-02 10:56:57 +08002182 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2183 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2184 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002185 Objects.requireNonNull(nc);
2186 Objects.requireNonNull(packageName);
2187 enforceNetworkStackOrSettingsPermission();
2188 if (!checkAccessPermission(-1 /* pid */, uid)) {
2189 return null;
2190 }
2191 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2192 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2193 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2194 callingAttributionTag);
2195 }
2196
lucaslin69e1aa92022-03-22 18:15:09 +08002197 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2198 if (nc.getUnderlyingNetworks() != null
2199 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2200 nc.setUnderlyingNetworks(null);
2201 }
2202 }
2203
Qingxi Libb8da982020-01-17 17:54:27 -08002204 @VisibleForTesting
2205 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002206 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002207 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2208 // this would be expensive (one more permission check every time any NC callback is
2209 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2210 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2211 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002212 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002213 if (!checkSettingsPermission(callerPid, callerUid)) {
2214 newNc.setUids(null);
2215 newNc.setSSID(null);
2216 }
Etan Cohen107ae952018-12-30 17:59:59 -08002217 if (newNc.getNetworkSpecifier() != null) {
2218 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2219 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002220 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2221 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2222 newNc.setAdministratorUids(new int[0]);
2223 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002224 if (!checkAnyPermissionOf(
2225 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002226 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002227 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002228 }
lucaslin69e1aa92022-03-22 18:15:09 +08002229 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002230
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002231 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002232 }
2233
Roshan Pius98f59ec2021-02-23 08:47:39 -08002234 /**
2235 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002236 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002237 * NetworkCapabilities.
2238 * Note: This wrapper does not support any sort of invalidation and thus must not be
2239 * persistent or long-lived. It may only be used for the time necessary to
2240 * compute the redactions required by one particular NetworkCallback or
2241 * synchronous call.
2242 */
2243 private class RedactionPermissionChecker {
2244 private final int mCallingPid;
2245 private final int mCallingUid;
2246 @NonNull private final String mCallingPackageName;
2247 @Nullable private final String mCallingAttributionTag;
2248
2249 private Boolean mHasLocationPermission = null;
2250 private Boolean mHasLocalMacAddressPermission = null;
2251 private Boolean mHasSettingsPermission = null;
2252
2253 RedactionPermissionChecker(int callingPid, int callingUid,
2254 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2255 mCallingPid = callingPid;
2256 mCallingUid = callingUid;
2257 mCallingPackageName = callingPackageName;
2258 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002259 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002260
2261 private boolean hasLocationPermissionInternal() {
2262 final long token = Binder.clearCallingIdentity();
2263 try {
2264 return mLocationPermissionChecker.checkLocationPermission(
2265 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2266 null /* message */);
2267 } finally {
2268 Binder.restoreCallingIdentity(token);
2269 }
2270 }
2271
2272 /**
2273 * Returns whether the app holds location permission or not (might return cached result
2274 * if the permission was already checked before).
2275 */
2276 public boolean hasLocationPermission() {
2277 if (mHasLocationPermission == null) {
2278 // If there is no cached result, perform the check now.
2279 mHasLocationPermission = hasLocationPermissionInternal();
2280 }
2281 return mHasLocationPermission;
2282 }
2283
2284 /**
2285 * Returns whether the app holds local mac address permission or not (might return cached
2286 * result if the permission was already checked before).
2287 */
2288 public boolean hasLocalMacAddressPermission() {
2289 if (mHasLocalMacAddressPermission == null) {
2290 // If there is no cached result, perform the check now.
2291 mHasLocalMacAddressPermission =
2292 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2293 }
2294 return mHasLocalMacAddressPermission;
2295 }
2296
2297 /**
2298 * Returns whether the app holds settings permission or not (might return cached
2299 * result if the permission was already checked before).
2300 */
2301 public boolean hasSettingsPermission() {
2302 if (mHasSettingsPermission == null) {
2303 // If there is no cached result, perform the check now.
2304 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2305 }
2306 return mHasSettingsPermission;
2307 }
2308 }
2309
2310 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2311 @NetworkCapabilities.NetCapability long redaction) {
2312 return (redactions & redaction) != 0;
2313 }
2314
2315 /**
2316 * Use the provided |applicableRedactions| to check the receiving app's
2317 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2318 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2319 * before being sent to the corresponding app.
2320 */
2321 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2322 @NetworkCapabilities.RedactionType long applicableRedactions,
2323 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2324 boolean includeLocationSensitiveInfo) {
2325 long redactions = applicableRedactions;
2326 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2327 if (includeLocationSensitiveInfo
2328 && redactionPermissionChecker.hasLocationPermission()) {
2329 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2330 }
2331 }
2332 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2333 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2334 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2335 }
2336 }
2337 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2338 if (redactionPermissionChecker.hasSettingsPermission()) {
2339 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2340 }
2341 }
2342 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002343 }
2344
Qingxi Lib2748102020-01-08 12:51:49 -08002345 @VisibleForTesting
2346 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002347 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002348 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002349 int callingPid, int callingUid, @NonNull String callingPkgName,
2350 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002351 if (nc == null) {
2352 return null;
2353 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002354 // Avoid doing location permission check if the transport info has no location sensitive
2355 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002356 final RedactionPermissionChecker redactionPermissionChecker =
2357 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2358 callingAttributionTag);
2359 final long redactions = retrieveRequiredRedactions(
2360 nc.getApplicableRedactions(), redactionPermissionChecker,
2361 includeLocationSensitiveInfo);
2362 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002363 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002364 // TODO : calling UID is redacted because apps should generally not know what UID is
2365 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002366 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002367 newNc.setOwnerUid(INVALID_UID);
2368 return newNc;
2369 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002370 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2371 if (nc.hasTransport(TRANSPORT_VPN)) {
2372 // Owner UIDs already checked above. No need to re-check.
2373 return newNc;
2374 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002375 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2376 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002377 // compatibility for older apps.
2378 if (!includeLocationSensitiveInfo
2379 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002380 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002381 newNc.setOwnerUid(INVALID_UID);
2382 return newNc;
2383 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002384 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002385 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002386 newNc.setOwnerUid(INVALID_UID);
2387 }
Qingxi Lib2748102020-01-08 12:51:49 -08002388 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002389 }
2390
lucaslinc582d502022-01-27 09:07:00 +08002391 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002392 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2393 LinkProperties lp, int callerPid, int callerUid) {
2394 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002395 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2396 // this would be expensive (one more permission check every time any LP callback is
2397 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2398 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2399 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002400
2401 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2402 final boolean needsSanitization =
2403 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2404 if (!needsSanitization) {
2405 return new LinkProperties(lp);
2406 }
2407
2408 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002409 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002410 }
2411
2412 final LinkProperties newLp = new LinkProperties(lp);
2413 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2414 // object gets parceled.
2415 newLp.setCaptivePortalApiUrl(null);
2416 newLp.setCaptivePortalData(null);
2417 return newLp;
2418 }
2419
Roshan Pius08c94fb2020-01-16 12:17:17 -08002420 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2421 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002422 // There is no need to track the effective UID of the request here. If the caller
2423 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002424 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002425 // Unprivileged apps can only pass in null or their own UID.
2426 if (nc.getUids() == null) {
2427 // If the caller passes in null, the callback will also match networks that do not
2428 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2429 // In this case, redact everything in the request immediately. This ensures that the
2430 // app is not able to get any redacted information by filing an unredacted request
2431 // and observing whether the request matches something.
2432 if (nc.getNetworkSpecifier() != null) {
2433 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2434 }
2435 } else {
2436 nc.setSingleUid(callerUid);
2437 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002438 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002439 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002440 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002441
2442 // Clear owner UID; this can never come from an app.
2443 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002444 }
2445
Chalard Jean38354d12018-03-20 19:13:57 +09002446 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002447 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002448 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2449 }
2450 }
2451
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002452 @Override
2453 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2454 enforceAccessPermission();
2455 final int callerUid = Binder.getCallingUid();
2456 final long token = Binder.clearCallingIdentity();
2457 try {
2458 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2459 } finally {
2460 Binder.restoreCallingIdentity(token);
2461 }
2462 }
2463
junyulaiebd15162021-03-03 12:09:05 +08002464 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002465 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002466 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002467 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002468 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002469
Serik Beketayev05130302021-01-15 16:47:25 -08002470 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002471 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002472 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2473 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002474 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002475 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002476 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002477 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2478 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002479 }
2480 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002481 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002482 }
2483
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002484 @Override
junyulaiebd15162021-03-03 12:09:05 +08002485 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002486 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002487 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002488 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002489
2490 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2491 for (Network network : getAllNetworks()) {
2492 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002493 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002494 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2495 // NetworkCapabilities, which may contain UIDs of apps to which the
2496 // network applies. Should the UIDs be cleared so as not to leak or
2497 // interfere ?
2498 result.add(nai.getNetworkStateSnapshot());
2499 }
2500 }
2501 return result;
2502 }
2503
2504 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002505 public boolean isActiveNetworkMetered() {
2506 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002507
Qingxi Lib2748102020-01-08 12:51:49 -08002508 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002509 if (caps != null) {
2510 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2511 } else {
2512 // Always return the most conservative value
2513 return true;
2514 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002515 }
2516
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002517 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002518 * Ensures that the system cannot call a particular method.
2519 */
2520 private boolean disallowedBecauseSystemCaller() {
2521 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002522 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2523 // for devices launched with Q and above. However, existing devices upgrading to Q and
2524 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002525 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002526 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002527 log("This method exists only for app backwards compatibility"
2528 + " and must not be called by system services.");
2529 return true;
2530 }
2531 return false;
2532 }
2533
paulhub2c28682021-08-18 18:35:54 +08002534 private int getAppUid(final String app, final UserHandle user) {
2535 final PackageManager pm =
2536 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2537 final long token = Binder.clearCallingIdentity();
2538 try {
2539 return pm.getPackageUid(app, 0 /* flags */);
2540 } catch (PackageManager.NameNotFoundException e) {
2541 return -1;
2542 } finally {
2543 Binder.restoreCallingIdentity(token);
2544 }
2545 }
2546
2547 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2548 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2549 if (getAppUid(packageName, user) != callingUid) {
2550 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2551 }
2552 }
2553
Lorenzo Colitti23862912018-09-28 11:31:55 +09002554 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002555 * Ensure that a network route exists to deliver traffic to the specified
2556 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002557 * @param networkType the type of the network over which traffic to the
2558 * specified host is to be routed
2559 * @param hostAddress the IP address of the host to which the route is
2560 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002561 * @return {@code true} on success, {@code false} on failure
2562 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002563 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002564 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2565 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002566 if (disallowedBecauseSystemCaller()) {
2567 return false;
2568 }
paulhub2c28682021-08-18 18:35:54 +08002569 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002570 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002571 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002572 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002573 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002574
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002575 InetAddress addr;
2576 try {
2577 addr = InetAddress.getByAddress(hostAddress);
2578 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002579 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002580 return false;
2581 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002582
The Android Open Source Project28527d22009-03-03 19:31:44 -08002583 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002584 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002585 return false;
2586 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002587
2588 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2589 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002590 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002591 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2592 } else {
2593 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2594 }
2595 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002596 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002597
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002598 DetailedState netState;
2599 synchronized (nai) {
2600 netState = nai.networkInfo.getDetailedState();
2601 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002602
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002603 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002604 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002605 log("requestRouteToHostAddress on down network "
2606 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002607 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002608 }
2609 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002610 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002611
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002612 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002613 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002614 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002615 LinkProperties lp;
2616 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002617 synchronized (nai) {
2618 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002619 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002620 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002621 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002622 if (DBG) {
2623 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2624 }
Wink Saville32506bc2013-06-29 21:10:57 -07002625 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002626 } finally {
2627 Binder.restoreCallingIdentity(token);
2628 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002629 }
2630
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002631 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002632 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002633 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002634 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002635 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002636 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002637 if (bestRoute.getGateway().equals(addr)) {
2638 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002639 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002640 } else {
2641 // if we will connect to this through another route, add a direct route
2642 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002643 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002644 }
2645 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002646 if (DBG) log("Adding legacy route " + bestRoute +
2647 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002648
2649 final String dst = bestRoute.getDestinationLinkAddress().toString();
2650 final String nextHop = bestRoute.hasGateway()
2651 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002652 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002653 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2654 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002655 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002656 return false;
2657 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002658 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002659 }
2660
paulhu7c0a2e62021-01-08 00:51:49 +08002661 class DnsResolverUnsolicitedEventCallback extends
2662 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002663 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002664 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002665 try {
2666 mHandler.sendMessage(mHandler.obtainMessage(
2667 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002668 new PrivateDnsValidationUpdate(event.netId,
2669 InetAddresses.parseNumericAddress(event.ipAddress),
2670 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002671 } catch (IllegalArgumentException e) {
2672 loge("Error parsing ip address in validation event");
2673 }
2674 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002675
2676 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002677 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2678 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002679 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2680 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2681 // event callback for certain nai. e.g. cellular. Register here to pass to
2682 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002683 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002684 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2685 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002686 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002687 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002688 }
2689 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002690
2691 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002692 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2693 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2694 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002695 }
dalyk1720e542018-03-05 12:42:22 -05002696
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002697 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002698 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002699 return this.VERSION;
2700 }
2701
2702 @Override
2703 public String getInterfaceHash() {
2704 return this.HASH;
2705 }
paulhu7c0a2e62021-01-08 00:51:49 +08002706 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002707
2708 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002709 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2710 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002711
paulhu7c0a2e62021-01-08 00:51:49 +08002712 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002713 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002714 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002715 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002716 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002717 }
2718 }
2719
Sudheer Shanka9967d462021-03-18 19:09:25 +00002720 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002721 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002722 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2724 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002725 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002726 };
2727
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002728 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002729 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002730 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002731 }
2732
paulhu1a407652019-03-22 16:35:06 +08002733 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2734 for (String permission : permissions) {
2735 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2736 return true;
2737 }
2738 }
2739 return false;
2740 }
2741
Paul Jensen83f5d572014-08-29 09:54:01 -04002742 private void enforceInternetPermission() {
2743 mContext.enforceCallingOrSelfPermission(
2744 android.Manifest.permission.INTERNET,
2745 "ConnectivityService");
2746 }
2747
The Android Open Source Project28527d22009-03-03 19:31:44 -08002748 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002749 mContext.enforceCallingOrSelfPermission(
2750 android.Manifest.permission.ACCESS_NETWORK_STATE,
2751 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002752 }
2753
lucaslinc582d502022-01-27 09:07:00 +08002754 private boolean checkAccessPermission(int pid, int uid) {
2755 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2756 == PERMISSION_GRANTED;
2757 }
2758
paulhua6ee2122021-02-22 15:40:43 +08002759 /**
2760 * Performs a strict and comprehensive check of whether a calling package is allowed to
2761 * change the state of network, as the condition differs for pre-M, M+, and
2762 * privileged/preinstalled apps. The caller is expected to have either the
2763 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2764 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2765 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2766 * permission and cannot be revoked. See http://b/23597341
2767 *
2768 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2769 * of this app will be updated to the current time.
2770 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002771 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002772 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2773 == PackageManager.PERMISSION_GRANTED) {
2774 return;
2775 }
2776
2777 if (callingPkg == null) {
2778 throw new SecurityException("Calling package name is null.");
2779 }
2780
2781 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2782 final int uid = mDeps.getCallingUid();
2783 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2784 callingPkg, callingAttributionTag, null /* message */);
2785
2786 if (mode == AppOpsManager.MODE_ALLOWED) {
2787 return;
2788 }
2789
2790 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2791 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2792 return;
2793 }
2794
2795 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2796 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2797 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002798 }
2799
Charles He9369e612017-05-15 17:07:18 +01002800 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002801 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002802 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002803 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002804 }
2805
paulhu8e96a752019-08-12 16:25:11 +08002806 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002807 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002808 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002809 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002810 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002811 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002812 }
2813
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002814 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002815 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002816 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002817 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002818 android.Manifest.permission.NETWORK_SETTINGS,
2819 android.Manifest.permission.NETWORK_FACTORY,
2820 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2821 }
2822
2823 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002824 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002825 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002826 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002827 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2828 android.Manifest.permission.NETWORK_FACTORY,
2829 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2830 }
2831
lucaslin69e1aa92022-03-22 18:15:09 +08002832 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2833 return PERMISSION_GRANTED == mContext.checkPermission(
2834 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2835 || PERMISSION_GRANTED == mContext.checkPermission(
2836 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2837 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002838 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002839 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002840 }
2841
Chalard Jean9a396cc2018-02-21 18:43:54 +09002842 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002843 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002844 android.Manifest.permission.NETWORK_SETTINGS,
2845 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002846 }
2847
2848 private boolean checkSettingsPermission(int pid, int uid) {
2849 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002850 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2851 || PERMISSION_GRANTED == mContext.checkPermission(
2852 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002853 }
2854
paulhu8e96a752019-08-12 16:25:11 +08002855 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002856 enforceNetworkStackPermissionOr(mContext,
2857 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002858 }
2859
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002860 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002861 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002862 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002863 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002864 }
2865
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002866 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002867 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002868 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2869 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002870 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002871 }
2872
James Mattis8378aec2021-01-26 14:05:36 -08002873 private void enforceOemNetworkPreferencesPermission() {
2874 mContext.enforceCallingOrSelfPermission(
2875 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2876 "ConnectivityService");
2877 }
2878
James Mattisfa270db2021-05-31 17:11:10 -07002879 private void enforceManageTestNetworksPermission() {
2880 mContext.enforceCallingOrSelfPermission(
2881 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2882 "ConnectivityService");
2883 }
2884
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002885 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002886 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002887 android.Manifest.permission.NETWORK_STACK,
2888 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002889 }
2890
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002891 private boolean checkNetworkStackPermission(int pid, int uid) {
2892 return checkAnyPermissionOf(pid, uid,
2893 android.Manifest.permission.NETWORK_STACK,
2894 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2895 }
2896
paulhu1a407652019-03-22 16:35:06 +08002897 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2898 return checkAnyPermissionOf(pid, uid,
2899 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002900 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2901 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002902 }
2903
Paul Hu8fc2a552022-05-04 18:44:42 +08002904 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2905 boolean checkUidsAllowedList) {
2906 if (PermissionUtils.checkAnyPermissionOf(mContext,
2907 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2908 return true;
2909 }
2910
2911 // fallback to ConnectivityInternalPermission
2912 // TODO: Remove this fallback check after all apps have declared
2913 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2914 if (PermissionUtils.checkAnyPermissionOf(mContext,
2915 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2916 return true;
2917 }
2918
2919 // Check whether uid is in allowed on restricted networks list.
2920 if (checkUidsAllowedList
2921 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2922 return true;
2923 }
2924 return false;
2925 }
2926
2927 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2928 final int callingUid = mDeps.getCallingUid();
2929 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2930 throw new SecurityException("ConnectivityService: user " + callingUid
2931 + " has no permission to access restricted network.");
2932 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002933 }
2934
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002935 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002936 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002937 }
2938
Roshan Pius98f59ec2021-02-23 08:47:39 -08002939 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2940 return PERMISSION_GRANTED == mContext.checkPermission(
2941 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2942 }
2943
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002944 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002945 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002946 }
2947
2948 private void sendInetConditionBroadcast(NetworkInfo info) {
2949 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2950 }
2951
Wink Saville4f0de1e2011-08-04 15:01:58 -07002952 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002953 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002954 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002955 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002956 if (info.isFailover()) {
2957 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2958 info.setFailover(false);
2959 }
2960 if (info.getReason() != null) {
2961 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2962 }
2963 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002964 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2965 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002966 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002967 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002968 return intent;
2969 }
2970
2971 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2972 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2973 }
2974
Chiachang Wang3bc52762021-11-25 14:17:57 +08002975 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2976 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002977 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002978 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002979 if (!mSystemReady
2980 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002981 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002982 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002983 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002984 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002985 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002986 }
2987
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002988 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002989 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002990 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002991 final NetworkInfo ni = intent.getParcelableExtra(
2992 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002993 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2994 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2995 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002996 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002997 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002998 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002999 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003000 } finally {
3001 Binder.restoreCallingIdentity(ident);
3002 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003003 }
3004 }
3005
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003006 /**
Aaron Huang96011892020-06-27 07:18:23 +08003007 * Called by SystemServer through ConnectivityManager when the system is ready.
3008 */
3009 @Override
3010 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003011 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003012 throw new SecurityException("Calling Uid is not system uid.");
3013 }
3014 systemReadyInternal();
3015 }
3016
3017 /**
3018 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003019 */
3020 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003021 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003022 // Load flags after PackageManager is ready to query module version
3023 mFlags.loadFlags(mDeps, mContext);
3024
Aaron Huang9a57acf2020-12-08 10:03:29 +08003025 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3026 // listening network request which is sent by MultipathPolicyTracker won't be added
3027 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3028 // be called after PermissionMonitor#startMonitoring().
3029 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3030 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3031 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003032 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003033 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003034 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003035
Hugo Benichie5220992017-04-26 14:53:28 +09003036 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003037 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003038 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003039 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003040 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003041 }
3042 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003043
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003044 // Create network requests for always-on networks.
3045 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003046
3047 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003048 // Note that updating can be skipped here if the list is empty only because no uid
3049 // rules are applied before system ready. Normally, the empty uid list means to clear
3050 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003051 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3052 updateMobileDataPreferredUids();
3053 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003054
3055 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3056 if (SdkLevel.isAtLeastT()) {
3057 mBpfNetMaps.setPullAtomCallback(mContext);
3058 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003059 }
3060
The Android Open Source Project28527d22009-03-03 19:31:44 -08003061 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003062 * Start listening for default data network activity state changes.
3063 */
3064 @Override
3065 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003066 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003067 }
3068
3069 /**
3070 * Stop listening for default data network activity state changes.
3071 */
3072 @Override
3073 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003074 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003075 }
3076
3077 /**
3078 * Check whether the default network radio is currently active.
3079 */
3080 @Override
3081 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003082 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003083 }
3084
3085 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003086 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003087 * and set it on it's iface.
3088 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003089 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3090 final String iface = newLp.getInterfaceName();
3091 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003092 if (oldLp == null && mtu == 0) {
3093 // Silently ignore unset MTU value.
3094 return;
3095 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003096 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3097 if (VDBG) log("identical MTU - not setting");
3098 return;
3099 }
paulhucbbc3db2019-03-08 16:35:20 +08003100 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003101 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003102 return;
3103 }
sy.yun4aa73922013-09-02 05:24:09 +09003104
w19976e714f1d2014-08-05 15:18:11 -07003105 // Cannot set MTU without interface name
3106 if (TextUtils.isEmpty(iface)) {
3107 loge("Setting MTU size with null iface.");
3108 return;
3109 }
3110
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003111 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003112 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003113 mNetd.interfaceSetMtu(iface, mtu);
3114 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003115 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003116 }
3117 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003118
Chenbo Feng15416292018-11-08 17:36:21 -08003119 @VisibleForTesting
3120 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003121
lucaslin821c9782018-11-28 19:27:52 +08003122 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003123 String[] values = null;
3124 if (tcpBufferSizes != null) {
3125 values = tcpBufferSizes.split(",");
3126 }
3127
3128 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003129 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003130 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3131 values = tcpBufferSizes.split(",");
3132 }
3133
3134 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3135
3136 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003137 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003138
Chenbo Feng15416292018-11-08 17:36:21 -08003139 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3140 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3141 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003142 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003143 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003144 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003145 }
3146 }
3147
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003148 @Override
3149 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003150 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003151 NETWORK_RESTORE_DELAY_PROP_NAME);
3152 if(restoreDefaultNetworkDelayStr != null &&
3153 restoreDefaultNetworkDelayStr.length() != 0) {
3154 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003155 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003156 } catch (NumberFormatException e) {
3157 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003158 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003159 // if the system property isn't set, use the value for the apn type
3160 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3161
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003162 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3163 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003164 }
3165 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003166 }
3167
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003168 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003169 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003170 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003171 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003172 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003173 // Start gathering diagnostic information.
3174 netDiags.add(new NetworkDiagnostics(
3175 nai.network,
3176 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003177 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003178 DIAG_TIME_MS));
3179 }
3180
3181 for (NetworkDiagnostics netDiag : netDiags) {
3182 pw.println();
3183 netDiag.waitForMeasurements();
3184 netDiag.dump(pw);
3185 }
3186 }
3187
The Android Open Source Project28527d22009-03-03 19:31:44 -08003188 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003189 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3190 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003191 if (!checkDumpPermission(mContext, TAG, writer)) return;
3192
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003193 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003194 }
3195
lucaslin99473f62020-12-10 15:10:54 +08003196 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3197 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3198 != PackageManager.PERMISSION_GRANTED) {
3199 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003200 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003201 + " due to missing android.permission.DUMP permission");
3202 return false;
3203 } else {
3204 return true;
3205 }
3206 }
3207
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003208 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003209 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003210
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003211 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003212 dumpNetworkDiagnostics(pw);
3213 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003214 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003215 dumpNetworks(pw);
3216 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003217 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003218 dumpNetworkRequests(pw);
3219 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003220 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3221 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3222 dumpTrafficController(pw, fd, verbose);
3223 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003224 }
Erik Kline9647f382015-06-05 17:47:34 +09003225
Junyu Lai0da479b2022-04-20 15:06:29 +08003226 pw.println("NetworkProviders for:");
3227 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003228 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003229 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003230 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003231 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003232 pw.println();
3233
Chalard Jean5b409c72021-02-04 13:12:59 +09003234 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003235 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003236 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003237 pw.println("none");
3238 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003239 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003240 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003241 pw.println();
3242
James Mattis8b298a02021-06-01 22:34:04 -07003243 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003244 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003245 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003246 pw.decreaseIndent();
3247 pw.println();
3248
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003249 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003250 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003251 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003252 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003253 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003254
junyulaif2c67e42018-08-07 19:50:45 +08003255 pw.println("Status for known UIDs:");
3256 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003257 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003258 for (int i = 0; i < size; i++) {
3259 // Don't crash if the array is modified while dumping in bugreports.
3260 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003261 final int uid = mUidBlockedReasons.keyAt(i);
3262 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3263 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003264 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003265 } catch (ArrayIndexOutOfBoundsException e) {
3266 pw.println(" ArrayIndexOutOfBoundsException");
3267 } catch (ConcurrentModificationException e) {
3268 pw.println(" ConcurrentModificationException");
3269 }
3270 }
3271 pw.println();
3272 pw.decreaseIndent();
3273
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003274 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003275 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003276 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003277 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003278 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003279
Junyu Lai0da479b2022-04-20 15:06:29 +08003280 pw.println("Network Offers:");
3281 pw.increaseIndent();
3282 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3283 pw.println(offerInfo.offer);
3284 }
3285 pw.decreaseIndent();
3286 pw.println();
3287
Robert Greenwalt94e22142014-07-30 16:31:24 -07003288 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003289
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003290 pw.println();
markchien5e866652019-09-30 14:40:57 +08003291 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003292
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003293 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003294 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003295
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003296 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003297
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003298 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003299 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003300 pw.println("mNetworkRequestInfoLogs (most recent first):");
3301 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003302 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003303 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003304
3305 pw.println();
3306 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3307 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003308 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003309 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003310
3311 pw.println();
3312 pw.println("NetTransition WakeLock activity (most recent first):");
3313 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003314 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3315 pw.println("total releases: " + mTotalWakelockReleases);
3316 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3317 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3318 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3319 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3320 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3321 }
James Mattiscb1e0362021-04-06 17:07:42 -07003322 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003323
3324 pw.println();
3325 pw.println("bandwidth update requests (by uid):");
3326 pw.increaseIndent();
3327 synchronized (mBandwidthRequests) {
3328 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3329 pw.println("[" + mBandwidthRequests.keyAt(i)
3330 + "]: " + mBandwidthRequests.valueAt(i));
3331 }
3332 }
3333 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003334 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003335
James Mattiscb1e0362021-04-06 17:07:42 -07003336 pw.println();
3337 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3338 pw.increaseIndent();
3339 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003340 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003341 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003342
3343 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003344
3345 pw.println();
3346 pw.println("Permission Monitor:");
3347 pw.increaseIndent();
3348 mPermissionMonitor.dump(pw);
3349 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003350
3351 pw.println();
3352 pw.println("Legacy network activity:");
3353 pw.increaseIndent();
3354 mNetworkActivityTracker.dump(pw);
3355 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003356 }
3357
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003358 private void dumpNetworks(IndentingPrintWriter pw) {
3359 for (NetworkAgentInfo nai : networksSortedById()) {
3360 pw.println(nai.toString());
3361 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003362 pw.println("Nat464Xlat:");
3363 pw.increaseIndent();
3364 nai.dumpNat464Xlat(pw);
3365 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003366 pw.println(String.format(
3367 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3368 nai.numForegroundNetworkRequests(),
3369 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3370 nai.numBackgroundNetworkRequests(),
3371 nai.numNetworkRequests()));
3372 pw.increaseIndent();
3373 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3374 pw.println(nai.requestAt(i).toString());
3375 }
3376 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003377 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003378 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003379 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003380 pw.decreaseIndent();
3381 pw.decreaseIndent();
3382 }
3383 }
3384
James Mattis8b298a02021-06-01 22:34:04 -07003385 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3386 if (!mProfileNetworkPreferences.isEmpty()) {
3387 pw.println("Profile preferences:");
3388 pw.increaseIndent();
3389 pw.println(mProfileNetworkPreferences.preferences);
3390 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003391 }
James Mattis8b298a02021-06-01 22:34:04 -07003392 if (!mOemNetworkPreferences.isEmpty()) {
3393 pw.println("OEM preferences:");
3394 pw.increaseIndent();
3395 pw.println(mOemNetworkPreferences);
3396 pw.decreaseIndent();
3397 }
3398 if (!mMobileDataPreferredUids.isEmpty()) {
3399 pw.println("Mobile data preferred UIDs:");
3400 pw.increaseIndent();
3401 pw.println(mMobileDataPreferredUids);
3402 pw.decreaseIndent();
3403 }
James Mattis45d81842021-01-10 14:24:24 -08003404
James Mattis8b298a02021-06-01 22:34:04 -07003405 pw.println("Default requests:");
3406 pw.increaseIndent();
3407 dumpPerAppDefaultRequests(pw);
3408 pw.decreaseIndent();
3409 }
3410
3411 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003412 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3413 if (mDefaultRequest == defaultRequest) {
3414 continue;
3415 }
3416
James Mattis8b298a02021-06-01 22:34:04 -07003417 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3418 final String networkOutput;
3419 if (null == satisfier) {
3420 networkOutput = "null";
3421 } else if (mNoServiceNetwork.equals(satisfier)) {
3422 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003423 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003424 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003425 }
James Mattis8b298a02021-06-01 22:34:04 -07003426 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3427 ? "" : " asUid: " + defaultRequest.mAsUid;
3428 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3429 + defaultRequest.mPid + asUidString + "]";
3430 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3431 + " Preference order: " + defaultRequest.mPreferenceOrder
3432 + " Tracked UIDs: " + defaultRequest.getUids();
3433 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003434 }
3435 }
3436
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003437 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003438 NetworkRequestInfo[] infos = null;
3439 while (infos == null) {
3440 try {
3441 infos = requestsSortedById();
3442 } catch (ConcurrentModificationException e) {
3443 // mNetworkRequests should only be accessed from handler thread, except dump().
3444 // As dump() is never called in normal usage, it would be needlessly expensive
3445 // to lock the collection only for its benefit. Instead, retry getting the
3446 // requests if ConcurrentModificationException is thrown during dump().
3447 }
3448 }
3449 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003450 pw.println(nri.toString());
3451 }
3452 }
3453
Ken Chene6d511f2022-01-25 11:10:42 +08003454 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3455 boolean verbose) {
3456 try {
3457 mBpfNetMaps.dump(fd, verbose);
3458 } catch (ServiceSpecificException e) {
3459 pw.println(e.getMessage());
3460 } catch (IOException e) {
3461 loge("Dump BPF maps failed, " + e);
3462 }
3463 }
3464
Chalard Jean524f0b12021-10-25 21:11:56 +09003465 private void dumpAllRequestInfoLogsToLogcat() {
3466 try (PrintWriter logPw = new PrintWriter(new Writer() {
3467 @Override
3468 public void write(final char[] cbuf, final int off, final int len) {
3469 // This method is called with 0-length and 1-length arrays for empty strings
3470 // or strings containing only the DEL character.
3471 if (len <= 1) return;
3472 Log.e(TAG, new String(cbuf, off, len));
3473 }
3474 @Override public void flush() {}
3475 @Override public void close() {}
3476 })) {
3477 mNetworkRequestInfoLogs.dump(logPw);
3478 }
3479 }
3480
Hugo Benichia480ba52018-09-03 08:19:02 +09003481 /**
3482 * Return an array of all current NetworkAgentInfos sorted by network id.
3483 */
3484 private NetworkAgentInfo[] networksSortedById() {
3485 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003486 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003487 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003488 return networks;
3489 }
3490
3491 /**
3492 * Return an array of all current NetworkRequest sorted by request id.
3493 */
James Mattis258ea3c2020-11-15 15:04:40 -08003494 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003495 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003496 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003497 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003498 // Sort the array based off the NRI containing the min requestId in its requests.
3499 Arrays.sort(requests,
3500 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3501 Comparator.comparingInt(req -> req.requestId)).requestId
3502 )
3503 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003504 return requests;
3505 }
3506
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003507 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003508 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003509 if (officialNai != null && officialNai.equals(nai)) return true;
3510 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003511 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003512 " - " + nai);
3513 }
3514 return false;
3515 }
3516
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003517 private boolean isDisconnectRequest(Message msg) {
3518 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3519 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3520 return info.getState() == NetworkInfo.State.DISCONNECTED;
3521 }
3522
Robert Greenwalt2034b912009-08-12 16:08:25 -07003523 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003524 private class NetworkStateTrackerHandler extends Handler {
3525 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003526 super(looper);
3527 }
3528
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003529 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003530 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3531 final NetworkAgentInfo nai = arg.first;
3532 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003533 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003534 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003535 }
3536 return;
3537 }
3538
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003539 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003540 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003541 return;
3542 }
3543
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003544 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003545 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003546 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3547 final NetworkCapabilities sanitized =
3548 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003549 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003550 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003551 break;
3552 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003553 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003554 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003555 processLinkPropertiesFromAgent(nai, newLp);
3556 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003557 break;
3558 }
3559 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003560 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003561 updateNetworkInfo(nai, info);
3562 break;
3563 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003564 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003565 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003566 break;
3567 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003568 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003569 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003570 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003571 // Note that if the NAI had been connected, this would affect the
3572 // score, and therefore would require re-mixing the score and performing
3573 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003574 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003575 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3576 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003577 // Mark the network as temporarily accepting partial connectivity so that it
3578 // will be validated (and possibly become default) even if it only provides
3579 // partial internet access. Note that if user connects to partial connectivity
3580 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3581 // out of wifi coverage) and if the same wifi is available again, the device
3582 // will auto connect to this wifi even though the wifi has "no internet".
3583 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003584 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003585 break;
3586 }
junyulai011b1f12019-01-03 18:50:15 +08003587 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003588 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003589 break;
3590 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003591 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003592 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003593 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003594
3595 if (isLegacyLockdownNai(nai)
3596 && (underlying == null || underlying.size() != 1)) {
3597 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3598 + " must have exactly one underlying network: " + underlying);
3599 }
3600
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003601 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3602 nai.declaredUnderlyingNetworks = (underlying != null)
3603 ? underlying.toArray(new Network[0]) : null;
3604
3605 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3606 if (DBG) {
3607 log(nai.toShortString() + " changed underlying networks to "
3608 + Arrays.toString(nai.declaredUnderlyingNetworks));
3609 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003610 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003611 notifyIfacesChangedForNetworkStats();
3612 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003613 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003614 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003615 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3616 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3617 nai.teardownDelayMs = msg.arg1;
3618 } else {
3619 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3620 }
Chalard Jean550b5212021-03-05 23:07:53 +09003621 break;
3622 }
3623 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3624 nai.setLingerDuration((int) arg.second);
3625 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003626 }
Tyler Wear72388212021-09-09 14:49:02 -07003627 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3628 DscpPolicy policy = (DscpPolicy) arg.second;
3629 if (mDscpPolicyTracker != null) {
3630 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3631 }
3632 break;
3633 }
3634 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3635 if (mDscpPolicyTracker != null) {
3636 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3637 }
3638 break;
3639 }
3640 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3641 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003642 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003643 }
3644 break;
3645 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003646 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003647 // If nai is not yet created, or is already destroyed, ignore.
3648 if (!shouldDestroyNativeNetwork(nai)) break;
3649
3650 final int timeoutMs = (int) arg.second;
3651 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3652 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3653 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3654 }
3655
3656 // Marking a network awaiting replacement is used to ensure that any requests
3657 // satisfied by the network do not switch to another network until a
3658 // replacement is available or the wait for a replacement times out.
3659 // If the network is inactive (i.e., nascent or lingering), then there are no
3660 // such requests, and there is no point keeping it. Just tear it down.
3661 // Note that setLingerDuration(0) cannot be used to do this because the network
3662 // could be nascent.
3663 nai.clearInactivityState();
3664 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3665 Log.d(TAG, nai.toShortString()
3666 + " marked awaiting replacement is unneeded, tearing down instead");
3667 teardownUnneededNetwork(nai);
3668 break;
3669 }
3670
3671 Log.d(TAG, "Marking " + nai.toShortString()
3672 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3673 destroyNativeNetwork(nai);
3674
3675 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3676 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3677 // consider the fact that the network could already have disconnected or been
3678 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3679 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3680 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3681 mKeepaliveTracker.handleStopAllKeepalives(nai,
3682 SocketKeepalive.ERROR_INVALID_NETWORK);
3683
3684 nai.updateScoreForNetworkAgentUpdate();
3685 // This rematch is almost certainly not going to result in any changes, because
3686 // the destroyed flag is only just above the "current satisfier wins"
3687 // tie-breaker. But technically anything that affects scoring should rematch.
3688 rematchAllNetworksAndRequests();
3689 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3690 break;
3691 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003692 }
3693 }
3694
3695 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003696 final int netId = msg.arg2;
3697 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003698 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003699 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003700 switch (msg.what) {
3701 default:
3702 return false;
lucasline117e2e2019-10-22 18:27:33 +08003703 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003704 if (nai == null) {
3705 break;
3706 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003707 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3708 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003709 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003710 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003711 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003712 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003713 if (probePrivateDnsCompleted) {
3714 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3715 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003716 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003717 }
3718 // Only show the notification when the private DNS is broken and the
3719 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003720 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003721 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3722 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003723 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003724 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3725 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3726 // private DNS is broken, it means this network is being reevaluated.
3727 // Either probing private DNS is not necessary any more or it hasn't been
3728 // done yet. In either case, the networkCapabilities should be updated to
3729 // reflect the new status.
3730 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003731 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003732 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003733 }
3734 break;
3735 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003736 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003737 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3738
Erik Kline31b4a9e2018-01-11 21:07:29 +09003739 if (nai == null) break;
3740
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003741 handleNetworkTested(nai, results.mTestResult,
3742 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003743 break;
3744 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003745 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003746 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003747 // If captive portal status has changed, update capabilities or disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003748 if (nai != null && (visible != nai.captivePortalDetected())) {
3749 nai.setCaptivePortalDetected(visible);
3750 if (visible && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3751 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003752 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003753 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003754 teardownUnneededNetwork(nai);
3755 break;
3756 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003757 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003758 }
3759 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003760 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003761 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003762 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3763 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003764 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003765 if (nai == null) {
3766 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3767 break;
3768 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003769 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003770 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003771 (PendingIntent) msg.obj,
3772 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003773 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003774 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003775 break;
3776 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003777 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003778 if (nai == null) break;
3779
Erik Kline9a62f012018-03-21 07:18:33 -07003780 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003781 break;
3782 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003783 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003784 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003785 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003786 break;
3787 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003788 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003789 return true;
3790 }
3791
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003792 private void handleNetworkTested(
3793 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003794 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3795 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
3796 final boolean captive = !TextUtils.isEmpty(redirectUrl);
3797
3798 // If there is any kind of working networking, then the NAI has been evaluated
3799 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3800 // the first time this ever happened.
3801 final boolean someConnectivity = (valid || partial || captive);
3802 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
3803 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3804
he_won.hwang881307a2022-03-15 21:23:52 +09003805 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3806 // Assume the validation failure is due to a temporary failure after roaming
3807 // and ignore it. NetworkMonitor will continue to retry validation. If it
3808 // continues to fail after the block timeout expires, the network will be
3809 // marked unvalidated. If it succeeds, then validation state will not change.
3810 return;
3811 }
3812
Chalard Jean254bd162022-08-25 13:04:51 +09003813 final boolean wasValidated = nai.isValidated();
3814 final boolean wasPartial = nai.partialConnectivity();
3815 nai.setPartialConnectivity((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3816 final boolean partialConnectivityChanged = (wasPartial != nai.partialConnectivity());
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003817
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003818 if (DBG) {
3819 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3820 ? " with redirect to " + redirectUrl
3821 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003822 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003823 }
Chalard Jean254bd162022-08-25 13:04:51 +09003824 if (valid != nai.isValidated()) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003825 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003826 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003827 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003828 if (valid) {
3829 handleFreshlyValidatedNetwork(nai);
3830 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3831 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003832 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003833 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003834 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003835 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003836 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003837 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003838 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003839 NotificationType.PRIVATE_DNS_BROKEN);
3840 // If network becomes valid, the hasShownBroken should be reset for
3841 // that network so that the notification will be fired when the private
3842 // DNS is broken again.
3843 nai.networkAgentConfig.hasShownBroken = false;
3844 }
3845 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003846 updateCapabilitiesForNetwork(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003847 } else if (becameEvaluated) {
3848 // If valid or partial connectivity changed, updateCapabilities* has
3849 // done the rematch.
3850 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003851 }
3852 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003853
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003854 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003855 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003856 nai.onValidationStatusChanged(
3857 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3858 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003859
3860 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003861 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003862 // immediately. Re-notify partial connectivity silently if no internet
3863 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003864 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003865 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003866 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
3867 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003868 }
3869
Chalard Jean254bd162022-08-25 13:04:51 +09003870 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003871 handleNetworkUnvalidated(nai);
3872 }
3873 }
3874
Calvin Ondada1452016-10-11 15:10:46 -07003875 private int getCaptivePortalMode() {
3876 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003877 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3878 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003879 }
3880
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003881 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3882 switch (msg.what) {
3883 default:
3884 return false;
3885 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3886 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3887 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3888 handleLingerComplete(nai);
3889 }
3890 break;
3891 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003892 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3893 handleNetworkAgentRegistered(msg);
3894 break;
3895 }
3896 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3897 handleNetworkAgentDisconnected(msg);
3898 break;
3899 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003900 }
3901 return true;
3902 }
3903
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003904 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003905 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003906 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003907 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003908 maybeHandleNetworkAgentMessage(msg);
3909 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003910 }
3911 }
3912
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003913 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003914 private final int mNetId;
3915 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003916
3917 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003918 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003919 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003920 }
3921
3922 @Override
3923 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3924 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003925 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003926 }
3927
3928 @Override
3929 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003930 // Legacy version of notifyNetworkTestedWithExtras.
3931 // Would only be called if the system has a NetworkStack module older than the
3932 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003933 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003934 }
3935
3936 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003937 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003938 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3939 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003940 final Message msg = mTrackerHandler.obtainMessage(
3941 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003942 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003943 new NetworkTestedResults(
3944 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003945 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003946
3947 // Invoke ConnectivityReport generation for this Network test event.
3948 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3949 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003950
Cody Kestingf1120be2020-08-03 18:01:40 -07003951 // NetworkMonitor reports the network validation result as a bitmask while
3952 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3953 // logical value for ConnectivityDiagnostics.
3954 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3955 p.result);
3956
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003957 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003958 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003959 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3960 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3961
Aaron Huang959d3642021-01-21 15:47:41 +08003962 ConnectivityReportEvent reportEvent =
3963 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3964 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003965 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003966 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003967 }
3968
3969 @Override
3970 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3971 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3972 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003973 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003974 }
3975
3976 @Override
lucasline117e2e2019-10-22 18:27:33 +08003977 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3978 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3979 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003980 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003981 }
3982
3983 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003984 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3985 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3986 EVENT_CAPPORT_DATA_CHANGED,
3987 0, mNetId, data));
3988 }
3989
3990 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003991 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003992 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003993 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003994
3995 final PendingIntent pendingIntent;
3996 // Only the system server can register notifications with package "android"
3997 final long token = Binder.clearCallingIdentity();
3998 try {
paulhu7746e4e2020-06-09 19:07:03 +08003999 pendingIntent = PendingIntent.getBroadcast(
4000 mContext,
4001 0 /* requestCode */,
4002 intent,
4003 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004004 } finally {
4005 Binder.restoreCallingIdentity(token);
4006 }
4007 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4008 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004009 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004010 }
4011
4012 @Override
4013 public void hideProvisioningNotification() {
4014 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004015 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004016 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004017
4018 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004019 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004020 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004021 }
4022
4023 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004024 public int getInterfaceVersion() {
4025 return this.VERSION;
4026 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004027
4028 @Override
4029 public String getInterfaceHash() {
4030 return this.HASH;
4031 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004032 }
4033
Cody Kestingf1120be2020-08-03 18:01:40 -07004034 /**
4035 * Converts the given NetworkMonitor-specific validation result bitmask to a
4036 * ConnectivityDiagnostics-specific validation result int.
4037 */
4038 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4039 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4040 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4041 }
4042 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4043 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4044 }
4045 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4046 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4047 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4048 }
4049
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004050 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004051 log("Data stall detected with methods: " + p.detectionMethod);
4052
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004053 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004054 int detectionMethod = 0;
4055 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4056 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4057 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4058 }
4059 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4060 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4061 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4062 p.tcpMetricsCollectionPeriodMillis);
4063 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004064 }
4065
Cody Kestingf53a0752020-04-15 12:33:28 -07004066 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004067 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004068 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004069
4070 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4071 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4072 // the cost of going through two handlers.
4073 mConnectivityDiagnosticsHandler.sendMessage(msg);
4074 }
4075
Cody Kestingb37958e2020-05-15 10:36:01 -07004076 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4077 return (p.detectionMethod & detectionMethod) != 0;
4078 }
4079
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004080 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4081 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004082 }
4083
Erik Klinea73af002018-06-26 18:53:43 +09004084 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4085 if (nai == null) return;
4086 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4087 // in order to restart a validation pass from within netd.
4088 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4089 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004090 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004091 }
4092 }
4093
Erik Kline31b4a9e2018-01-11 21:07:29 +09004094 private void handlePrivateDnsSettingsChanged() {
4095 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4096
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004097 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004098 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004099 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004100 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4101 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004102 }
4103 }
4104
Erik Kline9a62f012018-03-21 07:18:33 -07004105 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4106 // Private DNS only ever applies to networks that might provide
4107 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004108 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004109
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004110 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004111 // schedule DNS resolutions. If a DNS resolution is required the
4112 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004113 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004114
4115 // With Private DNS bypass support, we can proceed to update the
4116 // Private DNS config immediately, even if we're in strict mode
4117 // and have not yet resolved the provider name into a set of IPs.
4118 updatePrivateDns(nai, cfg);
4119 }
4120
4121 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4122 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004123 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004124 }
4125
dalyk1720e542018-03-05 12:42:22 -05004126 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4127 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4128 if (nai == null) {
4129 return;
4130 }
4131 mDnsManager.updatePrivateDnsValidation(update);
4132 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4133 }
4134
paulhu7c0a2e62021-01-08 00:51:49 +08004135 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004136 int prefixLength) {
4137 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4138 if (nai == null) return;
4139
paulhu7c0a2e62021-01-08 00:51:49 +08004140 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4141 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004142
4143 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004144 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004145 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004146 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004147 prefixLength);
4148 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004149 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004150 return;
4151 }
4152 }
4153
Lorenzo Colittid523d142020-04-01 20:16:30 +09004154 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004155 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4156 }
4157
Hai Shalome58bdc62021-01-11 18:45:34 -08004158 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004159 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004160 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004161 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4162 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4163 }
4164
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004165 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004166 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004167 * @param nai the agent info to update
4168 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004169 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004170 */
junyulai2b6f0c22021-02-03 20:15:30 +08004171 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4172 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4173 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004174 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004175 // one lingered request, set inactive.
4176 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004177 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004178 if (DBG) log("Unsetting inactive " + nai.toShortString());
4179 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004180 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004181 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004182 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004183 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4184 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004185 }
junyulai2b6f0c22021-02-03 20:15:30 +08004186 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004187 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004188 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004189 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004190 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004191 }
4192
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004193 private void handleNetworkAgentRegistered(Message msg) {
4194 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4195 if (!mNetworkAgentInfos.contains(nai)) {
4196 return;
4197 }
4198
4199 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4200 if (VDBG) log("NetworkAgent registered");
4201 } else {
4202 loge("Error connecting NetworkAgent");
4203 mNetworkAgentInfos.remove(nai);
4204 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004205 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004206 synchronized (mNetworkForNetId) {
4207 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004208 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004209 mNetIdManager.releaseNetId(nai.network.getNetId());
4210 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004211 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004212 }
4213 }
4214 }
Paul Jensend5f53392014-11-25 15:26:53 -05004215
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004216 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004217 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004218 }
4219
he_won.hwang881307a2022-03-15 21:23:52 +09004220 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004221 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004222 if (SdkLevel.isAtLeastT()) return false;
4223 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4224 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4225 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4226 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004227 final long currentTimeMs = SystemClock.elapsedRealtime();
4228 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004229 if (timeSinceLastRoam <= blockTimeOut) {
4230 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4231 return true;
4232 }
4233 }
4234 return false;
4235 }
4236
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004237 private void handleNetworkAgentDisconnected(Message msg) {
4238 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004239 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004240 }
4241
Chalard Jeand9fffc32018-05-11 20:19:20 +09004242 // Destroys a network, remove references to it from the internal state managed by
4243 // ConnectivityService, free its interfaces and clean up.
4244 // Must be called on the Handler thread.
4245 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004246 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004247
4248 if (!mNetworkAgentInfos.contains(nai)) return;
4249
Chalard Jeand9fffc32018-05-11 20:19:20 +09004250 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004251 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004252 }
lucaslinb25c9a62019-02-12 15:30:13 +08004253 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004254 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004255 // A network agent has disconnected.
4256 // TODO - if we move the logic to the network agent (have them disconnect
4257 // because they lost all their requests or because their score isn't good)
4258 // then they would disconnect organically, report their new state and then
4259 // disconnect the channel.
4260 if (nai.networkInfo.isConnected()) {
4261 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4262 null, null);
4263 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004264 final boolean wasDefault = isDefaultNetwork(nai);
4265 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004266 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004267 }
4268 notifyIfacesChangedForNetworkStats();
4269 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4270 // by other networks that are already connected. Perhaps that can be done by
4271 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4272 // of rematchAllNetworksAndRequests
4273 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004274 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004275
4276 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004277 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4278 // Disable wakeup packet monitoring for each interface.
4279 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4280 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004281 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004282 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004283 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004284 synchronized (mNetworkForNetId) {
4285 // Remove the NetworkAgent, but don't mark the netId as
4286 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004287 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004288 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004289 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004290 // Remove all previously satisfied requests.
4291 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004292 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004293 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004294 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004295 if (currentNetwork != null
4296 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004297 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004298 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4299 // rematch not to keep disconnected agents instead of setting it here ; this
4300 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004301 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004302 for (final NetworkOfferInfo noi : mNetworkOffers) {
4303 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004304 }
James Mattise3ef1912020-12-20 11:09:58 -08004305
Chalard Jean5b409c72021-02-04 13:12:59 +09004306 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004307 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004308 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004309 // network, because while incorrect this is the closest to the old (also
4310 // incorrect) behavior.
4311 mNetworkActivityTracker.updateDataActivityTracking(
4312 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004313 ensureNetworkTransitionWakelock(nai.toShortString());
4314 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004315 }
4316 }
junyulai2b6f0c22021-02-03 20:15:30 +08004317 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004318 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004319 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004320 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004321 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004322 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004323 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004324
4325 // Immediate teardown.
4326 if (nai.teardownDelayMs == 0) {
4327 destroyNetwork(nai);
4328 return;
4329 }
4330
4331 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004332 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304333 try {
4334 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4335 } catch (RemoteException e) {
4336 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4337 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004338 }
4339 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4340 }
4341
4342 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004343 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004344 // Tell netd to clean up the configuration for this network
4345 // (routing rules, DNS, etc).
4346 // This may be slow as it requires a lot of netd shelling out to ip and
4347 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004348 // after we've rematched networks with requests (which might change the default
4349 // network or service a new request from an app), so network traffic isn't interrupted
4350 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004351 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004352 }
Chalard Jean254bd162022-08-25 13:04:51 +09004353 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004354 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4355 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4356 // false if the network was never created.
4357 // TODO: delete when S is no longer supported.
4358 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004359 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004360 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004361 }
4362
Ken Chen6df7a902021-04-09 15:08:42 +08004363 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004364 try {
4365 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004366 final NativeNetworkConfig config;
4367 if (nai.isVPN()) {
4368 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004369 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004370 return false;
4371 }
4372 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4373 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004374 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004375 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004376 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004377 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004378 getNetworkPermission(nai.networkCapabilities),
4379 false /* secure */,
4380 VpnManager.TYPE_VPN_NONE,
4381 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004382 }
Ken Chen6df7a902021-04-09 15:08:42 +08004383 mNetd.networkCreate(config);
4384 mDnsResolver.createNetworkCache(nai.network.getNetId());
4385 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4386 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004387 return true;
4388 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004389 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004390 return false;
4391 }
4392 }
4393
Ken Chen6df7a902021-04-09 15:08:42 +08004394 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004395 if (mDscpPolicyTracker != null) {
4396 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4397 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004398 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004399 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004400 } catch (RemoteException | ServiceSpecificException e) {
4401 loge("Exception destroying network(networkDestroy): " + e);
4402 }
4403 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004404 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004405 } catch (RemoteException | ServiceSpecificException e) {
4406 loge("Exception destroying network: " + e);
4407 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004408 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4409 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4410 // gets created, could add data to DnsManager data structures that will never get deleted.
4411 mDnsManager.removeNetwork(nai.network);
4412
4413 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004414 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004415 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4416 }
4417
Chalard Jean254bd162022-08-25 13:04:51 +09004418 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004419 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004420 }
4421
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004422 // If this method proves to be too slow then we can maintain a separate
4423 // pendingIntent => NetworkRequestInfo map.
4424 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4425 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004426 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4427 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4428 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004429 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004430 return entry.getValue();
4431 }
4432 }
4433 return null;
4434 }
4435
Chalard Jean524f0b12021-10-25 21:11:56 +09004436 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4437 if (SdkLevel.isAtLeastT()) {
4438 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4439 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4440 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4441 // bug is fixed.
4442 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004443 throw new IllegalStateException("This NRI is already registered. New : " + nri
4444 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004445 }
4446 }
4447 }
4448 }
4449
Chalard Jeanac9ace02022-01-26 16:54:05 +09004450 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4451 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004452 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004453 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4454 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004455 }
4456 return false;
4457 }
4458
James Mattisf7027322020-12-13 16:28:14 -08004459 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004460 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004461 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4462 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4463 final NetworkRequestInfo existingRequest =
4464 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004465 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004466 if (DBG) {
4467 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4468 + nri.mRequests.get(0) + " because their intents matched.");
4469 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004470 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004471 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004472 }
Erik Kline05f2b402015-04-30 12:58:40 +09004473 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004474 }
4475
James Mattisf7027322020-12-13 16:28:14 -08004476 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004477 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004478 }
4479
James Mattis3ce3d3c2021-02-09 18:18:28 -08004480 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004481 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004482 for (final NetworkRequestInfo nri : nris) {
4483 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004484 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004485 for (final NetworkRequest req : nri.mRequests) {
4486 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004487 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004488 if (req.isListen()) {
4489 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4490 if (req.networkCapabilities.hasSignalStrength()
4491 && network.satisfiesImmutableCapabilitiesOf(req)) {
4492 updateSignalStrengthThresholds(network, "REGISTER", req);
4493 }
James Mattisf7027322020-12-13 16:28:14 -08004494 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004495 }
4496 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004497
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004498 // If this NRI has a satisfier already, it is replacing an older request that
4499 // has been removed. Track it.
4500 final NetworkRequest activeRequest = nri.getActiveRequest();
4501 if (null != activeRequest) {
4502 // If there is an active request, then for sure there is a satisfier.
4503 nri.getSatisfier().addRequest(activeRequest);
4504 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004505 }
James Mattisf7027322020-12-13 16:28:14 -08004506
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004507 if (mFlags.noRematchAllRequestsOnRegister()) {
4508 rematchNetworksAndRequests(nris);
4509 } else {
4510 rematchAllNetworksAndRequests();
4511 }
James Mattis45d81842021-01-10 14:24:24 -08004512
Chalard Jean0354d8c2021-01-12 10:58:56 +09004513 // Requests that have not been matched to a network will not have been sent to the
4514 // providers, because the old satisfier and the new satisfier are the same (null in this
4515 // case). Send these requests to the providers.
4516 for (final NetworkRequestInfo nri : nris) {
4517 for (final NetworkOfferInfo noi : mNetworkOffers) {
4518 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004519 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004520 }
4521 }
4522
James Mattisf7027322020-12-13 16:28:14 -08004523 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4524 final int callingUid) {
4525 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004526 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004527 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4528 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4529 handleReleaseNetworkRequest(
4530 nri.mRequests.get(0),
4531 callingUid,
4532 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004533 }
4534 }
4535
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004536 // Determines whether the network is the best (or could become the best, if it validated), for
4537 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4538 // on the value of reason:
4539 //
4540 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4541 // then it should be torn down.
4542 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4543 // then it should be lingered.
4544 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004545 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004546
Chalard Jean254bd162022-08-25 13:04:51 +09004547 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004548 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4549 return false;
4550 }
4551
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004552 final int numRequests;
4553 switch (reason) {
4554 case TEARDOWN:
4555 numRequests = nai.numRequestNetworkRequests();
4556 break;
4557 case LINGER:
4558 numRequests = nai.numForegroundNetworkRequests();
4559 break;
4560 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004561 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004562 return true;
4563 }
4564
Chalard Jean947acd42021-03-08 22:29:27 +09004565 if (numRequests > 0) return false;
4566
Paul Jensende49eb12015-06-25 15:30:08 -04004567 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004568 if (reason == UnneededFor.LINGER
4569 && !nri.isMultilayerRequest()
4570 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004571 // Background requests don't affect lingering.
4572 continue;
4573 }
4574
James Mattis3d229892020-11-16 16:46:28 -08004575 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004576 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004577 }
4578 }
Paul Jensende49eb12015-06-25 15:30:08 -04004579 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004580 }
4581
James Mattis3d229892020-11-16 16:46:28 -08004582 private boolean isNetworkPotentialSatisfier(
4583 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4584 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004585 // request, return immediately. For multilayer requests, check to see if any of the
4586 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004587 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4588 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004589 return false;
4590 }
4591 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004592 // This multilayer listen request is satisfied therefore no further requests need to be
4593 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004594 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004595 return false;
4596 }
James Mattis3d229892020-11-16 16:46:28 -08004597 // As non-multilayer listen requests have already returned, the below would only happen
4598 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004599 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004600 continue;
4601 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004602 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004603 // there is hope for it to become one if it validated, then it is needed.
4604 if (candidate.satisfies(req)) {
4605 // As soon as a network is found that satisfies a request, return. Specifically for
4606 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4607 // is important so as to not evaluate lower priority requests further in
4608 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004609 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4610 ? nri.getSatisfier() : null;
4611 // Note that this catches two important cases:
4612 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4613 // is currently satisfying the request. This is desirable when
4614 // cellular ends up validating but WiFi does not.
4615 // 2. Unvalidated WiFi will not be reaped when validated cellular
4616 // is currently satisfying the request. This is desirable when
4617 // WiFi ends up validating and out scoring cellular.
4618 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004619 }
4620 }
4621
4622 return false;
4623 }
4624
Erik Kline0c04b742016-07-07 16:50:58 +09004625 private NetworkRequestInfo getNriForAppRequest(
4626 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004627 // Looking up the app passed param request in mRequests isn't possible since it may return
4628 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4629 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004630 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4631 // to avoid potential race conditions when validating a package->uid mapping when sending
4632 // the callback on the very low-chance that an application shuts down prior to the callback
4633 // being sent.
4634 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4635 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004636
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004637 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004638 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004639 log(String.format("UID %d attempted to %s for unowned request %s",
4640 callingUid, requestedOperation, nri));
4641 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004642 }
Erik Kline0c04b742016-07-07 16:50:58 +09004643 }
4644
4645 return nri;
4646 }
4647
James Mattisf7027322020-12-13 16:28:14 -08004648 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4649 final String callingMethod) {
4650 if (nri.isMultilayerRequest()) {
4651 throw new IllegalStateException(
4652 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004653 }
4654 }
4655
James Mattisf7027322020-12-13 16:28:14 -08004656 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004657 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004658 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4659 // single NetworkRequest and thus does not apply to multilayer requests.
4660 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4661 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004662 return;
4663 }
James Mattis2516da32021-01-31 17:06:19 -08004664 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004665 return;
4666 }
James Mattisf7027322020-12-13 16:28:14 -08004667 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4668 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004669 }
4670 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004671 callCallbackForRequest(
4672 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004673 }
4674
James Mattisf7027322020-12-13 16:28:14 -08004675 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4676 final int callingUid,
4677 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004678 final NetworkRequestInfo nri =
4679 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4680 if (nri == null) {
4681 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004682 }
James Mattisf7027322020-12-13 16:28:14 -08004683 if (VDBG || (DBG && request.isRequest())) {
4684 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004685 }
4686 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004687 if (callOnUnavailable) {
4688 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4689 }
Erik Kline155a59a2015-11-25 12:49:38 +09004690 }
Erik Kline0c04b742016-07-07 16:50:58 +09004691
James Mattisa076c532020-12-02 14:12:41 -08004692 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004693 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004694 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004695 if (null == mNetworkRequests.remove(req)) {
4696 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4697 continue;
4698 }
James Mattisa076c532020-12-02 14:12:41 -08004699 if (req.isListen()) {
4700 removeListenRequestFromNetworks(req);
4701 }
4702 }
James Mattis8f036802021-06-20 16:26:01 -07004703 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004704 if (mDefaultNetworkRequests.remove(nri)) {
4705 // If this request was one of the defaults, then the UID rules need to be updated
4706 // WARNING : if the app(s) for which this network request is the default are doing
4707 // traffic, this will kill their connected sockets, even if an equivalent request
4708 // is going to be reinstated right away ; unconnected traffic will go on the default
4709 // until the new default is set, which will happen very soon.
4710 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4711 // remove ranges for those requests that won't have a replacement
4712 final NetworkAgentInfo satisfier = nri.getSatisfier();
4713 if (null != satisfier) {
4714 try {
paulhu0e79d952021-06-09 16:11:35 +08004715 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4716 satisfier.network.getNetId(),
4717 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004718 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004719 } catch (RemoteException e) {
4720 loge("Exception setting network preference default network", e);
4721 }
4722 }
4723 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004724 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004725 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004726 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004727
4728 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004729 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004730 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004731 }
4732 }
4733
Chalard Jean0354d8c2021-01-12 10:58:56 +09004734 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4735 // needed for this offer.
4736 for (final NetworkOfferInfo noi : mNetworkOffers) {
4737 for (final NetworkRequest req : nri.mRequests) {
4738 if (req.isRequest() && noi.offer.neededFor(req)) {
4739 noi.offer.onNetworkUnneeded(req);
4740 }
4741 }
4742 }
James Mattisa076c532020-12-02 14:12:41 -08004743 }
4744
James Mattis3ce3d3c2021-02-09 18:18:28 -08004745 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4746 for (final NetworkRequestInfo nri : nris) {
4747 if (mDefaultRequest == nri) {
4748 // Make sure we never remove the default request.
4749 continue;
4750 }
4751 handleRemoveNetworkRequest(nri);
4752 }
4753 }
4754
James Mattisa076c532020-12-02 14:12:41 -08004755 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4756 // listens don't have a singular affected Network. Check all networks to see
4757 // if this listen request applies and remove it.
4758 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4759 nai.removeRequest(req.requestId);
4760 if (req.networkCapabilities.hasSignalStrength()
4761 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4762 updateSignalStrengthThresholds(nai, "RELEASE", req);
4763 }
4764 }
4765 }
4766
4767 /**
4768 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4769 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4770 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4771 */
4772 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4773 boolean wasKept = false;
4774 final NetworkAgentInfo nai = nri.getSatisfier();
4775 if (nai != null) {
4776 final int requestLegacyType = nri.getActiveRequest().legacyType;
4777 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4778 nai.removeRequest(nri.getActiveRequest().requestId);
4779 if (VDBG || DDBG) {
4780 log(" Removing from current network " + nai.toShortString()
4781 + ", leaving " + nai.numNetworkRequests() + " requests.");
4782 }
4783 // If there are still lingered requests on this network, don't tear it down,
4784 // but resume lingering instead.
4785 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004786 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004787 notifyNetworkLosing(nai, now);
4788 }
4789 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4790 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4791 teardownUnneededNetwork(nai);
4792 } else {
4793 wasKept = true;
4794 }
James Mattisa076c532020-12-02 14:12:41 -08004795 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4796 // Went from foreground to background.
4797 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004798 }
4799
Erik Kline0c04b742016-07-07 16:50:58 +09004800 // Maintain the illusion. When this request arrived, we might have pretended
4801 // that a network connected to serve it, even though the network was already
4802 // connected. Now that this request has gone away, we might have to pretend
4803 // that the network disconnected. LegacyTypeTracker will generate that
4804 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004805 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004806 boolean doRemove = true;
4807 if (wasKept) {
4808 // check if any of the remaining requests for this network are for the
4809 // same legacy type - if so, don't remove the nai
4810 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4811 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004812 if (otherRequest.legacyType == requestLegacyType
4813 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004814 if (DBG) log(" still have other legacy request - leaving");
4815 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004816 }
4817 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004818 }
4819
Erik Kline0c04b742016-07-07 16:50:58 +09004820 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004821 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004822 }
4823 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004824 }
4825 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004826
Junyu Lai00d92df2022-07-05 11:01:52 +08004827 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004828 return checkAnyPermissionOf(
4829 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4830 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4831 }
4832
Lorenzo Colittid6459092016-07-04 12:55:44 +09004833 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004834 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004835 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004836 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004837 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004838 }
4839
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004840 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004841 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4842 enforceNetworkStackSettingsOrSetup();
4843 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4844 encodeBool(accept), encodeBool(always), network));
4845 }
4846
4847 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004848 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004849 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004850 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4851 }
4852
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004853 @Override
4854 public void setTestAllowBadWifiUntil(long timeMs) {
4855 enforceSettingsPermission();
4856 if (!Build.isDebuggable()) {
4857 throw new IllegalStateException("Does not support in non-debuggable build");
4858 }
4859
4860 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4861 throw new IllegalArgumentException("It should not exceed "
4862 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4863 }
4864
4865 mHandler.sendMessage(
4866 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4867 }
4868
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004869 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4870 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4871 " accept=" + accept + " always=" + always);
4872
4873 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4874 if (nai == null) {
4875 // Nothing to do.
4876 return;
4877 }
4878
Chalard Jean254bd162022-08-25 13:04:51 +09004879 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004880 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004881 return;
4882 }
4883
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004884 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004885 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004886 }
4887
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004888 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4889 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004890 // If network becomes partial connectivity and user already accepted to use this
4891 // network, we should respect the user's option and don't need to popup the
4892 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004893 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004894 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004895 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004896 }
4897
4898 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004899 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004900 }
4901
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004902 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004903 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004904 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004905 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004906 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004907 }
4908
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004909 }
4910
lucaslin2240ef62019-03-12 13:08:03 +08004911 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4912 boolean always) {
4913 if (DBG) {
4914 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4915 + " always=" + always);
4916 }
4917
4918 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4919 if (nai == null) {
4920 // Nothing to do.
4921 return;
4922 }
4923
Chalard Jean254bd162022-08-25 13:04:51 +09004924 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004925 // The network validated while the dialog box was up. Take no action.
4926 return;
4927 }
4928
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004929 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4930 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004931 }
4932
4933 // TODO: Use the current design or save the user choice into IpMemoryStore.
4934 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004935 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004936 }
4937
4938 if (!accept) {
4939 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004940 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004941 // Tear down the network.
4942 teardownUnneededNetwork(nai);
4943 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004944 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4945 // result in a partial connectivity result which will be processed by
4946 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004947 //
4948 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4949 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004950 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004951 }
4952 }
4953
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004954 private void handleSetAvoidUnvalidated(Network network) {
4955 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09004956 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004957 // Nothing to do. The network either disconnected or revalidated.
4958 return;
4959 }
Chalard Jean254bd162022-08-25 13:04:51 +09004960 if (0L == nai.getAvoidUnvalidated()) {
4961 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09004962 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004963 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004964 }
4965 }
4966
Chalard Jean5fb43c72022-09-08 19:03:14 +09004967 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09004968 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09004969 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004970 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09004971 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004972 }
4973
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004974 @Override
4975 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004976 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004977 mHandler.post(() -> {
4978 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4979 if (nai == null) return;
4980 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004981 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004982 });
4983 }
4984
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004985 /**
4986 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4987 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004988 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004989 * @param appExtras Bundle to use as intent extras for the captive portal application.
4990 * Must be treated as opaque to avoid preventing the captive portal app to
4991 * update its arguments.
4992 */
4993 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004994 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004995 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4996 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004997
4998 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4999 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005000 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5001 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005002 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5003
lucaslin75ff7022020-12-17 04:14:35 +08005004 final long token = Binder.clearCallingIdentity();
5005 try {
5006 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5007 } finally {
5008 Binder.restoreCallingIdentity(token);
5009 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005010 }
5011
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005012 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5013 private final Network mNetwork;
5014
5015 private CaptivePortalImpl(Network network) {
5016 mNetwork = network;
5017 }
5018
5019 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005020 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005021 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5022 enforceSettingsPermission();
5023 }
5024
Chiachang Wang938bfba2020-01-09 13:50:55 +08005025 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005026 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005027 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005028 }
5029
5030 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005031 public void appRequest(final int request) {
5032 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5033 if (nm == null) return;
5034
5035 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005036 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005037 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005038 }
5039 }
5040
5041 @Nullable
5042 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5043 // getNetworkAgentInfoForNetwork is thread-safe
5044 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5045 if (nai == null) return null;
5046
5047 // nai.networkMonitor() is thread-safe
5048 return nai.networkMonitor();
5049 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005050 }
5051
Hugo Benichic9048bc2016-09-14 23:23:08 +00005052 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005053 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005054 }
5055
Chalard Jean020b93a2022-09-01 13:20:14 +09005056 private boolean activelyPreferBadWifi() {
5057 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5058 }
5059
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005060 /**
5061 * Return whether the device should maintain continuous, working connectivity by switching away
5062 * from WiFi networks having no connectivity.
5063 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5064 */
5065 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005066 if (!checkNetworkStackPermission()) {
5067 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5068 }
5069 return avoidBadWifi();
5070 }
5071
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005072 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005073 ensureRunningOnConnectivityServiceThread();
5074 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005075 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005076 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005077 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005078 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5079 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5080 for (final NetworkOfferInfo noi : offersToUpdate) {
5081 updateOfferScore(noi.offer);
5082 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005083 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005084 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005085 }
5086
Erik Kline95ecfee2016-10-02 18:02:14 +09005087 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005088 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005089 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005090 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005091 if (!configRestrict) {
5092 pw.println("Bad Wi-Fi avoidance: unrestricted");
5093 return;
5094 }
5095
5096 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5097 pw.increaseIndent();
5098 pw.println("Config restrict: " + configRestrict);
Chalard Jean020b93a2022-09-01 13:20:14 +09005099 pw.println("Actively prefer: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005100
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005101 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005102 String description;
5103 // Can't use a switch statement because strings are legal case labels, but null is not.
5104 if ("0".equals(value)) {
5105 description = "get stuck";
5106 } else if (value == null) {
5107 description = "prompt";
5108 } else if ("1".equals(value)) {
5109 description = "avoid";
5110 } else {
5111 description = value + " (?)";
5112 }
5113 pw.println("User setting: " + description);
5114 pw.println("Network overrides:");
5115 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005116 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005117 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005118 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005119 }
5120 }
5121 pw.decreaseIndent();
5122 pw.decreaseIndent();
5123 }
5124
paulhu7746e4e2020-06-09 19:07:03 +08005125 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5126 // unify the method.
5127 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5128 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5129 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5130 return settingsComponent != null
5131 ? settingsComponent.getPackageName() : "com.android.settings";
5132 }
5133
lucaslinb1e8e382019-01-24 15:55:30 +08005134 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005135 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005136 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005137 switch (type) {
5138 case NO_INTERNET:
5139 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005140 // High priority because it is only displayed for explicitly selected networks.
5141 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005142 break;
lucasline117e2e2019-10-22 18:27:33 +08005143 case PRIVATE_DNS_BROKEN:
5144 action = Settings.ACTION_WIRELESS_SETTINGS;
5145 // High priority because we should let user know why there is no internet.
5146 highPriority = true;
5147 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005148 case LOST_INTERNET:
5149 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005150 // High priority because it could help the user avoid unexpected data usage.
5151 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005152 break;
lucaslin2240ef62019-03-12 13:08:03 +08005153 case PARTIAL_CONNECTIVITY:
5154 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005155 // Don't bother the user with a high-priority notification if the network was not
5156 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005157 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005158 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005159 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005160 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005161 return;
5162 }
5163
5164 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005165 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005166 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005167 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005168 // Some OEMs have their own Settings package. Thus, need to get the current using
5169 // Settings package name instead of just use default name "com.android.settings".
5170 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5171 intent.setClassName(settingsPkgName,
5172 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005173 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005174
paulhu2af50222020-10-11 22:52:27 +08005175 PendingIntent pendingIntent = PendingIntent.getActivity(
5176 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005177 0 /* requestCode */,
5178 intent,
paulhu2af50222020-10-11 22:52:27 +08005179 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005180
Serik Beketayevec8ad212020-12-07 22:43:07 -08005181 mNotifier.showNotification(
5182 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005183 }
5184
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005185 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5186 // Don't prompt if the network is validated, and don't prompt on captive portals
5187 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005188 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005189 return false;
5190 }
5191
5192 // If a network has partial connectivity, always prompt unless the user has already accepted
5193 // partial connectivity and selected don't ask again. This ensures that if the device
5194 // automatically connects to a network that has partial Internet access, the user will
5195 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005196 // because we have prompted them.
5197 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005198 return true;
5199 }
5200
5201 // If a network has no Internet access, only prompt if the network was explicitly selected
5202 // and if the user has not already told us to use the network regardless of whether it
5203 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005204 if (nai.networkAgentConfig.explicitlySelected
5205 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005206 return true;
5207 }
5208
5209 return false;
5210 }
5211
Chalard Jean5fb43c72022-09-08 19:03:14 +09005212 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5213 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005214
Chalard Jean5fb43c72022-09-08 19:03:14 +09005215 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5216 if (null == nai) return;
5217
5218 if (nai.setEvaluated()) {
5219 // If setEvaluated() returned true, the network never had any form of connectivity.
5220 // This may have an impact on request matching if bad WiFi avoidance is off and the
5221 // network was found not to have Internet access.
5222 nai.updateScoreForNetworkAgentUpdate();
5223 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005224 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005225
Chalard Jean5fb43c72022-09-08 19:03:14 +09005226 if (!shouldPromptUnvalidated(nai)) return;
5227
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005228 // Stop automatically reconnecting to this network in the future. Automatically connecting
5229 // to a network that provides no or limited connectivity is not useful, because the user
5230 // cannot use that network except through the notification shown by this method, and the
5231 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005232 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005233
Chalard Jean254bd162022-08-25 13:04:51 +09005234 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005235 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005236 } else {
5237 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5238 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005239 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005240
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005241 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5242 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005243 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005244
lucaslin2240ef62019-03-12 13:08:03 +08005245 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5246 return;
5247 }
5248
5249 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005250 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005251 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005252 }
5253
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005254 @Override
5255 public int getMultipathPreference(Network network) {
5256 enforceAccessPermission();
5257
5258 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005259 if (nai != null && nai.networkCapabilities
5260 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005261 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5262 }
5263
Aaron Huang9a57acf2020-12-08 10:03:29 +08005264 final NetworkPolicyManager netPolicyManager =
5265 mContext.getSystemService(NetworkPolicyManager.class);
5266
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005267 final long token = Binder.clearCallingIdentity();
5268 final int networkPreference;
5269 try {
5270 networkPreference = netPolicyManager.getMultipathPreference(network);
5271 } finally {
5272 Binder.restoreCallingIdentity(token);
5273 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005274 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005275 return networkPreference;
5276 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005277 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5278 }
5279
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005280 @Override
5281 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005282 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005283 }
5284
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005285 private class InternalHandler extends Handler {
5286 public InternalHandler(Looper looper) {
5287 super(looper);
5288 }
5289
5290 @Override
5291 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005292 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005293 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005294 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005295 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005296 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005297 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005298 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005299 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005300 break;
5301 }
Jason Monka69f1b02013-10-10 14:02:51 -04005302 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005303 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5304 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005305 break;
5306 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005307 case EVENT_REGISTER_NETWORK_PROVIDER: {
5308 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005309 break;
5310 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005311 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5312 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005313 break;
5314 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005315 case EVENT_REGISTER_NETWORK_OFFER: {
5316 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5317 break;
5318 }
5319 case EVENT_UNREGISTER_NETWORK_OFFER: {
5320 final NetworkOfferInfo offer =
5321 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5322 if (null != offer) {
5323 handleUnregisterNetworkOffer(offer);
5324 }
5325 break;
5326 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005327 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005328 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5329 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5330 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005331 break;
5332 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005333 case EVENT_REGISTER_NETWORK_REQUEST:
5334 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005335 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005336 break;
5337 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005338 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5339 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005340 handleRegisterNetworkRequestWithIntent(msg);
5341 break;
5342 }
Erik Kline155a59a2015-11-25 12:49:38 +09005343 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5344 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5345 handleTimedOutNetworkRequest(nri);
5346 break;
5347 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005348 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5349 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5350 break;
5351 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005352 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005353 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5354 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005355 break;
5356 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005357 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005358 Network network = (Network) msg.obj;
5359 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005360 break;
5361 }
lucaslin2240ef62019-03-12 13:08:03 +08005362 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5363 Network network = (Network) msg.obj;
5364 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5365 toBool(msg.arg2));
5366 break;
5367 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005368 case EVENT_SET_AVOID_UNVALIDATED: {
5369 handleSetAvoidUnvalidated((Network) msg.obj);
5370 break;
5371 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005372 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5373 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005374 break;
5375 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005376 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5377 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005378 break;
5379 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005380 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005381 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005382 mKeepaliveTracker.handleStartKeepalive(msg);
5383 break;
5384 }
5385 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005386 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005387 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5388 int slot = msg.arg1;
5389 int reason = msg.arg2;
5390 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5391 break;
5392 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005393 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5394 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5395 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005396 break;
5397 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005398 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5399 handlePrivateDnsSettingsChanged();
5400 break;
dalyk1720e542018-03-05 12:42:22 -05005401 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5402 handlePrivateDnsValidationUpdate(
5403 (PrivateDnsValidationUpdate) msg.obj);
5404 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005405 case EVENT_UID_BLOCKED_REASON_CHANGED:
5406 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005407 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005408 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5409 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5410 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005411 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005412 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5413 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005414 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005415 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005416 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005417 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005418 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5419 IOnCompleteListener> arg =
5420 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5421 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005422 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005423 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005424 }
lucaslin1193a5d2021-01-21 02:04:15 +08005425 case EVENT_REPORT_NETWORK_ACTIVITY:
5426 mNetworkActivityTracker.handleReportNetworkActivity();
5427 break;
paulhu51f77dc2021-06-07 02:34:20 +00005428 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5429 handleMobileDataPreferredUidsChanged();
5430 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005431 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5432 final long timeMs = ((Long) msg.obj).longValue();
5433 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5434 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005435 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5436 handleIngressRateLimitChanged();
5437 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005438 }
5439 }
5440 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -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 int getLastTetherError(String iface) {
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 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005449 }
5450
Lorenzo Colittid6459092016-07-04 12:55:44 +09005451 @Override
markchien5776f962019-12-16 20:15:20 +08005452 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005453 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005454 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005455 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5456 Context.TETHERING_SERVICE);
5457 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005458 }
5459
Lorenzo Colittid6459092016-07-04 12:55:44 +09005460 @Override
markchien5776f962019-12-16 20:15:20 +08005461 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005462 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005463 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005464 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5465 Context.TETHERING_SERVICE);
5466 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005467 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005468
markchien5776f962019-12-16 20:15:20 +08005469
Lorenzo Colittid6459092016-07-04 12:55:44 +09005470 @Override
markchien5776f962019-12-16 20:15:20 +08005471 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005472 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005473 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005474 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5475 Context.TETHERING_SERVICE);
5476
5477 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005478 }
5479
Lorenzo Colittid6459092016-07-04 12:55:44 +09005480 @Override
markchien5776f962019-12-16 20:15:20 +08005481 @Deprecated
5482 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005483 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005484 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5485 Context.TETHERING_SERVICE);
5486
5487 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005488 }
5489
Udam Saini8f7d6a72017-06-07 12:06:28 -07005490 @Override
markchien5776f962019-12-16 20:15:20 +08005491 @Deprecated
5492 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005493 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005494 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5495 Context.TETHERING_SERVICE);
5496 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005497 }
5498
Robert Greenwalte0b00512014-07-02 09:59:16 -07005499 // Called when we lose the default network and have no replacement yet.
5500 // This will automatically be cleared after X seconds or a new default network
5501 // becomes CONNECTED, whichever happens first. The timer is started by the
5502 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005503 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005504 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005505 if (mNetTransitionWakeLock.isHeld()) {
5506 return;
5507 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005508 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005509 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5510 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005511 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005512 mWakelockLogs.log("ACQUIRE for " + forWhom);
5513 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005514 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005515 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005516 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005517 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005518
Hugo Benichi471b62a2017-03-30 23:18:10 +09005519 // Called when we gain a new default network to release the network transition wakelock in a
5520 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5521 // message is cancelled.
5522 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005523 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005524 if (!mNetTransitionWakeLock.isHeld()) {
5525 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005526 }
5527 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005528 // Cancel self timeout on wakelock hold.
5529 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5530 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5531 mHandler.sendMessageDelayed(msg, 1000);
5532 }
5533
5534 // Called when either message of ensureNetworkTransitionWakelock or
5535 // scheduleReleaseNetworkTransitionWakelock is processed.
5536 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5537 String event = eventName(eventId);
5538 synchronized (this) {
5539 if (!mNetTransitionWakeLock.isHeld()) {
5540 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005541 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005542 return;
5543 }
5544 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005545 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5546 mTotalWakelockDurationMs += lockDuration;
5547 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5548 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005549 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005550 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005551 }
5552
Robert Greenwalt986c7412010-09-08 15:24:47 -07005553 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005554 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005555 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005556 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005557 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005558 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005559 }
5560
Lorenzo Colittid6459092016-07-04 12:55:44 +09005561 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005562 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005563 enforceAccessPermission();
5564 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005565 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005566 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005567
5568 final NetworkAgentInfo nai;
5569 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005570 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005571 } else {
5572 nai = getNetworkAgentInfoForNetwork(network);
5573 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005574
5575 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005576 mHandler.obtainMessage(
5577 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005578 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005579
Hugo Benichid6b510a2017-04-06 17:22:18 +09005580 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005581 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005582 if (nai == null
5583 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005584 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005585 return;
5586 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005587 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005588 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005589 mConnectivityDiagnosticsHandler.sendMessage(
5590 mConnectivityDiagnosticsHandler.obtainMessage(
5591 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5592 new ReportedNetworkConnectivityInfo(
5593 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005594 return;
5595 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005596 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005597 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005598 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005599 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005600 // Validating a network that has not yet connected could result in a call to
5601 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005602 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005603 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005604 }
paulhu7aeba372020-12-30 00:42:19 +08005605 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5606 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005607 return;
5608 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005609
5610 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5611 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5612 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5613 // completed.
5614 mConnectivityDiagnosticsHandler.sendMessage(
5615 mConnectivityDiagnosticsHandler.obtainMessage(
5616 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5617 new ReportedNetworkConnectivityInfo(
5618 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005619 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005620 }
5621
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005622 // TODO: call into netd.
5623 private boolean queryUserAccess(int uid, Network network) {
5624 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5625 if (nai == null) return false;
5626
5627 // Any UID can use its default network.
5628 if (nai == getDefaultNetworkForUid(uid)) return true;
5629
5630 // Privileged apps can use any network.
5631 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5632 return true;
5633 }
5634
5635 // An unprivileged UID can use a VPN iff the VPN applies to it.
5636 if (nai.isVPN()) {
5637 return nai.networkCapabilities.appliesToUid(uid);
5638 }
5639
5640 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5641 // sockets, i.e., if it is the owner.
5642 final NetworkAgentInfo vpn = getVpnForUid(uid);
5643 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5644 && uid != vpn.networkCapabilities.getOwnerUid()) {
5645 return false;
5646 }
5647
5648 // The UID's permission must be at least sufficient for the network. Since the restricted
5649 // permission was already checked above, that just leaves background networks.
5650 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5651 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5652 }
5653
5654 // Unrestricted network. Anyone gets to use it.
5655 return true;
5656 }
5657
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005658 /**
5659 * Returns information about the proxy a certain network is using. If given a null network, it
5660 * it will return the proxy for the bound network for the caller app or the default proxy if
5661 * none.
5662 *
5663 * @param network the network we want to get the proxy information for.
5664 * @return Proxy information if a network has a proxy configured, or otherwise null.
5665 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005666 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005667 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005668 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005669 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005670 if (network == null) {
5671 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005672 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005673 true);
5674 if (activeNetwork == null) {
5675 return null;
5676 }
5677 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005678 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005679 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5680 // caller may not have.
5681 return getLinkPropertiesProxyInfo(network);
5682 }
5683 // No proxy info available if the calling UID does not have network access.
5684 return null;
5685 }
5686
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005687
5688 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005689 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5690 if (nai == null) return null;
5691 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005692 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5693 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005694 }
5695 }
5696
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005697 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005698 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005699 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005700 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005701 }
5702
Chalard Jean777e2e52018-06-07 18:02:37 +09005703 @Override
5704 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005705 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005706 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005707 }
5708
Jason Monk4d5e20f2014-04-25 15:00:09 -04005709 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005710 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005711 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005712 proxy = null;
5713 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005714 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005715 }
5716
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005717 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5718 // when any network changes proxy.
5719 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5720 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005721 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005722 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5723 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5724
Chalard Jean7d97afc2018-06-07 17:41:29 +09005725 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005726 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005727 }
5728 }
5729
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005730 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005731 final private HashMap<Uri, Integer> mUriEventMap;
5732 final private Context mContext;
5733 final private Handler mHandler;
5734
5735 SettingsObserver(Context context, Handler handler) {
5736 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005737 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005738 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005739 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005740 }
5741
Erik Kline05f2b402015-04-30 12:58:40 +09005742 void observe(Uri uri, int what) {
5743 mUriEventMap.put(uri, what);
5744 final ContentResolver resolver = mContext.getContentResolver();
5745 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005746 }
5747
5748 @Override
5749 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005750 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005751 }
5752
5753 @Override
5754 public void onChange(boolean selfChange, Uri uri) {
5755 final Integer what = mUriEventMap.get(uri);
5756 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005757 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005758 } else {
5759 loge("No matching event to send for URI=" + uri);
5760 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005761 }
5762 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005763
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005764 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005765 Log.d(TAG, s);
5766 }
5767
5768 private static void logw(String s) {
5769 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005770 }
5771
Daniel Brightf9e945b2020-06-15 16:10:01 -07005772 private static void logwtf(String s) {
5773 Log.wtf(TAG, s);
5774 }
5775
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005776 private static void logwtf(String s, Throwable t) {
5777 Log.wtf(TAG, s, t);
5778 }
5779
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005780 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005781 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005782 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005783
Hugo Benichi39621362017-02-11 17:04:43 +09005784 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005785 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005786 }
5787
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005788 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005789 * Return the information of all ongoing VPNs.
5790 *
5791 * <p>This method is used to update NetworkStatsService.
5792 *
5793 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005794 */
junyulai2050bed2021-01-23 09:46:34 +08005795 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005796 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005797 if (mLockdownEnabled) {
5798 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005799 }
junyulai2050bed2021-01-23 09:46:34 +08005800 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005801 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005802 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005803 if (info != null) {
5804 infoList.add(info);
5805 }
5806 }
junyulai2050bed2021-01-23 09:46:34 +08005807 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005808 }
5809
5810 /**
5811 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005812 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005813 */
junyulai2050bed2021-01-23 09:46:34 +08005814 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005815 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005816 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5817 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005818 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5819 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5820 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005821 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5822 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005823 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005824 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005825 }
5826 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005827
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005828 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005829
5830 List<String> interfaces = new ArrayList<>();
5831 for (Network network : underlyingNetworks) {
5832 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5833 if (underlyingNai == null) continue;
5834 LinkProperties lp = underlyingNai.linkProperties;
5835 for (String iface : lp.getAllInterfaceNames()) {
5836 if (!TextUtils.isEmpty(iface)) {
5837 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005838 }
5839 }
Benedict Wong34857f82019-06-12 17:46:15 +00005840 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005841
5842 if (interfaces.isEmpty()) return null;
5843
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005844 // Must be non-null or NetworkStatsService will crash.
5845 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5846 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005847 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005848 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005849
junyulai2050bed2021-01-23 09:46:34 +08005850 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5851 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005852 }
5853
James Mattisd31bdfa2020-12-23 16:37:26 -08005854 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005855 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5856 Network[] underlyingNetworks) {
5857 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005858 if (underlyingNetworks == null && defaultNetwork != null) {
5859 // null underlying networks means to track the default.
5860 underlyingNetworks = new Network[] { defaultNetwork };
5861 }
5862 return underlyingNetworks;
5863 }
5864
5865 // Returns true iff |network| is an underlying network of |nai|.
5866 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5867 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5868 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005869 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005870 final Network[] underlying = underlyingNetworksOrDefault(
5871 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005872 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005873 }
5874
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005875 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005876 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005877 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005878 * When underlying networks change, such networks may have to update capabilities to reflect
5879 * things like the metered bit, their transports, and so on. The capabilities are calculated
5880 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005881 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005882 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005883 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005884 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005885 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005886 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005887 }
5888 }
5889 }
5890
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005891 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5892 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5893 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5894 // a VPN is not up.
5895 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5896 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5897 for (UidRange range : blockedUidRanges) {
5898 if (range.contains(uid)) return true;
5899 }
5900 return false;
5901 }
5902
5903 @Override
5904 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005905 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005906 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5907 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5908 }
5909
5910 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5911 if (DBG) {
5912 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5913 + Arrays.toString(ranges));
5914 }
5915 // Cannot use a Set since the list of UID ranges might contain duplicates.
5916 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5917 for (int i = 0; i < ranges.length; i++) {
5918 if (requireVpn) {
5919 newVpnBlockedUidRanges.add(ranges[i]);
5920 } else {
5921 newVpnBlockedUidRanges.remove(ranges[i]);
5922 }
5923 }
5924
5925 try {
5926 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5927 } catch (RemoteException | ServiceSpecificException e) {
5928 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5929 + Arrays.toString(ranges) + "): netd command failed: " + e);
5930 }
5931
Motomu Utsumib08654c2022-05-11 05:56:26 +00005932 if (SdkLevel.isAtLeastT()) {
5933 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5934 }
5935
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005936 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5937 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005938 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5939 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005940 }
5941
5942 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5943 }
5944
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005945 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005946 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005947 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005948 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005949 }
5950
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005951 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5952 return mLockdownEnabled
5953 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5954 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005955 }
5956
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005957 private NetworkAgentInfo getLegacyLockdownNai() {
5958 if (!mLockdownEnabled) {
5959 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005960 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005961 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005962 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5963 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005964
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005965 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005966 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5967 // a local variable. There is no need to make a copy because its contents cannot change.
5968 final Network[] underlying = nai.declaredUnderlyingNetworks;
5969 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005970 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005971 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005972
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005973 // The legacy lockdown VPN always uses the default network.
5974 // If the VPN's underlying network is no longer the current default network, it means that
5975 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005976 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5977 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005978 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005979 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005980 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005981 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005982
5983 return nai;
5984 };
5985
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005986 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5987 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5988 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005989 private DetailedState getLegacyLockdownState(DetailedState origState) {
5990 if (origState != DetailedState.CONNECTED) {
5991 return origState;
5992 }
5993 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5994 ? DetailedState.CONNECTING
5995 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005996 }
5997
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005998 private void filterForLegacyLockdown(NetworkInfo ni) {
5999 if (!mLockdownEnabled || !ni.isConnected()) return;
6000 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6001 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6002 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6003 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6004 // network, this time with a state of CONNECTED.
6005 //
6006 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6007 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6008 // is not too far off the truth, since an always-on VPN, when not connected, is always
6009 // trying to reconnect.
6010 if (getLegacyLockdownNai() == null) {
6011 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6012 }
6013 }
6014
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006015 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006016 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006017 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006018 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006019 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6020 return;
6021 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006022 final long ident = Binder.clearCallingIdentity();
6023 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006024 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006025 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006026 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006027 } finally {
6028 Binder.restoreCallingIdentity(ident);
6029 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006030 }
Wink Savillecb117d32013-08-29 14:57:08 -07006031
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006032 @Override
6033 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006034 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006035 final long ident = Binder.clearCallingIdentity();
6036 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006037 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006038 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006039 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6040 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006041 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006042 } finally {
6043 Binder.restoreCallingIdentity(ident);
6044 }
6045 }
6046
James Mattis02220e22021-03-13 19:27:21 -08006047 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006048 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006049 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6050 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6051 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006052 }
6053
James Mattis02220e22021-03-13 19:27:21 -08006054 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006055 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006056 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006057 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006058 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006059 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006060 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6061 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6062 }
junyulaid91e7052020-08-28 13:44:33 +08006063 }
6064
James Mattis02220e22021-03-13 19:27:21 -08006065 private void onPackageChanged(@NonNull final String packageName) {
6066 // This is necessary in case a package is added or removed, but also when it's replaced to
6067 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6068 // as one in the preferences, then it should follow the same routing as that other package,
6069 // which means updating the rules is never to be needed in this case (whether it joins or
6070 // leaves a UID with a preference).
6071 if (isMappedInOemNetworkPreference(packageName)) {
6072 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6073 }
6074 }
6075
6076 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006077 @Override
6078 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006079 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006080 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006081 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006082
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006083 // User should be filled for below intents, check the existence.
6084 if (user == null) {
6085 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6086 return;
6087 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006088
Lorenzo Colitticd675292021-02-04 17:32:07 +09006089 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006090 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006091 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006092 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006093 } else {
junyulaid91e7052020-08-28 13:44:33 +08006094 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006095 }
6096 }
6097 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006098
James Mattis02220e22021-03-13 19:27:21 -08006099 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6100 @Override
6101 public void onReceive(Context context, Intent intent) {
6102 ensureRunningOnConnectivityServiceThread();
6103 switch (intent.getAction()) {
6104 case Intent.ACTION_PACKAGE_ADDED:
6105 case Intent.ACTION_PACKAGE_REMOVED:
6106 case Intent.ACTION_PACKAGE_REPLACED:
6107 onPackageChanged(intent.getData().getSchemeSpecificPart());
6108 break;
6109 default:
6110 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6111 }
6112 }
6113 };
6114
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006115 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006116 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006117
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006118 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006119 public final String name;
6120 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006121 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006122 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006123
lifraf3a3492021-03-10 13:58:14 +08006124 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6125 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006126 this.name = name;
6127 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006128 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006129 mDeathRecipient = deathRecipient;
6130
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006131 if (mDeathRecipient == null) {
6132 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006133 }
6134 }
6135
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006136 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006137 try {
6138 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6139 } catch (RemoteException e) {
6140 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006141 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006142 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006143 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006144
James Mattis4fce5d12020-11-12 15:53:42 -08006145 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6146 for (int i = 0; i < requests.size(); i++) {
6147 ensureNetworkRequestHasType(requests.get(i));
6148 }
6149 }
6150
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006151 private void ensureNetworkRequestHasType(NetworkRequest request) {
6152 if (request.type == NetworkRequest.Type.NONE) {
6153 throw new IllegalArgumentException(
6154 "All NetworkRequests in ConnectivityService must have a type");
6155 }
6156 }
6157
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006158 /**
6159 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006160 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006161 */
James Mattis258ea3c2020-11-15 15:04:40 -08006162 @VisibleForTesting
6163 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006164 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6165 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006166 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006167
James Mattisa076c532020-12-02 14:12:41 -08006168 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6169 void setSatisfier(
6170 @Nullable final NetworkAgentInfo satisfier,
6171 @Nullable final NetworkRequest activeRequest) {
6172 mSatisfier = satisfier;
6173 mActiveRequest = activeRequest;
6174 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006175
James Mattisd31bdfa2020-12-23 16:37:26 -08006176 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006177 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006178 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006179 private NetworkAgentInfo mSatisfier;
6180 NetworkAgentInfo getSatisfier() {
6181 return mSatisfier;
6182 }
6183
6184 // The request in mRequests assigned to a network agent. This is null if none of the
6185 // requests in mRequests can be satisfied. This member has the constraint of only being
6186 // accessible on the handler thread.
6187 @Nullable
6188 private NetworkRequest mActiveRequest;
6189 NetworkRequest getActiveRequest() {
6190 return mActiveRequest;
6191 }
6192
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006193 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006194 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006195 @Nullable
6196 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006197
6198 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006199 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006200 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006201 final int mPid;
6202 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006203 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006204 @Nullable
6205 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006206
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006207 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006208 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006209
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006210 // Effective UID of this request. This is different from mUid when a privileged process
6211 // files a request on behalf of another UID. This UID is used to determine blocked status,
6212 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6213 // maximum limit of registered callbacks per UID.
6214 final int mAsUid;
6215
paulhu48291862021-07-14 14:53:57 +08006216 // Preference order of this request.
6217 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006218
James Mattis3ce3d3c2021-02-09 18:18:28 -08006219 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6220 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6221 // maintained for keying off of. This is only a concern when the original nri
6222 // mNetworkRequests changes which happens currently for apps that register callbacks to
6223 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6224 // that match the per-app default nri that currently tracks the calling app's uid so that
6225 // callbacks are fired at the appropriate time. When the callbacks fire,
6226 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6227 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6228 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6229 @NonNull
6230 private final NetworkRequest mNetworkRequestForCallback;
6231 NetworkRequest getNetworkRequestForCallback() {
6232 return mNetworkRequestForCallback;
6233 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006234
James Mattisd31bdfa2020-12-23 16:37:26 -08006235 /**
6236 * Get the list of UIDs this nri applies to.
6237 */
6238 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006239 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006240 // networkCapabilities.getUids() returns a defensive copy.
6241 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006242 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6243 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006244 }
6245
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006246 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6247 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006248 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006249 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006250 }
6251
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006252 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006253 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006254 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006255 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006256 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006257 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006258 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006259 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006260 mBinder = null;
6261 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006262 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006263 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006264 mPerUidCounter = getRequestCounter(this);
6265 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006266 /**
6267 * Location sensitive data not included in pending intent. Only included in
6268 * {@link NetworkCallback}.
6269 */
6270 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006271 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006272 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006273 }
6274
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006275 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006276 @Nullable final IBinder binder,
6277 @NetworkCallback.Flag int callbackFlags,
6278 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006279 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6280 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006281 }
6282
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006283 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006284 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006285 @Nullable final IBinder binder,
6286 @NetworkCallback.Flag int callbackFlags,
6287 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006288 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006289 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006290 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006291 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006292 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006293 mBinder = binder;
6294 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006295 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006296 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006297 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006298 mPerUidCounter = getRequestCounter(this);
6299 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006300 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006301 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006302 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006303 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006304 }
6305
James Mattis3ce3d3c2021-02-09 18:18:28 -08006306 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6307 @NonNull final List<NetworkRequest> r) {
6308 super();
6309 ensureAllNetworkRequestsHaveType(r);
6310 mRequests = initializeRequests(r);
6311 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006312 final NetworkAgentInfo satisfier = nri.getSatisfier();
6313 if (null != satisfier) {
6314 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6315 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006316 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006317 // As this code creates a new NRI with a new set of requests, figure out which of
6318 // the list of requests should be the active request. It is always the first
6319 // request of the list that can be satisfied by the satisfier since the order of
6320 // requests is a priority order.
6321 // Note even in the presence of a satisfier there may not be an active request,
6322 // when the satisfier is the no-service network.
6323 NetworkRequest activeRequest = null;
6324 for (final NetworkRequest candidate : r) {
6325 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6326 activeRequest = candidate;
6327 break;
6328 }
6329 }
6330 setSatisfier(satisfier, activeRequest);
6331 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006332 mMessenger = nri.mMessenger;
6333 mBinder = nri.mBinder;
6334 mPid = nri.mPid;
6335 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006336 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006337 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006338 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006339 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006340 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006341 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006342 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006343 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006344 }
6345
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006346 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006347 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006348 }
6349
paulhue9913722021-05-26 15:19:20 +08006350 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006351 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006352 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006353 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006354 }
6355
James Mattis2516da32021-01-31 17:06:19 -08006356 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6357 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6358 // false.
6359 boolean isBeingSatisfied() {
6360 return (null != mSatisfier && null != mActiveRequest);
6361 }
6362
James Mattis3d229892020-11-16 16:46:28 -08006363 boolean isMultilayerRequest() {
6364 return mRequests.size() > 1;
6365 }
6366
James Mattis45d81842021-01-10 14:24:24 -08006367 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6368 // Creating a defensive copy to prevent the sender from modifying the list being
6369 // reflected in the return value of this method.
6370 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006371 return Collections.unmodifiableList(tempRequests);
6372 }
6373
James Mattisb1392002021-03-31 13:57:52 -07006374 void linkDeathRecipient() {
6375 if (null != mBinder) {
6376 try {
6377 mBinder.linkToDeath(this, 0);
6378 } catch (RemoteException e) {
6379 binderDied();
6380 }
6381 }
6382 }
6383
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006384 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006385 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006386 try {
6387 mBinder.unlinkToDeath(this, 0);
6388 } catch (NoSuchElementException e) {
6389 // Temporary workaround for b/194394697 pending analysis of additional logs
6390 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6391 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006392 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006393 }
6394
paulhu48291862021-07-14 14:53:57 +08006395 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6396 // Compare two preference orders.
6397 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006398 }
6399
paulhu48291862021-07-14 14:53:57 +08006400 int getPreferenceOrderForNetd() {
6401 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6402 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6403 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006404 }
paulhu48291862021-07-14 14:53:57 +08006405 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006406 }
6407
James Mattis4fce5d12020-11-12 15:53:42 -08006408 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006409 public void binderDied() {
6410 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006411 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006412 // As an immutable collection, mRequests cannot change by the time the
6413 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6414 // is acceptable. Use handleReleaseNetworkRequest and not directly
6415 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6416 // the app already unregistered the request.
6417 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6418 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006419 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006420
James Mattis4fce5d12020-11-12 15:53:42 -08006421 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006422 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006423 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6424 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006425 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006426 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006427 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006428 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006429 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006430 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006431 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006432 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006433 }
6434
Junyu Lai00d92df2022-07-05 11:01:52 +08006435 // Keep backward compatibility since the ServiceSpecificException is used by
6436 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6437 public static class RequestInfoPerUidCounter extends PerUidCounter {
6438 RequestInfoPerUidCounter(int maxCountPerUid) {
6439 super(maxCountPerUid);
6440 }
6441
6442 @Override
6443 public synchronized void incrementCountOrThrow(int uid) {
6444 try {
6445 super.incrementCountOrThrow(uid);
6446 } catch (IllegalStateException e) {
6447 throw new ServiceSpecificException(
6448 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6449 "Uid " + uid + " exceeded its allotted requests limit");
6450 }
6451 }
6452
6453 @Override
6454 public synchronized void decrementCountOrThrow(int uid) {
6455 throw new UnsupportedOperationException("Use decrementCount instead.");
6456 }
6457
6458 public synchronized void decrementCount(int uid) {
6459 try {
6460 super.decrementCountOrThrow(uid);
6461 } catch (IllegalStateException e) {
6462 logwtf("Exception when decrement per uid request count: ", e);
6463 }
6464 }
6465 }
6466
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006467 // This checks that the passed capabilities either do not request a
6468 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006469 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006470 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006471 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006472 throw new SecurityException("Insufficient permissions to request a specific SSID");
6473 }
paulhu1a407652019-03-22 16:35:06 +08006474
6475 if (nc.hasSignalStrength()
6476 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6477 throw new SecurityException(
6478 "Insufficient permissions to request a specific signal strength");
6479 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006480 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006481
junyulai2217bec2021-04-14 23:33:31 +08006482 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006483 enforceNetworkFactoryPermission();
6484 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006485 }
6486
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006487 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006488 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006489 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006490 // mNetworkRequests may contain the same value multiple times in case of
6491 // multilayer requests. It won't matter in this case because the thresholds
6492 // will then be the same and be deduplicated as they enter the `thresholds` set.
6493 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006494 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6495 for (final NetworkRequest req : nri.mRequests) {
6496 if (req.networkCapabilities.hasSignalStrength()
6497 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6498 thresholds.add(req.networkCapabilities.getSignalStrength());
6499 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006500 }
6501 }
6502 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006503 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006504 }
6505
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006506 private void updateSignalStrengthThresholds(
6507 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006508 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006509
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006510 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006511 String detail;
6512 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6513 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6514 } else {
6515 detail = reason;
6516 }
6517 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006518 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006519 }
6520
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006521 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006522 }
6523
Chalard Jeandd421992021-12-16 23:16:02 +09006524 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006525 if (nc == null) {
6526 return;
6527 }
6528 NetworkSpecifier ns = nc.getNetworkSpecifier();
6529 if (ns == null) {
6530 return;
6531 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006532 if (ns instanceof MatchAllNetworkSpecifier) {
6533 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6534 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006535 }
6536
Chalard Jeandd421992021-12-16 23:16:02 +09006537 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006538 ensureValidNetworkSpecifier(nc);
6539 if (nc.isPrivateDnsBroken()) {
6540 throw new IllegalArgumentException("Can't request broken private DNS");
6541 }
Chalard Jeande665262022-02-25 16:12:12 +09006542 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006543 throw new IllegalArgumentException("Can't request access UIDs");
6544 }
lucasline117e2e2019-10-22 18:27:33 +08006545 }
6546
Chalard Jeandd421992021-12-16 23:16:02 +09006547 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6548 ensureListenableCapabilities(nc);
6549 final String badCapability = nc.describeFirstNonRequestableCapability();
6550 if (badCapability != null) {
6551 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6552 }
6553 }
6554
Chiachang Wang3bc52762021-11-25 14:17:57 +08006555 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6556 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006557 private boolean isTargetSdkAtleast(int version, int callingUid,
6558 @NonNull String callingPackageName) {
6559 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006560 final PackageManager pm =
6561 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006562 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006563 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006564 if (callingVersion < version) return false;
6565 } catch (PackageManager.NameNotFoundException e) { }
6566 return true;
6567 }
6568
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006569 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006570 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006571 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006572 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006573 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006574 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006575 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6576 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006577 throw new SecurityException("Insufficient permissions to specify legacy type");
6578 }
markchienfac84a22020-03-18 21:16:15 +08006579 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006580 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006581 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006582 // Privileged callers can track the default network of another UID by passing in a UID.
6583 if (asUid != Process.INVALID_UID) {
6584 enforceSettingsPermission();
6585 } else {
6586 asUid = callingUid;
6587 }
junyulaiad010792021-01-11 16:53:38 +08006588 final NetworkRequest.Type reqType;
6589 try {
6590 reqType = NetworkRequest.Type.values()[reqTypeInt];
6591 } catch (ArrayIndexOutOfBoundsException e) {
6592 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6593 }
6594 switch (reqType) {
6595 case TRACK_DEFAULT:
6596 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006597 // is unused and will be replaced by ones appropriate for the UID (usually, the
6598 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006599 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006600 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006601 enforceAccessPermission();
6602 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006603 case TRACK_SYSTEM_DEFAULT:
6604 enforceSettingsPermission();
6605 networkCapabilities = new NetworkCapabilities(defaultNc);
6606 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006607 case BACKGROUND_REQUEST:
6608 enforceNetworkStackOrSettingsPermission();
6609 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006610 case REQUEST:
6611 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6612 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006613 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006614 // TODO: this is incorrect. We mark the request as metered or not depending on
6615 // the state of the app when the request is filed, but we never change the
6616 // request if the app changes network state. http://b/29964605
6617 enforceMeteredApnPolicy(networkCapabilities);
6618 break;
junyulai1b1c8742021-03-12 20:05:08 +08006619 case LISTEN_FOR_BEST:
6620 enforceAccessPermission();
6621 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6622 break;
junyulaiad010792021-01-11 16:53:38 +08006623 default:
6624 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006625 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006626 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006627 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006628 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006629
junyulai1b1c8742021-03-12 20:05:08 +08006630 // Enforce FOREGROUND if the caller does not have permission to use background network.
6631 if (reqType == LISTEN_FOR_BEST) {
6632 restrictBackgroundRequestForCaller(networkCapabilities);
6633 }
6634
6635 // Set the UID range for this request to the single UID of the requester, unless the
6636 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006637 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6638 // are no visible methods to set the UIDs, an app could use reflection to try and get
6639 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006640 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006641 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6642 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006643
Etan Cohen85000162017-02-05 10:42:27 -08006644 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006645 throw new IllegalArgumentException("Bad timeout specified");
6646 }
Etan Cohen9786d922015-11-18 10:56:15 -08006647
James Mattis3ce3d3c2021-02-09 18:18:28 -08006648 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006649 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006650 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006651 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006652 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006653 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006654
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006655 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6656 // copied from the default request above. (This is necessary to ensure, for example, that
6657 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6658 // changes don't alter request matching.
6659 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6660 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006661 throw new IllegalStateException(
6662 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006663 + networkCapabilities + " vs. " + defaultNc);
6664 }
6665
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006666 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006667 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006668 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006669 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006670 }
6671 return networkRequest;
6672 }
6673
James Mattis3ce3d3c2021-02-09 18:18:28 -08006674 /**
6675 * Return the nri to be used when registering a network request. Specifically, this is used with
6676 * requests registered to track the default request. If there is currently a per-app default
6677 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6678 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006679 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6680 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006681 * @param nr the network request for the nri.
6682 * @param msgr the messenger for the nri.
6683 * @param binder the binder for the nri.
6684 * @param callingAttributionTag the calling attribution tag for the nri.
6685 * @return the nri to register.
6686 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006687 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006688 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006689 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006690 @Nullable String callingAttributionTag) {
6691 final List<NetworkRequest> requests;
6692 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6693 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006694 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006695 } else {
6696 requests = Collections.singletonList(nr);
6697 }
Roshan Pius951c0032020-12-22 15:10:42 -08006698 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006699 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006700 }
6701
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006702 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006703 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006704 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006705 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6706 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6707 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6708 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006709 }
junyulai96bd9fe2022-03-08 17:36:42 +08006710 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006711 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006712 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006713 }
6714 }
6715
fenglu3f357402015-03-20 11:29:56 -07006716 @Override
fenglub00f4882015-04-21 17:12:05 -07006717 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006718 enforceAccessPermission();
6719 NetworkAgentInfo nai = null;
6720 if (network == null) {
6721 return false;
6722 }
6723 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006724 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006725 }
6726 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006727 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006728 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006729 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006730 Integer uidReqs = mBandwidthRequests.get(uid);
6731 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006732 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006733 }
6734 mBandwidthRequests.put(uid, ++uidReqs);
6735 }
fenglu3f357402015-03-20 11:29:56 -07006736 return true;
6737 }
6738 return false;
6739 }
6740
Felipe Leme0a5ae422016-06-20 16:36:29 -07006741 private boolean isSystem(int uid) {
6742 return uid < Process.FIRST_APPLICATION_UID;
6743 }
fenglu3f357402015-03-20 11:29:56 -07006744
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006745 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006746 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006747 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006748 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006749 return;
6750 }
Hugo Benichi39621362017-02-11 17:04:43 +09006751 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6752 // Policy already enforced.
6753 return;
6754 }
paulhuaf50d7d2020-12-24 19:47:34 +08006755 final long ident = Binder.clearCallingIdentity();
6756 try {
6757 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6758 // If UID is restricted, don't allow them to bring up metered APNs.
6759 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6760 }
6761 } finally {
6762 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006763 }
6764 }
6765
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006766 @Override
6767 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006768 PendingIntent operation, @NonNull String callingPackageName,
6769 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006770 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006771 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006772 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006773 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006774 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006775 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006776 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006777 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006778 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006779 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6780 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006781
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006782 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006783 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006784 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6785 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006786 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006787 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6788 nri));
6789 return networkRequest;
6790 }
6791
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006792 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6793 mHandler.sendMessageDelayed(
6794 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006795 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006796 }
6797
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006798 @Override
6799 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006800 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006801 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006802 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006803 }
6804
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006805 // In order to implement the compatibility measure for pre-M apps that call
6806 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6807 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6808 // This ensures it has permission to do so.
6809 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6810 if (nc == null) {
6811 return false;
6812 }
6813 int[] transportTypes = nc.getTransportTypes();
6814 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6815 return false;
6816 }
6817 try {
6818 mContext.enforceCallingOrSelfPermission(
6819 android.Manifest.permission.ACCESS_WIFI_STATE,
6820 "ConnectivityService");
6821 } catch (SecurityException e) {
6822 return false;
6823 }
6824 return true;
6825 }
6826
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006827 @Override
6828 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006829 Messenger messenger, IBinder binder,
6830 @NetworkCallback.Flag int callbackFlags,
6831 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006832 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006833 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6834 enforceAccessPermission();
6835 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006836
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006837 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006838 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006839 Binder.getCallingPid(), callingUid, callingPackageName);
6840 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006841 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6842 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6843 // onLost and onAvailable callbacks when networks move in and out of the background.
6844 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6845 // can't request networks.
6846 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006847 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006848
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006849 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006850 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006851 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006852 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006853 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006854 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006855
6856 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6857 return networkRequest;
6858 }
6859
6860 @Override
6861 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006862 PendingIntent operation, @NonNull String callingPackageName,
6863 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006864 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006865 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006866 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6867 enforceAccessPermission();
6868 }
Chalard Jeandd421992021-12-16 23:16:02 +09006869 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006870 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006871 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006872 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006873 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006874
6875 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006876 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006877 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6878 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006879 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006880
WeiZhang1cc3f172021-06-03 19:02:04 -05006881 mHandler.sendMessage(mHandler.obtainMessage(
6882 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006883 }
6884
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006885 /** Returns the next Network provider ID. */
6886 public final int nextNetworkProviderId() {
6887 return mNextNetworkProviderId.getAndIncrement();
6888 }
6889
Erik Kline0c04b742016-07-07 16:50:58 +09006890 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006891 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006892 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006893 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006894 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006895 }
6896
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006897 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6898 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006899 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6900 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6901 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006902 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006903 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006904 return;
6905 }
6906
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006907 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6908 mNetworkProviderInfos.put(npi.messenger, npi);
6909 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006910 }
6911
6912 @Override
6913 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006914 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006915 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006916 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006917 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006918 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6919 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006920 }
6921
6922 @Override
6923 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006924 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006925 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006926 }
6927
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006928 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006929 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006930 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6931 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006932 Objects.requireNonNull(score);
6933 Objects.requireNonNull(caps);
6934 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006935 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006936 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006937 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6938 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006939 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6940 }
6941
Chalard Jeanbb902a52021-08-18 01:35:19 +09006942 private void updateOfferScore(final NetworkOffer offer) {
6943 final boolean yieldToBadWiFi =
6944 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6945 final NetworkOffer newOffer = new NetworkOffer(
6946 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6947 offer.caps, offer.callback, offer.providerId);
6948 if (offer.equals(newOffer)) return;
6949 handleRegisterNetworkOffer(newOffer);
6950 }
6951
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006952 @Override
6953 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006954 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006955 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6956 }
6957
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006958 private void handleUnregisterNetworkProvider(Messenger messenger) {
6959 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6960 if (npi == null) {
6961 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006962 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006963 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006964 // Unregister all the offers from this provider
6965 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6966 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006967 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006968 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6969 toRemove.add(noi);
6970 }
6971 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006972 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006973 handleUnregisterNetworkOffer(noi);
6974 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006975 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006976 }
6977
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006978 @Override
James Mattisf7027322020-12-13 16:28:14 -08006979 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006980 if (request.hasTransport(TRANSPORT_TEST)) {
6981 enforceNetworkFactoryOrTestNetworksPermission();
6982 } else {
6983 enforceNetworkFactoryPermission();
6984 }
James Mattisf7027322020-12-13 16:28:14 -08006985 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6986 if (nri != null) {
6987 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6988 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6989 mHandler.post(() -> handleReleaseNetworkRequest(
6990 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6991 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006992 }
6993
Paul Jensen1f567382015-02-13 14:18:39 -05006994 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6995 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006996 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006997 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006998 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006999 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007000 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007001
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007002 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007003 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007004 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007005
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007006 // UID ranges for users that are currently blocked by VPNs.
7007 // This array is accessed and iterated on multiple threads without holding locks, so its
7008 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7009 // (on the handler thread).
7010 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7011
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007012 // Must only be accessed on the handler thread
7013 @NonNull
7014 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7015
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007016 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007017 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007018
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007019 // Current OEM network preferences. This object must only be written to on the handler thread.
7020 // Since it is immutable and always non-null, other threads may read it if they only care
7021 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007022 @NonNull
7023 private OemNetworkPreferences mOemNetworkPreferences =
7024 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007025 // Current per-profile network preferences. This object follows the same threading rules as
7026 // the OEM network preferences above.
7027 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007028 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7029 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007030
paulhu51f77dc2021-06-07 02:34:20 +00007031 // A set of UIDs that should use mobile data preferentially if available. This object follows
7032 // the same threading rules as the OEM network preferences above.
7033 @NonNull
7034 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7035
James Mattiscb1e0362021-04-06 17:07:42 -07007036 // OemNetworkPreferences activity String log entries.
7037 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7038 @NonNull
7039 private final LocalLog mOemNetworkPreferencesLogs =
7040 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7041
James Mattis02220e22021-03-13 19:27:21 -08007042 /**
7043 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7044 * @param packageName the package name to check existence of a mapping for.
7045 * @return true if a mapping exists, false otherwise
7046 */
7047 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7048 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7049 }
7050
James Mattise3ef1912020-12-20 11:09:58 -08007051 // The always-on request for an Internet-capable network that apps without a specific default
7052 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007053 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007054 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007055 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007056 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007057 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007058 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007059 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007060
James Mattisd31bdfa2020-12-23 16:37:26 -08007061 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7062 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7063 }
7064
7065 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007066 * Return the default network request currently tracking the given uid.
7067 * @param uid the uid to check.
7068 * @return the NetworkRequestInfo tracking the given uid.
7069 */
7070 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007071 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007072 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007073 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007074 // Checking the first request is sufficient as only multilayer requests will have more
7075 // than one request and for multilayer, all requests will track the same uids.
7076 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007077 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007078 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007079 highestPriorityNri = nri;
7080 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007081 }
7082 }
paulhuaa0743d2021-05-26 21:56:03 +08007083 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007084 }
7085
7086 /**
7087 * Get a copy of the network requests of the default request that is currently tracking the
7088 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007089 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7090 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007091 * @param requestorUid the uid to check the default for.
7092 * @param requestorPackageName the requestor's package name.
7093 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7094 */
7095 @NonNull
7096 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007097 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007098 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007099 getDefaultRequestTrackingUid(asUid).mRequests,
7100 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007101 }
7102
7103 /**
7104 * Copy the given nri's NetworkRequest collection.
7105 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007106 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7107 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007108 * @param requestorUid the uid to set on the copied collection.
7109 * @param requestorPackageName the package name to set on the copied collection.
7110 * @return the copied NetworkRequest collection.
7111 */
7112 @NonNull
7113 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007114 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7115 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007116 final List<NetworkRequest> requests = new ArrayList<>();
7117 for (final NetworkRequest nr : requestsToCopy) {
7118 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007119 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007120 nr.legacyType, nextNetworkRequestId(), nr.type));
7121 }
7122 return requests;
7123 }
7124
7125 @NonNull
7126 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007127 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7128 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007129 // These capabilities are for a TRACK_DEFAULT callback, so:
7130 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7131 // mDefaultRequest and a per-UID default request.
7132 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007133 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007134 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007135 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7136 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007137 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007138 restrictRequestUidsForCallerAndSetRequestorInfo(
7139 netCap, requestorUid, requestorPackageName);
7140 return netCap;
7141 }
7142
7143 /**
7144 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7145 * @param nr the network request to check for equality against.
7146 * @return the nri if one exists, null otherwise.
7147 */
7148 @Nullable
7149 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7150 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7151 if (nri.getNetworkRequestForCallback().equals(nr)) {
7152 return nri;
7153 }
7154 }
7155 return null;
7156 }
7157
7158 /**
7159 * Check if an nri is currently being managed by per-app default networking.
7160 * @param nri the nri to check.
7161 * @return true if this nri is currently being managed by per-app default networking.
7162 */
7163 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7164 // nri.mRequests.get(0) is only different from the original request filed in
7165 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7166 // functionality therefore if these two don't match, it means this particular nri is
7167 // currently being managed by a per-app default.
7168 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7169 }
7170
7171 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007172 * Determine if an nri is a managed default request that disallows default networking.
7173 * @param nri the request to evaluate
7174 * @return true if device-default networking is disallowed
7175 */
7176 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7177 // Check if this nri is a managed default that supports the default network at its
7178 // lowest priority request.
7179 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7180 final NetworkCapabilities lowestPriorityNetCap =
7181 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7182 return isPerAppDefaultRequest(nri)
7183 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7184 lowestPriorityNetCap));
7185 }
7186
Erik Kline05f2b402015-04-30 12:58:40 +09007187 // Request used to optionally keep mobile data active even when higher
7188 // priority networks like Wi-Fi are active.
7189 private final NetworkRequest mDefaultMobileDataRequest;
7190
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007191 // Request used to optionally keep wifi data active even when higher
7192 // priority networks like ethernet are active.
7193 private final NetworkRequest mDefaultWifiRequest;
7194
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007195 // Request used to optionally keep vehicle internal network always active
7196 private final NetworkRequest mDefaultVehicleRequest;
7197
James Mattisd31bdfa2020-12-23 16:37:26 -08007198 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7199 // network with no service. This NAI should never be matched against, nor should any public API
7200 // ever return the associated network. For this reason, this NAI is not in the list of available
7201 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7202 // default requests that don't support using the device default network which will ultimately
7203 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7204 @VisibleForTesting
7205 final NetworkAgentInfo mNoServiceNetwork;
7206
Chalard Jean5b409c72021-02-04 13:12:59 +09007207 // The NetworkAgentInfo currently satisfying the default request, if any.
7208 private NetworkAgentInfo getDefaultNetwork() {
7209 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007210 }
7211
James Mattis2516da32021-01-31 17:06:19 -08007212 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007213 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007214 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7215 // Currently, all network requests will have the same uids therefore checking the first
7216 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007217 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007218 if (null == uids) {
7219 continue;
7220 }
7221 for (final UidRange range : uids) {
7222 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007223 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007224 highestPriorityNri = nri;
7225 }
James Mattis2516da32021-01-31 17:06:19 -08007226 }
7227 }
7228 }
paulhuaa0743d2021-05-26 21:56:03 +08007229 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007230 }
7231
Varun Ananddf569952019-02-06 10:13:38 -08007232 @Nullable
7233 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7234 return nai != null ? nai.network : null;
7235 }
7236
7237 private void ensureRunningOnConnectivityServiceThread() {
7238 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7239 throw new IllegalStateException(
7240 "Not running on ConnectivityService thread: "
7241 + Thread.currentThread().getName());
7242 }
7243 }
7244
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007245 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007246 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7247 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007248 }
7249
Chalard Jean29d06db2018-05-02 21:14:54 +09007250 /**
7251 * Register a new agent with ConnectivityService to handle a network.
7252 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007253 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007254 * @param networkInfo the initial info associated with this network. It can be updated later :
7255 * see {@link #updateNetworkInfo}.
7256 * @param linkProperties the initial link properties of this network. They can be updated
7257 * later : see {@link #updateLinkProperties}.
7258 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007259 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007260 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007261 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007262 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007263 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007264 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007265 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007266 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007267 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7268 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007269 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7270 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7271 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007272 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007273 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007274 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007275 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007276 } else {
7277 enforceNetworkFactoryPermission();
7278 }
7279
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007280 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007281 final long token = Binder.clearCallingIdentity();
7282 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007283 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007284 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007285 } finally {
7286 Binder.restoreCallingIdentity(token);
7287 }
7288 }
7289
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007290 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007291 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007292 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7293 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007294
Chalard Jeandbc46952022-02-02 00:14:18 +09007295 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7296 // and mutate them at any time.
7297 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7298 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7299 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7300
Chalard Jean366c5252022-01-25 18:27:53 +09007301 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007302 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007303 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7304 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007305 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007306 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007307 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007308 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7309 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007310
Chalard Jeandbc46952022-02-02 00:14:18 +09007311 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007312 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007313 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007314 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007315 mDeps.getNetworkStack().makeNetworkMonitor(
7316 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007317 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7318 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007319 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007320 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007321 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007322 }
7323
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007324 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007325 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007326 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007327 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007328 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007329 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7330 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7331 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007332
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007333 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007334
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007335 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007336 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007337 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007338 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007339
7340 try {
7341 networkMonitor.start();
7342 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007343 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007344 }
Chalard Jean366c5252022-01-25 18:27:53 +09007345
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007346 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007347 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007348 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007349 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007350 }
7351
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007352 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7353 @NonNull public final NetworkOffer offer;
7354
7355 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7356 this.offer = offer;
7357 }
7358
7359 @Override
7360 public void binderDied() {
7361 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7362 }
7363 }
7364
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007365 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7366 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7367 if (npi.providerId == providerId) return true;
7368 }
7369 return false;
7370 }
7371
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007372 /**
7373 * Register or update a network offer.
7374 * @param newOffer The new offer. If the callback member is the same as an existing
7375 * offer, it is an update of that offer.
7376 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007377 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007378 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7379 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007380 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007381 // This may actually happen if a provider updates its score or registers and then
7382 // immediately unregisters. The offer would still be in the handler queue, but the
7383 // provider would have been removed.
7384 if (DBG) log("Received offer from an unregistered provider");
7385 return;
7386 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007387 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7388 if (null != existingOffer) {
7389 handleUnregisterNetworkOffer(existingOffer);
7390 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007391 if (DBG) {
7392 // handleUnregisterNetworkOffer has already logged the old offer
7393 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7394 }
7395 } else {
7396 if (DBG) {
7397 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7398 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007399 }
7400 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7401 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007402 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007403 } catch (RemoteException e) {
7404 noi.binderDied();
7405 return;
7406 }
7407 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007408 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007409 }
7410
7411 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7412 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007413 if (DBG) {
7414 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7415 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007416
7417 // If the provider removes the offer and dies immediately afterwards this
7418 // function may be called twice in a row, but the array will no longer contain
7419 // the offer.
7420 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007421 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007422 }
7423
7424 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7425 @NonNull final INetworkOfferCallback callback) {
7426 ensureRunningOnConnectivityServiceThread();
7427 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007428 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007429 }
7430 return null;
7431 }
7432
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007433 /**
7434 * Called when receiving LinkProperties directly from a NetworkAgent.
7435 * Stores into |nai| any data coming from the agent that might also be written to the network's
7436 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7437 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007438 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007439 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007440 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7441 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007442 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007443 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007444 }
7445
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007446 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007447 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007448 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007449
Lorenzo Colittid523d142020-04-01 20:16:30 +09007450 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7451 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7452 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007453 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007454
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007455 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007456
7457 // update filtering rules, need to happen after the interface update so netd knows about the
7458 // new interface (the interface name -> index map becomes initialized)
7459 updateVpnFiltering(newLp, oldLp, networkAgent);
7460
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007461 updateMtu(newLp, oldLp);
7462 // TODO - figure out what to do for clat
7463// for (LinkProperties lp : newLp.getStackedLinks()) {
7464// updateMtu(lp, null);
7465// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007466 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007467 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7468 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007469
Erik Klineb9888902016-04-05 13:30:49 +09007470 updateRoutes(newLp, oldLp, netId);
7471 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007472 // Make sure LinkProperties represents the latest private DNS status.
7473 // This does not need to be done before updateDnses because the
7474 // LinkProperties are not the source of the private DNS configuration.
7475 // updateDnses will fetch the private DNS configuration from DnsManager.
7476 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007477
Chalard Jean5b409c72021-02-04 13:12:59 +09007478 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007479 handleApplyDefaultProxy(newLp.getHttpProxy());
7480 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007481 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007482 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007483
7484 updateWakeOnLan(newLp);
7485
Hai Shalome58bdc62021-01-11 18:45:34 -08007486 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7487 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7488 // does, it needs to be merged here.
7489 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7490 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007491
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007492 // TODO - move this check to cover the whole function
7493 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007494 synchronized (networkAgent) {
7495 networkAgent.linkProperties = newLp;
7496 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007497 // Start or stop DNS64 detection and 464xlat according to network state.
7498 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007499 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007500 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7501 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007502 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007503 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007504
7505 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007506 }
7507
Hai Shalome58bdc62021-01-11 18:45:34 -08007508 /**
7509 * @param naData captive portal data from NetworkAgent
7510 * @param apiData captive portal data from capport API
7511 */
7512 @Nullable
7513 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7514 CaptivePortalData apiData) {
7515 if (naData == null || apiData == null) {
7516 return naData == null ? apiData : naData;
7517 }
7518 final CaptivePortalData.Builder captivePortalBuilder =
7519 new CaptivePortalData.Builder(naData);
7520
7521 if (apiData.isCaptive()) {
7522 captivePortalBuilder.setCaptive(true);
7523 }
7524 if (apiData.isSessionExtendable()) {
7525 captivePortalBuilder.setSessionExtendable(true);
7526 }
7527 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7528 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7529 // otherwise data would be inconsistent. Prefer the capport API info if present,
7530 // as it can generally be refreshed more often.
7531 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7532 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7533 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7534 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7535 // No source has time / bytes remaining information: surface the newest refresh time
7536 // for other fields
7537 captivePortalBuilder.setRefreshTime(
7538 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7539 }
7540
Hai Shalom7c6ab402021-02-04 19:34:06 -08007541 // Prioritize the user portal URL from the network agent if the source is authenticated.
7542 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7543 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7544 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7545 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007546 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007547 // Prioritize the venue information URL from the network agent if the source is
7548 // authenticated.
7549 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7550 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7551 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7552 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007553 }
7554 return captivePortalBuilder.build();
7555 }
7556
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007557 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007558 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007559 // marks on unsupported interfaces is harmless.
7560 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7561 return;
7562 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007563
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007564 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7565 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7566
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007567 // Mask/mark of zero will not detect anything interesting.
7568 // Don't install rules unless both values are nonzero.
7569 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007570 return;
7571 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007572
7573 final String prefix = "iface:" + iface;
7574 try {
7575 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007576 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007577 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007578 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007579 }
7580 } catch (Exception e) {
7581 loge("Exception modifying wakeup packet monitoring: " + e);
7582 }
7583
Joel Scherpelza235a812017-05-22 13:47:41 +09007584 }
7585
Chalard Jean9589e722019-11-19 19:03:53 +09007586 private void updateInterfaces(final @Nullable LinkProperties newLp,
7587 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007588 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007589 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007590 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7591 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007592 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007593 for (final String iface : interfaceDiff.added) {
7594 try {
7595 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007596 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007597 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007598 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7599 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007600 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007601 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007602 }
Paul Jensenbff73492014-04-28 10:33:11 -04007603 }
7604 }
Chalard Jean9589e722019-11-19 19:03:53 +09007605 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007606 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007607 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007608 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007609 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007610 } catch (Exception e) {
7611 loge("Exception removing interface: " + e);
7612 }
7613 }
7614 }
7615
Tyler Weare4314862019-12-05 14:55:30 -08007616 // TODO: move to frameworks/libs/net.
7617 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7618 final String nextHop;
7619
7620 switch (route.getType()) {
7621 case RouteInfo.RTN_UNICAST:
7622 if (route.hasGateway()) {
7623 nextHop = route.getGateway().getHostAddress();
7624 } else {
7625 nextHop = INetd.NEXTHOP_NONE;
7626 }
7627 break;
7628 case RouteInfo.RTN_UNREACHABLE:
7629 nextHop = INetd.NEXTHOP_UNREACHABLE;
7630 break;
7631 case RouteInfo.RTN_THROW:
7632 nextHop = INetd.NEXTHOP_THROW;
7633 break;
7634 default:
7635 nextHop = INetd.NEXTHOP_NONE;
7636 break;
7637 }
7638
7639 final RouteInfoParcel rip = new RouteInfoParcel();
7640 rip.ifName = route.getInterface();
7641 rip.destination = route.getDestination().toString();
7642 rip.nextHop = nextHop;
7643 rip.mtu = route.getMtu();
7644
7645 return rip;
7646 }
7647
Paul Jensene0fd4a82014-08-06 15:51:33 -04007648 /**
7649 * Have netd update routes from oldLp to newLp.
7650 * @return true if routes changed between oldLp and newLp
7651 */
7652 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007653 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007654 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7655 new CompareOrUpdateResult<>(
7656 oldLp != null ? oldLp.getAllRoutes() : null,
7657 newLp != null ? newLp.getAllRoutes() : null,
7658 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007659
7660 // add routes before removing old in case it helps with continuous connectivity
7661
Chalard Jean9dd11612018-06-04 16:52:49 +09007662 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007663 for (RouteInfo route : routeDiff.added) {
7664 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007665 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007666 try {
Tyler Weare4314862019-12-05 14:55:30 -08007667 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007668 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007669 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007670 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007671 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007672 }
7673 }
7674 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007675 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007676 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007677 try {
Tyler Weare4314862019-12-05 14:55:30 -08007678 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007679 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007680 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007681 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007682 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007683 }
7684 }
7685
7686 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007687 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007688 try {
Tyler Weare4314862019-12-05 14:55:30 -08007689 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007690 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007691 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007692 }
7693 }
Tyler Weare4314862019-12-05 14:55:30 -08007694
7695 for (RouteInfo route : routeDiff.updated) {
7696 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7697 try {
7698 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7699 } catch (Exception e) {
7700 loge("Exception in networkUpdateRouteParcel: " + e);
7701 }
7702 }
7703 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7704 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007705 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007706
Erik Klineb9888902016-04-05 13:30:49 +09007707 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7708 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7709 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007710 }
Erik Klineb9888902016-04-05 13:30:49 +09007711
Erik Kline31b4a9e2018-01-11 21:07:29 +09007712 if (DBG) {
7713 final Collection<InetAddress> dnses = newLp.getDnsServers();
7714 log("Setting DNS servers for network " + netId + " to " + dnses);
7715 }
Erik Klineb9888902016-04-05 13:30:49 +09007716 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007717 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007718 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007719 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007720 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007721 }
Erik Kline54e35c02017-04-07 15:29:29 +09007722 }
7723
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007724 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7725 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007726 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7727 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007728 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7729 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007730
7731 if (!wasFiltering && !needsFiltering) {
7732 // Nothing to do.
7733 return;
7734 }
7735
7736 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7737 // Nothing changed.
7738 return;
7739 }
7740
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007741 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007742 if (ranges == null || ranges.isEmpty()) {
7743 return;
7744 }
7745
Qingxi Libb8da982020-01-17 17:54:27 -08007746 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007747 // TODO: this create a window of opportunity for apps to receive traffic between the time
7748 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007749 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007750 // old rules are being removed.
7751 if (wasFiltering) {
7752 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7753 }
7754 if (needsFiltering) {
7755 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7756 }
7757 }
7758
Valentin Iftime9fa35092019-09-24 13:32:13 +02007759 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007760 if (mWolSupportedInterfaces == null) {
7761 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007762 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007763 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007764 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7765 }
7766
Luke Huangb913c812018-08-24 20:33:16 +08007767 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007768 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007769 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007770 }
7771 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007772 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007773 }
Luke Huangb913c812018-08-24 20:33:16 +08007774 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007775 }
7776
Chalard Jean62edfd82019-12-02 18:39:29 +09007777 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7778 @NonNull final NetworkCapabilities newNc) {
7779 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7780 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007781 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007782 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007783 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007784 } catch (RemoteException | ServiceSpecificException e) {
7785 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007786 }
7787 }
7788 }
7789
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007790 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007791 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007792 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007793 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007794 underlyingNetworks = underlyingNetworksOrDefault(
7795 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007796 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007797 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7798 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007799 // metered if any underlying is metered, or originally declared metered by the agent.
7800 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007801 boolean roaming = false; // roaming if any underlying is roaming
7802 boolean congested = false; // congested if any underlying is congested
7803 boolean suspended = true; // suspended if all underlying are suspended
7804
7805 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007806 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007807 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007808 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007809 for (Network underlyingNetwork : underlyingNetworks) {
7810 final NetworkAgentInfo underlying =
7811 getNetworkAgentInfoForNetwork(underlyingNetwork);
7812 if (underlying == null) continue;
7813
7814 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7815 hadUnderlyingNetworks = true;
7816 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007817 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007818 }
7819
7820 // Merge capabilities of this underlying network. For bandwidth, assume the
7821 // worst case.
7822 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7823 underlyingCaps.getLinkDownstreamBandwidthKbps());
7824 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7825 underlyingCaps.getLinkUpstreamBandwidthKbps());
7826 // If this underlying network is metered, the VPN is metered (it may cost money
7827 // to send packets on this network).
7828 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7829 // If this underlying network is roaming, the VPN is roaming (the billing structure
7830 // is different than the usual, local one).
7831 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7832 // If this underlying network is congested, the VPN is congested (the current
7833 // condition of the network affects the performance of this network).
7834 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7835 // If this network is not suspended, the VPN is not suspended (the VPN
7836 // is able to transfer some data).
7837 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007838 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007839 }
7840 }
7841 if (!hadUnderlyingNetworks) {
7842 // No idea what the underlying networks are; assume reasonable defaults
7843 metered = true;
7844 roaming = false;
7845 congested = false;
7846 suspended = false;
7847 }
7848
lifrade6c2a2021-03-04 14:08:08 +08007849 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007850 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7851 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7852 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7853 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7854 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7855 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007856 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007857 }
7858
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007859 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007860 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7861 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7862 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007863 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007864 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007865 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007866 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007867 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7868 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007869 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007870 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007871 if (nai.everConnected()
7872 && !nai.isVPN()
7873 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007874 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007875 // does not cause any request (that is not a listen) currently matching that agent to
7876 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007877 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007878 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007879 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007880 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007881 }
7882
Paul Jensen53f08952015-06-16 14:27:36 -04007883 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007884 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007885 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007886 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007887 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007888 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007889 }
Chalard Jean254bd162022-08-25 13:04:51 +09007890 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007891 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007892 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007893 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007894 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007895 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007896 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007897 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007898 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007899 }
Chalard Jean254bd162022-08-25 13:04:51 +09007900 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007901 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7902 } else {
7903 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7904 }
lucasline117e2e2019-10-22 18:27:33 +08007905 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007906
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007907 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007908 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7909 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007910 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007911 }
7912
Lorenzo Colittibd079452021-07-02 11:47:57 +09007913 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007914 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007915 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007916 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007917 }
7918
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007919 return newNc;
7920 }
7921
Lorenzo Colitti44840702021-01-11 22:27:57 +09007922 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7923 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7924 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7925 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7926 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7927 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7928 if (prevSuspended != suspended) {
7929 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7930 // onResumed have been removed.
7931 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7932 : ConnectivityManager.CALLBACK_RESUMED);
7933 }
7934 if (prevSuspended != suspended || prevRoaming != roaming) {
7935 // updateNetworkInfo will mix in the suspended info from the capabilities and
7936 // take appropriate action for the network having possibly changed state.
7937 updateNetworkInfo(nai, nai.networkInfo);
7938 }
7939 }
7940
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007941 /**
7942 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7943 *
7944 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7945 * capabilities we manage and store in {@code nai}, such as validated status and captive
7946 * portal status)
7947 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7948 * potentially triggers rematches.
7949 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7950 * change.)
7951 *
7952 * @param oldScore score of the network before any of the changes that prompted us
7953 * to call this function.
7954 * @param nai the network having its capabilities updated.
7955 * @param nc the new network capabilities.
7956 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007957 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007958 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007959 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007960 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007961 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007962 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007963
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007964 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09007965 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007966 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007967
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007968 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007969 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7970 // the change we're processing can't affect any requests, it can only affect the listens
7971 // on this network. We might have been called by rematchNetworkAndRequests when a
7972 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007973 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007974 } else {
7975 // If the requestable capabilities have changed or the score changed, we can't have been
7976 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007977 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007978 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007979 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007980 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007981
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007982 final boolean oldMetered = prevNc.isMetered();
7983 final boolean newMetered = newNc.isMetered();
7984 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007985
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007986 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007987 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7988 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007989 }
junyulaif2c67e42018-08-07 19:50:45 +08007990
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007991 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7992 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007993
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007994 // Report changes that are interesting for network statistics tracking.
7995 if (meteredChanged || roamingChanged) {
7996 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007997 }
7998
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007999 // This network might have been underlying another network. Propagate its capabilities.
8000 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008001
8002 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008003 mDnsManager.updateTransportsForNetwork(
8004 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008005 }
lucaslin53e8a262021-06-08 01:43:59 +08008006
8007 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008008 }
8009
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008010 /** Convenience method to update the capabilities for a given network. */
8011 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008012 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008013 }
8014
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008015 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008016 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008017 *
8018 * Ingress interface filtering enforces that all apps under the given network can only receive
8019 * packets from the network's interface (and loopback). This is important for VPNs because
8020 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8021 * non-VPN interfaces.
8022 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008023 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008024 * 1. the network is an app VPN (not legacy VPN)
8025 * 2. the VPN does not allow bypass
8026 * 3. the VPN is fully-routed
8027 * 4. the VPN interface is non-null
8028 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008029 * @see INetd#firewallAddUidInterfaceRules
8030 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008031 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008032 @Nullable
8033 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008034 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008035 if (nc == null || lp == null) return null;
8036 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008037 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008038 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008039 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008040 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008041 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008042 && !lp.hasExcludeRoute()) {
8043 return lp.getInterfaceName();
8044 }
8045 return null;
8046 }
8047
8048 /**
8049 * Returns whether we need to set interface filtering rule or not
8050 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008051 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008052 String isolationIface) {
8053 // Allow rules are always needed if VPN isolation is enabled.
8054 if (isolationIface != null) return true;
8055
8056 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8057 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8058 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8059 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008060 }
8061
Chiachang Wang28afaff2020-12-10 22:24:47 +08008062 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8063 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8064 int index = 0;
8065 for (UidRange range : ranges) {
8066 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8067 index++;
8068 }
8069 return stableRanges;
8070 }
8071
Chalard Jeane6c95272022-01-25 21:04:21 +09008072 private static UidRangeParcel[] intsToUidRangeStableParcels(
8073 final @NonNull ArraySet<Integer> uids) {
8074 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8075 int index = 0;
8076 for (int uid : uids) {
8077 stableRanges[index] = new UidRangeParcel(uid, uid);
8078 index++;
8079 }
8080 return stableRanges;
8081 }
8082
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008083 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8084 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8085 for (int i = 0; i < ranges.length; i++) {
8086 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8087 }
8088 return stableRanges;
8089 }
8090
Ken Chen5e65a852020-12-24 12:59:10 +08008091 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8092 int[] exemptUids) {
8093 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8094 try {
8095 mNetd.socketDestroy(ranges, exemptUids);
8096 } catch (Exception e) {
8097 loge("Exception in socket destroy: ", e);
8098 }
8099 }
8100 }
8101
paulhuaa0743d2021-05-26 21:56:03 +08008102 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008103 int[] exemptUids = new int[2];
8104 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8105 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8106 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8107 exemptUids[0] = VPN_UID;
8108 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8109 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8110
8111 maybeCloseSockets(nai, ranges, exemptUids);
8112 try {
8113 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008114 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008115 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008116 } else {
paulhu0e79d952021-06-09 16:11:35 +08008117 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008118 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008119 }
8120 } catch (Exception e) {
8121 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8122 " on netId " + nai.network.netId + ". " + e);
8123 }
8124 maybeCloseSockets(nai, ranges, exemptUids);
8125 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008126
lucaslin53e8a262021-06-08 01:43:59 +08008127 private boolean isProxySetOnAnyDefaultNetwork() {
8128 ensureRunningOnConnectivityServiceThread();
8129 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8130 final NetworkAgentInfo nai = nri.getSatisfier();
8131 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8132 return true;
8133 }
8134 }
8135 return false;
8136 }
8137
8138 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8139 NetworkCapabilities newNc) {
8140 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8141 // the proxy might be changed since the default network satisfied by the apps might also
8142 // changed.
8143 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8144 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008145 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8146 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008147 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008148 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8149 mProxyTracker.sendProxyBroadcast();
8150 }
8151 }
8152
Chalard Jeane6c95272022-01-25 21:04:21 +09008153 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8154 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008155 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8156 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008157 if (null == prevRanges) prevRanges = new ArraySet<>();
8158 if (null == newRanges) newRanges = new ArraySet<>();
8159 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8160
8161 prevRanges.removeAll(newRanges);
8162 newRanges.removeAll(prevRangesCopy);
8163
8164 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008165 // When updating the VPN uid routing rules, add the new range first then remove the old
8166 // range. If old range were removed first, there would be a window between the old
8167 // range being removed and the new range being added, during which UIDs contained
8168 // in both ranges are not subject to any VPN routing rules. Adding new range before
8169 // removing old range works because, unlike the filtering rules below, it's possible to
8170 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008171 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8172 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8173 // [1-5] & [1-2],[4-5] == [3]
8174 // Then we can do:
8175 // maybeCloseSockets([3])
8176 // mNetd.networkAddUidRanges([1-2],[4-5])
8177 // mNetd.networkRemoveUidRanges([1-5])
8178 // maybeCloseSockets([3])
8179 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8180 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008181 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008182 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008183 }
8184 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008185 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008186 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008187 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8188 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008189 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8190 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008191 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008192 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008193 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8194 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8195 // were added first and then newRanges got removed later, there would be only one uid
8196 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8197 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8198 // Note that this is in contrast with the (more robust) update of VPN routing rules
8199 // above, where the addition of new ranges happens before the removal of old ranges.
8200 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8201 // to be removed will never overlap with the new range to be added.
8202 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008203 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8204 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008205 }
8206 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008207 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008208 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008209 } catch (Exception e) {
8210 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008211 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008212 }
8213 }
8214
Chalard Jeande665262022-02-25 16:12:12 +09008215 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008216 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8217 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008218 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8219 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008220 if (prevEmpty && newEmpty) return;
8221
8222 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008223 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008224 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008225 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008226
8227 if (prevUids.equals(newUids)) return;
8228
8229 // This implementation is very simple and vastly faster for sets of Integers than
8230 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8231 // a key computed from the value and has storage for that.
8232 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8233 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8234 toRemove.removeAll(newUids);
8235 toAdd.removeAll(prevUids);
8236
8237 try {
8238 if (!toAdd.isEmpty()) {
8239 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8240 nai.network.netId,
8241 intsToUidRangeStableParcels(toAdd),
8242 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8243 }
8244 if (!toRemove.isEmpty()) {
8245 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8246 nai.network.netId,
8247 intsToUidRangeStableParcels(toRemove),
8248 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8249 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008250 } catch (ServiceSpecificException e) {
8251 // Has the interface disappeared since the network was built ?
8252 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008253 } catch (RemoteException e) {
8254 // Netd died. This usually causes a runtime restart anyway.
8255 }
8256 }
8257
Hugo Benichi9d35b752017-09-01 01:23:32 +00008258 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008259 ensureRunningOnConnectivityServiceThread();
8260
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008261 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008262 // Ignore updates for disconnected networks
8263 return;
8264 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008265 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008266 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008267 + "; created=" + nai.getCreatedTime()
8268 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008269 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008270 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8271 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008272 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008273 }
8274
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008275 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8276 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008277 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008278 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008279 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008280 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8281 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8282 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008283 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8284 // need to be sent as a separate extra.
8285 final NetworkRequest req = nri.isMultilayerRequest()
8286 ? nri.getActiveRequest()
8287 // Non-multilayer listen requests do not have an active request
8288 : nri.mRequests.get(0);
8289 if (req == null) {
8290 Log.wtf(TAG, "No request in NRI " + nri);
8291 }
8292 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008293 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008294 sendIntent(nri.mPendingIntent, intent);
8295 }
8296 // else not handled
8297 }
8298
8299 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8300 mPendingIntentWakeLock.acquire();
8301 try {
8302 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008303 final BroadcastOptions options = BroadcastOptions.makeBasic();
8304 if (SdkLevel.isAtLeastT()) {
8305 // Explicitly disallow the receiver from starting activities, to prevent apps from
8306 // utilizing the PendingIntent as a backdoor to do this.
8307 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8308 }
8309 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8310 null /* requiredPermission */,
8311 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008312 } catch (PendingIntent.CanceledException e) {
8313 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8314 mPendingIntentWakeLock.release();
8315 releasePendingNetworkRequest(pendingIntent);
8316 }
8317 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8318 }
8319
8320 @Override
8321 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8322 String resultData, Bundle resultExtras) {
8323 if (DBG) log("Finished sending " + pendingIntent);
8324 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008325 // Release with a delay so the receiving client has an opportunity to put in its
8326 // own request.
8327 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008328 }
8329
Chalard Jean46bfbf02022-02-02 00:56:25 +09008330 // networkAgent is only allowed to be null if notificationType is
8331 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8332 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008333 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008334 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008335 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008336 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008337 // Default request has no msgr. Also prevents callbacks from being invoked for
8338 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8339 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8340 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008341 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008342 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008343 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008344 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008345 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008346 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008347 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008348 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8349 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008350 }
Roshan Pius951c0032020-12-22 15:10:42 -08008351 final boolean includeLocationSensitiveInfo =
8352 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008353 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008354 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008355 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008356 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008357 networkCapabilitiesRestrictedForCallerPermissions(
8358 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8359 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008360 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008361 nri.mCallingAttributionTag);
8362 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008363 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8364 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008365 // For this notification, arg1 contains the blocked status.
8366 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008367 break;
8368 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008369 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008370 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008371 break;
8372 }
8373 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008374 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008375 final NetworkCapabilities netCap =
8376 networkCapabilitiesRestrictedForCallerPermissions(
8377 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8378 putParcelable(
8379 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008380 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008381 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008382 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008383 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008384 break;
8385 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008386 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008387 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8388 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008389 break;
8390 }
junyulaif2c67e42018-08-07 19:50:45 +08008391 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008392 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008393 msg.arg1 = arg1;
8394 break;
8395 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008396 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008397 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008398 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008399 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008400 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008401 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008402 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008403 }
James Mattis45d81842021-01-10 14:24:24 -08008404 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008405 } catch (RemoteException e) {
8406 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008407 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008408 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008409 }
8410
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008411 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8412 bundle.putParcelable(t.getClass().getSimpleName(), t);
8413 }
8414
Chalard Jean0702f982021-09-16 21:50:07 +09008415 /**
8416 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8417 *
8418 * When a request should be assigned to a new network, it is normally lingered to give
8419 * time for apps to gracefully migrate their connections. When both networks are on the same
8420 * radio, but that radio can't do time-sharing efficiently, this may end up being
8421 * counter-productive because any traffic on the old network may drastically reduce the
8422 * performance of the new network.
8423 * The stack supports a configuration to let modem vendors state that their radio can't
8424 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8425 * from one cell network to another can't be done gracefully.
8426 *
8427 * @param oldNai the old network serving the request
8428 * @param newNai the new network serving the request
8429 * @return whether the switch can be graceful
8430 */
8431 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8432 @NonNull final NetworkAgentInfo newSatisfier) {
8433 if (mCellularRadioTimesharingCapable) return true;
8434 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8435 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8436 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8437 }
8438
Paul Jensenaf94b982014-09-30 15:37:41 -04008439 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008440 if (nai.numRequestNetworkRequests() != 0) {
8441 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8442 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008443 // Ignore listening and track default requests.
8444 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008445 loge("Dead network still had at least " + nr);
8446 break;
8447 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008448 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008449 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008450 }
8451
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008452 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8453 if (oldNetwork == null) {
8454 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8455 return;
8456 }
Chalard Jean49707572019-12-10 21:07:02 +09008457 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008458
8459 // If we get here it means that the last linger timeout for this network expired. So there
8460 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008461 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008462
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008463 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008464 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008465 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008466 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008467 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008468 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008469 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008470 }
8471
James Mattise3ef1912020-12-20 11:09:58 -08008472 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8473 boolean isDefaultChanged = false;
8474 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8475 final NetworkReassignment.RequestReassignment reassignment =
8476 changes.getReassignment(defaultRequestInfo);
8477 if (null == reassignment) {
8478 continue;
8479 }
8480 // reassignment only contains those instances where the satisfying network changed.
8481 isDefaultChanged = true;
8482 // Notify system services of the new default.
8483 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8484 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008485
James Mattise3ef1912020-12-20 11:09:58 -08008486 if (isDefaultChanged) {
8487 // Hold a wakelock for a short time to help apps in migrating to a new default.
8488 scheduleReleaseNetworkTransitionWakelock();
8489 }
8490 }
8491
8492 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8493 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8494 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8495 if (DBG) {
8496 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8497 }
Chalard Jean8e382112019-12-03 20:45:30 +09008498
James Mattisd31bdfa2020-12-23 16:37:26 -08008499 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8500 if (newDefaultNetwork != null) {
8501 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008502 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008503
James Mattisd31bdfa2020-12-23 16:37:26 -08008504 // Set an app level managed default and return since further processing only applies to the
8505 // default network.
8506 if (mDefaultRequest != nri) {
8507 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8508 return;
8509 }
8510
8511 makeDefaultNetwork(newDefaultNetwork);
8512
James Mattise3ef1912020-12-20 11:09:58 -08008513 if (oldDefaultNetwork != null) {
8514 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8515 }
8516 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008517 handleApplyDefaultProxy(null != newDefaultNetwork
8518 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8519 updateTcpBufferSizes(null != newDefaultNetwork
8520 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008521 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008522 }
8523
James Mattisd31bdfa2020-12-23 16:37:26 -08008524 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8525 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8526 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8527 try {
8528 if (VDBG) {
8529 log("Setting default network for " + nri
8530 + " using UIDs " + nri.getUids()
8531 + " with old network " + (oldDefaultNetwork != null
8532 ? oldDefaultNetwork.network().getNetId() : "null")
8533 + " and new network " + (newDefaultNetwork != null
8534 ? newDefaultNetwork.network().getNetId() : "null"));
8535 }
8536 if (nri.getUids().isEmpty()) {
8537 throw new IllegalStateException("makeDefaultForApps called without specifying"
8538 + " any applications to set as the default." + nri);
8539 }
8540 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008541 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008542 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008543 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008544 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008545 }
8546 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008547 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008548 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008549 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008550 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008551 }
8552 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008553 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008554 }
8555 }
8556
8557 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8558 try {
8559 if (null != newDefaultNetwork) {
8560 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8561 } else {
8562 mNetd.networkClearDefault();
8563 }
8564 } catch (RemoteException | ServiceSpecificException e) {
8565 loge("Exception setting default network :" + e);
8566 }
8567 }
8568
Chalard Jean05cbe972019-12-09 11:50:38 +09008569 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008570 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008571 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008572 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008573 processNewlySatisfiedListenRequests(nai);
8574 }
8575
8576 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008577 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8578 if (nri.isMultilayerRequest()) {
8579 continue;
8580 }
8581 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008582 if (!nr.isListen()) continue;
8583 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008584 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008585 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8586 }
8587 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008588 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008589
Chalard Jeancd397a22019-11-22 22:33:33 +09008590 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008591 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8592 if (nri.isMultilayerRequest()) {
8593 continue;
8594 }
8595 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008596 if (!nr.isListen()) continue;
8597 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8598 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008599 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008600 }
8601 }
8602 }
8603
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008604 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008605 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008606 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008607 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008608 @Nullable public final NetworkRequest mOldNetworkRequest;
8609 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008610 @Nullable public final NetworkAgentInfo mOldNetwork;
8611 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008612 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008613 @Nullable final NetworkRequest oldNetworkRequest,
8614 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008615 @Nullable final NetworkAgentInfo oldNetwork,
8616 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008617 mNetworkRequestInfo = networkRequestInfo;
8618 mOldNetworkRequest = oldNetworkRequest;
8619 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008620 mOldNetwork = oldNetwork;
8621 mNewNetwork = newNetwork;
8622 }
Chalard Jean49707572019-12-10 21:07:02 +09008623
8624 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008625 final NetworkRequest requestToShow = null != mNewNetworkRequest
8626 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8627 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008628 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8629 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008630 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008631 }
8632
Chalard Jean46a62372019-12-10 21:25:24 +09008633 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008634
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008635 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008636 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008637 }
8638
8639 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008640 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008641 // The code is never supposed to add two reassignments of the same request. Make
8642 // sure this stays true, but without imposing this expensive check on all
8643 // reassignments on all user devices.
8644 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008645 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008646 throw new IllegalStateException("Trying to reassign ["
8647 + reassignment + "] but already have ["
8648 + existing + "]");
8649 }
8650 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008651 }
Chalard Jean46a62372019-12-10 21:25:24 +09008652 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008653 }
8654
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008655 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008656 // the passed request.
8657 @Nullable
8658 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008659 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008660 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008661 }
8662 return null;
8663 }
Chalard Jean49707572019-12-10 21:07:02 +09008664
8665 public String toString() {
8666 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8667 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008668 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008669 for (final RequestReassignment rr : getRequestReassignments()) {
8670 sj.add(rr.toString());
8671 }
8672 return sj.toString();
8673 }
8674
8675 public String debugString() {
8676 final StringBuilder sb = new StringBuilder();
8677 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008678 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008679 for (final RequestReassignment rr : getRequestReassignments()) {
8680 sb.append("\n ").append(rr);
8681 }
8682 return sb.append("\n").toString();
8683 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008684 }
8685
Chalard Jean24344d72019-12-04 13:32:31 +09008686 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008687 @Nullable final NetworkRequest previousRequest,
8688 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008689 @Nullable final NetworkAgentInfo previousSatisfier,
8690 @Nullable final NetworkAgentInfo newSatisfier,
8691 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008692 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008693 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008694 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008695 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008696 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008697 }
James Mattisa076c532020-12-02 14:12:41 -08008698 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008699 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008700 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008701 // If this network switch can't be supported gracefully, the request is not
8702 // lingered. This allows letting go of the network sooner to reclaim some
8703 // performance on the new network, since the radio can't do both at the same
8704 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008705 //
8706 // Also don't linger the request if the old network has been destroyed.
8707 // A destroyed network does not provide actual network connectivity, so
8708 // lingering it is not useful. In particular this ensures that a destroyed
8709 // network is outscored by its replacement,
8710 // then it is torn down immediately instead of being lingered, and any apps that
8711 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008712 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8713 }
Chalard Jean24344d72019-12-04 13:32:31 +09008714 } else {
8715 if (VDBG || DDBG) log(" accepting network in place of null");
8716 }
junyulai0ac374f2020-12-14 18:41:52 +08008717
8718 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8719 // and immediately satisfies a request then remove the timer. This will happen for
8720 // all networks except in the case of an underlying network for a VCN.
8721 if (newSatisfier.isNascent()) {
8722 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008723 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008724 }
8725
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008726 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008727 newSatisfier.unlingerRequest(newRequest.requestId);
8728 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008729 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008730 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008731 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008732 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008733 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008734 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008735 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008736 }
James Mattisa076c532020-12-02 14:12:41 -08008737 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008738 }
James Mattisa076c532020-12-02 14:12:41 -08008739 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008740 }
8741
James Mattisa076c532020-12-02 14:12:41 -08008742 /**
8743 * This function is triggered when something can affect what network should satisfy what
8744 * request, and it computes the network reassignment from the passed collection of requests to
8745 * network match to the one that the system should now have. That data is encoded in an
8746 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8747 * satisfier.
8748 *
8749 * After the reassignment is computed, it is applied to the state objects.
8750 *
8751 * @param networkRequests the nri objects to evaluate for possible network reassignment
8752 * @return NetworkReassignment listing of proposed network assignment changes
8753 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008754 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008755 private NetworkReassignment computeNetworkReassignment(
8756 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008757 final NetworkReassignment changes = new NetworkReassignment();
8758
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008759 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008760 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008761 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008762 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008763 }
Chalard Jean857a1712019-12-10 21:08:07 +09008764
James Mattisa076c532020-12-02 14:12:41 -08008765 for (final NetworkRequestInfo nri : networkRequests) {
8766 // Non-multilayer listen requests can be ignored.
8767 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8768 continue;
8769 }
8770 NetworkAgentInfo bestNetwork = null;
8771 NetworkRequest bestRequest = null;
8772 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008773 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008774 // Stop evaluating as the highest possible priority request is satisfied.
8775 if (null != bestNetwork) {
8776 bestRequest = req;
8777 break;
8778 }
8779 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008780 if (null == bestNetwork && isDefaultBlocked(nri)) {
8781 // Remove default networking if disallowed for managed default requests.
8782 bestNetwork = mNoServiceNetwork;
8783 }
8784 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008785 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008786 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008787 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008788 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008789 }
8790 return changes;
8791 }
8792
James Mattisa076c532020-12-02 14:12:41 -08008793 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8794 return new HashSet<>(mNetworkRequests.values());
8795 }
8796
Paul Jensenc88b39b2015-06-16 14:27:36 -04008797 /**
James Mattisa076c532020-12-02 14:12:41 -08008798 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008799 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008800 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008801 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008802 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8803 }
8804
8805 /**
8806 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8807 * being disconnected.
8808 */
8809 private void rematchNetworksAndRequests(
8810 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8811 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008812 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008813 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008814 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008815 final long computed = SystemClock.elapsedRealtime();
8816 applyNetworkReassignment(changes, start);
8817 final long applied = SystemClock.elapsedRealtime();
8818 issueNetworkNeeds();
8819 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008820 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008821 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8822 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008823 log(changes.debugString());
8824 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008825 // Shorter form, only one line of log
8826 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8827 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008828 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008829 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008830
Chalard Jeand7f762d2019-12-10 19:01:29 +09008831 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008832 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008833 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008834
8835 // Since most of the time there are only 0 or 1 background networks, it would probably
8836 // be more efficient to just use an ArrayList here. TODO : measure performance
8837 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8838 for (final NetworkAgentInfo nai : nais) {
8839 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8840 }
8841
Chalard Jeand7f762d2019-12-10 19:01:29 +09008842 // First, update the lists of satisfied requests in the network agents. This is necessary
8843 // because some code later depends on this state to be correct, most prominently computing
8844 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008845 for (final NetworkReassignment.RequestReassignment event :
8846 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008847 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8848 event.mOldNetworkRequest, event.mNewNetworkRequest,
8849 event.mOldNetwork, event.mNewNetwork,
8850 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008851 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008852
James Mattise3ef1912020-12-20 11:09:58 -08008853 // Process default network changes if applicable.
8854 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008855
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008856 // Notify requested networks are available after the default net is switched, but
8857 // before LegacyTypeTracker sends legacy broadcasts
8858 for (final NetworkReassignment.RequestReassignment event :
8859 changes.getRequestReassignments()) {
8860 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008861 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008862 } else {
James Mattisa076c532020-12-02 14:12:41 -08008863 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008864 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008865 }
8866 }
8867
junyulai0ac374f2020-12-14 18:41:52 +08008868 // Update the inactivity state before processing listen callbacks, because the background
8869 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008870 // just yet though, because they have to be sent after the listens are processed to keep
8871 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008872 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008873 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008874 // Rematching may have altered the inactivity state of some networks, so update all
8875 // inactivity timers. updateInactivityState reads the state from the network agent
8876 // and does nothing if the state has not changed : the source of truth is controlled
8877 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8878 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008879 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008880 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008881 }
8882 }
8883
Chalard Jeanb10ab412019-12-11 14:12:30 +09008884 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008885 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008886 // Process listen requests and update capabilities if the background state has
8887 // changed for this network. For consistency with previous behavior, send onLost
8888 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008889 processNewlyLostListenRequests(nai);
8890 if (oldBackground != nai.isBackgroundNetwork()) {
8891 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008892 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008893 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008894 }
8895
junyulai0ac374f2020-12-14 18:41:52 +08008896 for (final NetworkAgentInfo nai : inactiveNetworks) {
8897 // For nascent networks, if connecting with no foreground request, skip broadcasting
8898 // LOSING for backward compatibility. This is typical when mobile data connected while
8899 // wifi connected with mobile data always-on enabled.
8900 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008901 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008902 }
8903
James Mattise3ef1912020-12-20 11:09:58 -08008904 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008905
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008906 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008907 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008908 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008909 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008910 // This network has active linger timers and no requests, but is not
8911 // lingering. Linger it.
8912 //
8913 // One way (the only way?) this can happen if this network is unvalidated
8914 // and became unneeded due to another network improving its score to the
8915 // point where this network will no longer be able to satisfy any requests
8916 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008917 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008918 notifyNetworkLosing(nai, now);
8919 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008920 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008921 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008922 teardownUnneededNetwork(nai);
8923 }
8924 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008925 }
8926 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008927
Chalard Jean62edfd82019-12-02 18:39:29 +09008928 /**
8929 * Apply a change in background state resulting from rematching networks with requests.
8930 *
8931 * During rematch, a network may change background states by starting to satisfy or stopping
8932 * to satisfy a foreground request. Listens don't count for this. When a network changes
8933 * background states, its capabilities need to be updated and callbacks fired for the
8934 * capability change.
8935 *
8936 * @param nai The network that changed background states
8937 */
8938 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8939 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8940 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8941 updateNetworkPermissions(nai, newNc);
8942 nai.getAndSetNetworkCapabilities(newNc);
8943 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8944 }
8945
Chalard Jeanf0344532019-11-19 19:23:38 +09008946 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008947 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008948 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008949 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8950 changes.getReassignment(mDefaultRequest);
8951 final NetworkAgentInfo oldDefaultNetwork =
8952 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8953 final NetworkAgentInfo newDefaultNetwork =
8954 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008955
Chalard Jean5b409c72021-02-04 13:12:59 +09008956 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008957 // Maintain the illusion : since the legacy API only understands one network at a time,
8958 // if the default network changed, apps should see a disconnected broadcast for the
8959 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008960 if (oldDefaultNetwork != null) {
8961 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8962 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008963 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008964 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008965 // The new default network can be newly null if and only if the old default
8966 // network doesn't satisfy the default request any more because it lost a
8967 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09008968 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008969 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008970 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008971 }
8972 }
8973
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008974 // Now that all the callbacks have been sent, send the legacy network broadcasts
8975 // as needed. This is necessary so that legacy requests correctly bind dns
8976 // requests to this network. The legacy users are listening for this broadcast
8977 // and will generally do a dns request so they can ensureRouteToHost and if
8978 // they do that before the callbacks happen they'll use the default network.
8979 //
8980 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8981 // callbacks, but if apps can receive the broadcast before the callback, they still might
8982 // have an inconsistent view of networking.
8983 //
8984 // This *does* introduce a race where if the user uses the new api
8985 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8986 // they may get old info. Reverse this after the old startUsing api is removed.
8987 // This is on top of the multiple intent sequencing referenced in the todo above.
8988 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09008989 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008990 addNetworkToLegacyTypeTracker(nai);
8991 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008992 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008993 }
8994
Chalard Jean0354d8c2021-01-12 10:58:56 +09008995 private void issueNetworkNeeds() {
8996 ensureRunningOnConnectivityServiceThread();
8997 for (final NetworkOfferInfo noi : mNetworkOffers) {
8998 issueNetworkNeeds(noi);
8999 }
9000 }
9001
9002 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9003 ensureRunningOnConnectivityServiceThread();
9004 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9005 informOffer(nri, noi.offer, mNetworkRanker);
9006 }
9007 }
9008
9009 /**
9010 * Inform a NetworkOffer about any new situation of a request.
9011 *
9012 * This function handles updates to offers. A number of events may happen that require
9013 * updating the registrant for this offer about the situation :
9014 * • The offer itself was updated. This may lead the offer to no longer being able
9015 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9016 * or conversely being strengthened enough to beat the satisfier (and therefore
9017 * start being needed)
9018 * • The network satisfying a request changed (including cases where the request
9019 * starts or stops being satisfied). The new network may be a stronger or weaker
9020 * match than the old one, possibly affecting whether the offer is needed.
9021 * • The network satisfying a request updated their score. This may lead the offer
9022 * to no longer be able to beat it if the current satisfier got better, or
9023 * conversely start being a good choice if the current satisfier got weaker.
9024 *
9025 * @param nri The request
9026 * @param offer The offer. This may be an updated offer.
9027 */
9028 private static void informOffer(@NonNull NetworkRequestInfo nri,
9029 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9030 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9031 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009032
9033 // Multi-layer requests have a currently active request, the one being satisfied.
9034 // Since the system will try to bring up a better network than is currently satisfying
9035 // the request, NetworkProviders need to be told the offers matching the requests *above*
9036 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9037 // not needed, and the offer is needed for the active request iff the offer can beat
9038 // the satisfier.
9039 // For non-multilayer requests, the logic above gracefully degenerates to only the
9040 // last case.
9041 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9042 // providers that the offer is needed for this request, until the active request is found.
9043 // In a second phase, deal with the currently active request. In a third phase, inform
9044 // the providers that offer is unneeded for the remaining requests.
9045
9046 // First phase : inform providers of all requests above the active request.
9047 int i;
9048 for (i = 0; nri.mRequests.size() > i; ++i) {
9049 final NetworkRequest request = nri.mRequests.get(i);
9050 if (activeRequest == request) break; // Found the active request : go to phase 2
9051 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9052 // Since this request is higher-priority than the one currently satisfied, if the
9053 // offer can satisfy it, the provider should try and bring up the network for sure ;
9054 // no need to even ask the ranker – an offer that can satisfy is always better than
9055 // no network. Hence tell the provider so unless it already knew.
9056 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9057 offer.onNetworkNeeded(request);
9058 }
9059 }
9060
9061 // Second phase : deal with the active request (if any)
9062 if (null != activeRequest && activeRequest.isRequest()) {
9063 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009064 // If an offer can satisfy the request, it is considered needed if it is currently
9065 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009066 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009067 && satisfier.factorySerialNumber == offer.providerId
9068 && activeRequest.canBeSatisfiedBy(offer.caps);
9069 final boolean newNeeded = currentlyServing
9070 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009071 if (newNeeded != oldNeeded) {
9072 if (newNeeded) {
9073 offer.onNetworkNeeded(activeRequest);
9074 } else {
9075 // The offer used to be able to beat the satisfier. Now it can't.
9076 offer.onNetworkUnneeded(activeRequest);
9077 }
9078 }
9079 }
9080
9081 // Third phase : inform the providers that the offer isn't needed for any request
9082 // below the active one.
9083 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9084 final NetworkRequest request = nri.mRequests.get(i);
9085 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9086 // Since this request is lower-priority than the one currently satisfied, if the
9087 // offer can satisfy it, the provider should not try and bring up the network.
9088 // Hence tell the provider so unless it already knew.
9089 if (offer.neededFor(request)) {
9090 offer.onNetworkUnneeded(request);
9091 }
9092 }
9093 }
9094
Chalard Jean61c79252019-11-07 23:07:32 +09009095 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9096 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9097 NetworkRequest nr = nai.requestAt(i);
9098 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9099 // legacy type tracker filters out repeat adds
9100 mLegacyTypeTracker.add(nr.legacyType, nai);
9101 }
9102 }
9103
9104 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009105 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009106 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9107 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9108 if (nai.isVPN()) {
9109 mLegacyTypeTracker.add(TYPE_VPN, nai);
9110 }
9111 }
9112
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009113 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009114 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009115 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009116 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009117 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009118 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009119
Chalard Jean254bd162022-08-25 13:04:51 +09009120 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009121 // Don't repeat publish.
9122 if (newInetCondition == mDefaultInetConditionPublished) return;
9123
9124 mDefaultInetConditionPublished = newInetCondition;
9125 sendInetConditionBroadcast(nai.networkInfo);
9126 }
9127
Chalard Jeand61375d2020-01-14 22:46:36 +09009128 @NonNull
9129 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9130 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009131 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009132 final boolean suspended =
9133 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9134 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9135 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9136 // state. This is because the network could have been suspended before connecting,
9137 // or it could be disconnecting while being suspended, and in both these cases
9138 // the state should not be overridden. Note that the only detailed state that
9139 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9140 // worry about multiple different substates of CONNECTED.
9141 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9142 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009143 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9144 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9145 // network agent is created, then goes to suspended, then goes out of suspended without
9146 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009147 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009148 ? NetworkInfo.DetailedState.CONNECTED
9149 : NetworkInfo.DetailedState.CONNECTING,
9150 info.getReason(),
9151 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009152 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009153 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009154 return newInfo;
9155 }
9156
9157 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9158 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9159
Erik Kline99f301b2017-02-15 19:59:17 +09009160 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009161 NetworkInfo oldInfo = null;
9162 synchronized (networkAgent) {
9163 oldInfo = networkAgent.networkInfo;
9164 networkAgent.networkInfo = newInfo;
9165 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009166
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009167 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009168 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9169 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009170 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009171
Chalard Jean254bd162022-08-25 13:04:51 +09009172 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009173 && (state == NetworkInfo.State.CONNECTED
9174 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009175
9176 // A network that has just connected has zero requests and is thus a foreground network.
9177 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9178
Luke Huangfdd11f82019-04-09 18:41:49 +08009179 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009180 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009181 // Initialize the network's capabilities to their starting values according to the
9182 // underlying networks. This ensures that the capabilities are correct before
9183 // anything happens to the network.
9184 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009185 }
Chalard Jean254bd162022-08-25 13:04:51 +09009186 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009187 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009188 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009189 }
9190
Chalard Jean254bd162022-08-25 13:04:51 +09009191 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9192 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009193
lucaslin45e639b2019-04-03 17:09:28 +08009194 // NetworkCapabilities need to be set before sending the private DNS config to
9195 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009196 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9197
Erik Kline9a62f012018-03-21 07:18:33 -07009198 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009199 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9200 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009201
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009202 // If a rate limit has been configured and is applicable to this network (network
9203 // provides internet connectivity), apply it. The tc police filter cannot be attached
9204 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9205 // updateInterfaces -> INetd#networkAddInterface.
9206 // Note: in case of a system server crash, the NetworkController constructor in netd
9207 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9208 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9209 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9210 mIngressRateLimit);
9211 }
9212
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009213 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9214 // command must be sent after updating LinkProperties to maximize chances of
9215 // NetworkMonitor seeing the correct LinkProperties when starting.
9216 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009217 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009218 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009219 }
Chalard Jeand4900722022-02-06 12:25:38 +09009220 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9221 params.networkAgentConfig = networkAgent.networkAgentConfig;
9222 params.networkCapabilities = networkAgent.networkCapabilities;
9223 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9224 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009225 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9226 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9227 // call that would cause a Log.wtf to be emitted from the system_server process, and
9228 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9229 // process to check the interface version, just use an SDK check. NetworkStack will
9230 // always be new enough when running on T+.
9231 if (SdkLevel.isAtLeastT()) {
9232 networkAgent.networkMonitor().notifyNetworkConnected(params);
9233 } else {
9234 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9235 params.networkCapabilities);
9236 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09009237 scheduleEvaluationTimeout(networkAgent.network, INITIAL_EVALUATION_TIMEOUT_MS);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009238
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009239 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9240 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9241 // capabilities, so it only needs to be done once on initial connect, not every time the
9242 // network's capabilities change. Note that we do this before rematching the network,
9243 // so we could decide to tear it down immediately afterwards. That's fine though - on
9244 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9245 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009246 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009247
junyulai0ac374f2020-12-14 18:41:52 +08009248 // Before first rematching networks, put an inactivity timer without any request, this
9249 // allows {@code updateInactivityState} to update the state accordingly and prevent
9250 // tearing down for any {@code unneeded} evaluation in this period.
9251 // Note that the timer will not be rescheduled since the expiry time is
9252 // fixed after connection regardless of the network satisfying other requests or not.
9253 // But it will be removed as soon as the network satisfies a request for the first time.
9254 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9255 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009256 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009257
Paul Jensen05e85ee2014-09-11 11:00:39 -04009258 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009259 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009260
9261 // This has to happen after matching the requests, because callbacks are just requests.
9262 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009263 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009264 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009265 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009266 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009267 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009268 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009269 if (networkAgent.isVPN()) {
9270 // As the active or bound network changes for apps, broadcast the default proxy, as
9271 // apps may need to update their proxy data. This is called after disconnecting from
9272 // VPN to make sure we do not broadcast the old proxy data.
9273 // TODO(b/122649188): send the broadcast only to VPN users.
9274 mProxyTracker.sendProxyBroadcast();
9275 }
Chalard Jean254bd162022-08-25 13:04:51 +09009276 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9277 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009278 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009279 }
9280 }
9281
Chalard Jean28018572020-12-21 18:36:52 +09009282 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009283 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9284 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009285 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009286 }
9287
Erik Kline99f301b2017-02-15 19:59:17 +09009288 // Notify only this one new request of the current state. Transfer all the
9289 // current state by calling NetworkCapabilities and LinkProperties callbacks
9290 // so that callers can be guaranteed to have as close to atomicity in state
9291 // transfer as can be supported by this current API.
9292 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009293 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009294 if (nri.mPendingIntent != null) {
9295 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9296 // Attempt no subsequent state pushes where intents are involved.
9297 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009298 }
Erik Kline99f301b2017-02-15 19:59:17 +09009299
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009300 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009301 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009302 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9303 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9304 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009305 }
9306
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009307 // Notify the requests on this NAI that the network is now lingered.
9308 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009309 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009310 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9311 }
9312
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009313 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9314 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9315 return vpnBlocked
9316 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9317 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9318 }
9319
9320 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9321 if (blockedReasons == BLOCKED_REASON_NONE) {
9322 mUidBlockedReasons.delete(uid);
9323 } else {
9324 mUidBlockedReasons.put(uid, blockedReasons);
9325 }
9326 }
9327
junyulaif2c67e42018-08-07 19:50:45 +08009328 /**
9329 * Notify of the blocked state apps with a registered callback matching a given NAI.
9330 *
9331 * Unlike other callbacks, blocked status is different between each individual uid. So for
9332 * any given nai, all requests need to be considered according to the uid who filed it.
9333 *
9334 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009335 * @param oldMetered True if the previous network capabilities were metered.
9336 * @param newMetered True if the current network capabilities are metered.
9337 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9338 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009339 */
9340 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009341 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9342 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009343
9344 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9345 NetworkRequest nr = nai.requestAt(i);
9346 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009347
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009348 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9349 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9350 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009351 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009352 : oldVpnBlocked;
9353
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009354 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9355 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9356 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009357 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009358 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009359 }
9360 }
9361 }
9362
9363 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009364 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009365 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009366 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009367 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009368 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009369 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009370 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009371 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009372
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009373 final int oldBlockedState = getBlockedState(
9374 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9375 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9376 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009377 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009378 }
junyulaif2c67e42018-08-07 19:50:45 +08009379 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9380 NetworkRequest nr = nai.requestAt(i);
9381 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009382 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009383 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9384 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009385 }
9386 }
9387 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009388 }
9389
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009390 @VisibleForTesting
9391 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009392 // The NetworkInfo we actually send out has no bearing on the real
9393 // state of affairs. For example, if the default connection is mobile,
9394 // and a request for HIPRI has just gone away, we need to pretend that
9395 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9396 // the state to DISCONNECTED, even though the network is of type MOBILE
9397 // and is still connected.
9398 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9399 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009400 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009401 if (state != DetailedState.DISCONNECTED) {
9402 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009403 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009404 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009405 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009406 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9407 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9408 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9409 if (info.isFailover()) {
9410 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9411 nai.networkInfo.setFailover(false);
9412 }
9413 if (info.getReason() != null) {
9414 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9415 }
9416 if (info.getExtraInfo() != null) {
9417 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9418 }
9419 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009420 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009421 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009422 if (newDefaultAgent != null) {
9423 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9424 newDefaultAgent.networkInfo);
9425 } else {
9426 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9427 }
9428 }
9429 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9430 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009431 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009432 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009433 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009434 }
9435 }
9436 }
9437
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009438 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009439 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009440 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009441 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009442 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009443 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9444 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009445 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9446 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009447 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009448 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009449 } else {
9450 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9451 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009452 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009453 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009454
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009455 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9456 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9457 }
9458
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009459 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009460 * Returns the list of all interfaces that could be used by network traffic that does not
9461 * explicitly specify a network. This includes the default network, but also all VPNs that are
9462 * currently connected.
9463 *
9464 * Must be called on the handler thread.
9465 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009466 @NonNull
9467 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009468 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009469 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009470 final Set<Integer> activeNetIds = new ArraySet<>();
9471 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9472 if (nri.isBeingSatisfied()) {
9473 activeNetIds.add(nri.getSatisfier().network().netId);
9474 }
9475 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009476 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009477 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009478 defaultNetworks.add(nai.network);
9479 }
9480 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009481 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009482 }
9483
9484 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009485 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9486 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009487 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009488 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009489 ensureRunningOnConnectivityServiceThread();
9490 String activeIface = null;
9491 LinkProperties activeLinkProperties = getActiveLinkProperties();
9492 if (activeLinkProperties != null) {
9493 activeIface = activeLinkProperties.getInterfaceName();
9494 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009495
junyulai2050bed2021-01-23 09:46:34 +08009496 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009497 try {
junyulaide41fc22021-01-22 22:46:01 +08009498 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009499 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009500 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9501 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009502 } catch (Exception ignored) {
9503 }
9504 }
9505
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009506 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009507 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009508 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009509 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009510 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009511
9512 if (!TextUtils.isEmpty(settingUrl)) {
9513 return settingUrl;
9514 }
9515
9516 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009517 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009518 if (!TextUtils.isEmpty(settingUrl)) {
9519 return settingUrl;
9520 }
9521
9522 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009523 }
9524
9525 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009526 public void startNattKeepalive(Network network, int intervalSeconds,
9527 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009528 enforceKeepalivePermission();
9529 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009530 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009531 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009532 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009533 }
9534
9535 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009536 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009537 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009538 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009539 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009540 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009541 mKeepaliveTracker.startNattKeepalive(
9542 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9543 intervalSeconds, cb,
9544 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9545 } finally {
9546 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9547 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009548 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9549 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009550 }
9551 }
junyulaid05a1922019-01-15 11:32:44 +08009552 }
9553
9554 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009555 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009556 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009557 try {
9558 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009559 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009560 mKeepaliveTracker.startTcpKeepalive(
9561 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9562 } finally {
9563 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9564 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009565 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9566 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009567 }
9568 }
junyulai0835a1e2019-01-08 20:04:33 +08009569 }
9570
9571 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009572 public void stopKeepalive(Network network, int slot) {
9573 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009574 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009575 }
9576
9577 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009578 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009579 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009580
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009581 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009582 final long token = Binder.clearCallingIdentity();
9583 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009584 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9585 UserHandle.getUserHandleForUid(uid))) {
9586 return;
9587 }
9588
Heemin Seogdb8489d2019-06-12 09:21:44 -07009589 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9590 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009591
9592 // Turn airplane mode off
9593 setAirplaneMode(false);
9594
9595 // restore private DNS settings to default mode (opportunistic)
9596 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9597 UserHandle.getUserHandleForUid(uid))) {
9598 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9599 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9600 }
9601
9602 Settings.Global.putString(mContext.getContentResolver(),
9603 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009604 } finally {
9605 Binder.restoreCallingIdentity(token);
9606 }
Stuart Scottd5463642015-04-02 18:00:02 -07009607 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009608
Ricky Wai7097cc92018-01-23 04:09:45 +00009609 @Override
9610 public byte[] getNetworkWatchlistConfigHash() {
9611 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9612 if (nwm == null) {
9613 loge("Unable to get NetworkWatchlistManager");
9614 return null;
9615 }
9616 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9617 return nwm.getWatchlistConfigHash();
9618 }
9619
Hugo Benichibe0c7652016-05-31 16:28:06 +09009620 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009621 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009622 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009623 }
Hugo Benichif4210292017-04-21 15:07:12 +09009624
9625 private static boolean toBool(int encodedBoolean) {
9626 return encodedBoolean != 0; // Only 0 means false.
9627 }
9628
9629 private static int encodeBool(boolean b) {
9630 return b ? 1 : 0;
9631 }
mswest4632928412018-03-12 10:34:34 -07009632
9633 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009634 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9635 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9636 @NonNull String[] args) {
9637 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9638 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009639 }
9640
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009641 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009642 @Override
9643 public int onCommand(String cmd) {
9644 if (cmd == null) {
9645 return handleDefaultCommands(cmd);
9646 }
9647 final PrintWriter pw = getOutPrintWriter();
9648 try {
9649 switch (cmd) {
9650 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009651 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9652 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009653 final String action = getNextArg();
9654 if ("enable".equals(action)) {
9655 setAirplaneMode(true);
9656 return 0;
9657 } else if ("disable".equals(action)) {
9658 setAirplaneMode(false);
9659 return 0;
9660 } else if (action == null) {
9661 final ContentResolver cr = mContext.getContentResolver();
9662 final int enabled = Settings.Global.getInt(cr,
9663 Settings.Global.AIRPLANE_MODE_ON);
9664 pw.println(enabled == 0 ? "disabled" : "enabled");
9665 return 0;
9666 } else {
9667 onHelp();
9668 return -1;
9669 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009670 case "reevaluate":
9671 // Usage : adb shell cmd connectivity reevaluate <netId>
9672 // If netId is omitted, then reevaluate the default network
9673 final String netId = getNextArg();
9674 final NetworkAgentInfo nai;
9675 if (null == netId) {
9676 // Note that the command is running on the wrong thread to call this,
9677 // so this could in principle return stale data. But it can't crash.
9678 nai = getDefaultNetwork();
9679 } else {
9680 // If netId can't be parsed, this throws NumberFormatException, which
9681 // is passed back to adb who prints it.
9682 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
9683 }
9684 if (null == nai) {
9685 pw.println("Unknown network (net ID not found or no default network)");
9686 return 0;
9687 }
9688 Log.d(TAG, "Reevaluating network " + nai.network);
9689 reportNetworkConnectivity(nai.network, !nai.isValidated());
9690 return 0;
mswest4632928412018-03-12 10:34:34 -07009691 default:
9692 return handleDefaultCommands(cmd);
9693 }
9694 } catch (Exception e) {
9695 pw.println(e);
9696 }
9697 return -1;
9698 }
9699
9700 @Override
9701 public void onHelp() {
9702 PrintWriter pw = getOutPrintWriter();
9703 pw.println("Connectivity service commands:");
9704 pw.println(" help");
9705 pw.println(" Print this help text.");
9706 pw.println(" airplane-mode [enable|disable]");
9707 pw.println(" Turn airplane mode on or off.");
9708 pw.println(" airplane-mode");
9709 pw.println(" Get airplane mode.");
9710 }
9711 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009712
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009713 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009714 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9715 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9716 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009717 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009718 }
9719
he_won.hwang881307a2022-03-15 21:23:52 +09009720 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9721 if (nai == null) return;
9722 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9723 final TransportInfo newInfo = nc.getTransportInfo();
9724 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9725 return;
9726 }
9727 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009728 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009729 }
9730 }
9731
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009732 /**
9733 * @param connectionInfo the connection to resolve.
9734 * @return {@code uid} if the connection is found and the app has permission to observe it
9735 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9736 * connection is not found.
9737 */
9738 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009739 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9740 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9741 }
9742
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009743 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009744 connectionInfo.local, connectionInfo.remote);
9745
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009746 if (uid == INVALID_UID) return uid; // Not found.
9747
9748 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9749 // VPN, if any, that applies to the UID that owns the connection.
9750 if (checkNetworkStackPermission()) return uid;
9751
9752 final NetworkAgentInfo vpn = getVpnForUid(uid);
9753 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009754 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009755 return INVALID_UID;
9756 }
9757
9758 return uid;
9759 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009760
Benedict Wong493e04b2018-11-09 14:45:34 -08009761 /**
9762 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9763 *
9764 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9765 */
9766 @Override
9767 public IBinder startOrGetTestNetworkService() {
9768 synchronized (mTNSLock) {
9769 TestNetworkService.enforceTestNetworkPermissions(mContext);
9770
9771 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009772 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009773 }
9774
9775 return mTNS;
9776 }
9777 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009778
Cody Kesting73708bf2019-12-18 10:57:50 -08009779 /**
9780 * Handler used for managing all Connectivity Diagnostics related functions.
9781 *
9782 * @see android.net.ConnectivityDiagnosticsManager
9783 *
9784 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9785 */
9786 @VisibleForTesting
9787 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009788 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9789
Cody Kesting73708bf2019-12-18 10:57:50 -08009790 /**
9791 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9792 * android.net.ConnectivityDiagnosticsManager}.
9793 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9794 * NetworkRequestInfo to be registered
9795 */
9796 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9797
9798 /**
9799 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9800 * android.net.ConnectivityDiagnosticsManager}.
9801 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9802 * arg1 = the uid of the caller
9803 */
9804 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9805
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009806 /**
9807 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009808 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009809 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9810 * NetworkMonitor.
9811 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009812 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009813 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009814
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009815 /**
9816 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9817 * been detected on the network.
9818 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9819 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9820 * arg2 = NetID.
9821 * data = PersistableBundle of extras passed from NetworkMonitor.
9822 */
9823 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9824
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009825 /**
9826 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9827 * the platform. This event will invoke {@link
9828 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9829 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009830 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009831 */
9832 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9833
Cody Kesting73708bf2019-12-18 10:57:50 -08009834 private ConnectivityDiagnosticsHandler(Looper looper) {
9835 super(looper);
9836 }
9837
9838 @Override
9839 public void handleMessage(Message msg) {
9840 switch (msg.what) {
9841 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9842 handleRegisterConnectivityDiagnosticsCallback(
9843 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9844 break;
9845 }
9846 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9847 handleUnregisterConnectivityDiagnosticsCallback(
9848 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9849 break;
9850 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009851 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009852 final ConnectivityReportEvent reportEvent =
9853 (ConnectivityReportEvent) msg.obj;
9854
Aaron Huang959d3642021-01-21 15:47:41 +08009855 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009856 break;
9857 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009858 case EVENT_DATA_STALL_SUSPECTED: {
9859 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009860 final Pair<Long, PersistableBundle> arg =
9861 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009862 if (nai == null) break;
9863
Aaron Huang959d3642021-01-21 15:47:41 +08009864 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009865 break;
9866 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009867 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009868 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009869 break;
9870 }
9871 default: {
9872 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9873 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009874 }
9875 }
9876 }
9877
9878 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9879 @VisibleForTesting
9880 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9881 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9882 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009883 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009884
9885 @VisibleForTesting
9886 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009887 @NonNull IConnectivityDiagnosticsCallback cb,
9888 @NonNull NetworkRequestInfo nri,
9889 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009890 mCb = cb;
9891 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009892 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009893 }
9894
9895 @Override
9896 public void binderDied() {
9897 log("ConnectivityDiagnosticsCallback IBinder died.");
9898 unregisterConnectivityDiagnosticsCallback(mCb);
9899 }
9900 }
9901
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009902 /**
9903 * Class used for sending information from {@link
9904 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9905 */
9906 private static class NetworkTestedResults {
9907 private final int mNetId;
9908 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009909 @Nullable private final String mRedirectUrl;
9910
9911 private NetworkTestedResults(
9912 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9913 mNetId = netId;
9914 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009915 mRedirectUrl = redirectUrl;
9916 }
9917 }
9918
9919 /**
9920 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9921 * ConnectivityDiagnosticsHandler}.
9922 */
9923 private static class ConnectivityReportEvent {
9924 private final long mTimestampMillis;
9925 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009926 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009927
Aaron Huang959d3642021-01-21 15:47:41 +08009928 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9929 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009930 mTimestampMillis = timestampMillis;
9931 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009932 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009933 }
9934 }
9935
Cody Kestingf1120be2020-08-03 18:01:40 -07009936 /**
9937 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9938 * ConnectivityDiagnosticsHandler}.
9939 */
9940 private static class ReportedNetworkConnectivityInfo {
9941 public final boolean hasConnectivity;
9942 public final boolean isNetworkRevalidating;
9943 public final int reporterUid;
9944 @NonNull public final NetworkAgentInfo nai;
9945
9946 private ReportedNetworkConnectivityInfo(
9947 boolean hasConnectivity,
9948 boolean isNetworkRevalidating,
9949 int reporterUid,
9950 @NonNull NetworkAgentInfo nai) {
9951 this.hasConnectivity = hasConnectivity;
9952 this.isNetworkRevalidating = isNetworkRevalidating;
9953 this.reporterUid = reporterUid;
9954 this.nai = nai;
9955 }
9956 }
9957
Cody Kesting73708bf2019-12-18 10:57:50 -08009958 private void handleRegisterConnectivityDiagnosticsCallback(
9959 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9960 ensureRunningOnConnectivityServiceThread();
9961
9962 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009963 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009964 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9965
James Mattis64b8b0f2020-11-24 17:40:49 -08009966 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9967 // confusing for these networks to change when an NRI is satisfied in another layer.
9968 if (nri.isMultilayerRequest()) {
9969 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9970 + "network requests.");
9971 }
9972
Cody Kesting73708bf2019-12-18 10:57:50 -08009973 // This means that the client registered the same callback multiple times. Do
9974 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009975 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009976 if (VDBG) log("Diagnostics callback is already registered");
9977
9978 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9979 // incremented when the NetworkRequestInfo is created as part of
9980 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009981 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -08009982 return;
9983 }
9984
Cody Kesting31f1ff62020-03-05 10:46:02 -08009985 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009986
9987 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009988 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009989 } catch (RemoteException e) {
9990 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009991 return;
9992 }
9993
9994 // Once registered, provide ConnectivityReports for matching Networks
9995 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9996 synchronized (mNetworkForNetId) {
9997 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9998 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009999 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10000 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010001 matchingNetworks.add(nai);
10002 }
10003 }
10004 }
10005 for (final NetworkAgentInfo nai : matchingNetworks) {
10006 final ConnectivityReport report = nai.getConnectivityReport();
10007 if (report == null) {
10008 continue;
10009 }
10010 if (!checkConnectivityDiagnosticsPermissions(
10011 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10012 continue;
10013 }
10014
10015 try {
10016 cb.onConnectivityReportAvailable(report);
10017 } catch (RemoteException e) {
10018 // Exception while sending the ConnectivityReport. Move on to the next network.
10019 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010020 }
10021 }
10022
10023 private void handleUnregisterConnectivityDiagnosticsCallback(
10024 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10025 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010026 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010027
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010028 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10029 mConnectivityDiagnosticsCallbacks.remove(iCb);
10030 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010031 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10032 return;
10033 }
10034
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010035 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010036
Cody Kesting70fa2b22020-12-02 12:16:56 -080010037 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10038 // (if the Binder died)
10039 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10040 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010041 return;
10042 }
10043
Cody Kesting46cb1672020-03-04 13:35:20 -080010044 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10045 // incremented when the NetworkRequestInfo is created as part of
10046 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010047 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010048
Cody Kesting31f1ff62020-03-05 10:46:02 -080010049 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010050 }
10051
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010052 private void handleNetworkTestedWithExtras(
10053 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10054 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010055 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010056 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010057 final ConnectivityReport report =
10058 new ConnectivityReport(
10059 reportEvent.mNai.network,
10060 reportEvent.mTimestampMillis,
10061 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010062 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010063 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010064 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010065
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010066 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010067 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010068 for (final IConnectivityDiagnosticsCallback cb : results) {
10069 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010070 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010071 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010072 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010073 }
10074 }
10075 }
10076
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010077 private void handleDataStallSuspected(
10078 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10079 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010080 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010081 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010082 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010083 new DataStallReport(
10084 nai.network,
10085 timestampMillis,
10086 detectionMethod,
10087 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010088 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010089 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010090 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010091 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010092 for (final IConnectivityDiagnosticsCallback cb : results) {
10093 try {
10094 cb.onDataStallSuspected(report);
10095 } catch (RemoteException ex) {
10096 loge("Error invoking onDataStallSuspected", ex);
10097 }
10098 }
10099 }
10100
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010101 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010102 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10103 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10104 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10105
10106 // If the Network is being re-validated as a result of this call to
10107 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10108 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010109 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010110 getMatchingPermissionedCallbacks(
10111 nai,
10112 reportedNetworkConnectivityInfo.isNetworkRevalidating
10113 ? Process.INVALID_UID
10114 : reportedNetworkConnectivityInfo.reporterUid);
10115
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010116 for (final IConnectivityDiagnosticsCallback cb : results) {
10117 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010118 cb.onNetworkConnectivityReported(
10119 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010120 } catch (RemoteException ex) {
10121 loge("Error invoking onNetworkConnectivityReported", ex);
10122 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010123
10124 // If the Network isn't re-validating, also provide the cached report. If there is no
10125 // cached report, the Network is still being validated and a report will be sent once
10126 // validation is complete. Note that networks which never undergo validation will still
10127 // have a cached ConnectivityReport with RESULT_SKIPPED.
10128 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10129 try {
10130 cb.onConnectivityReportAvailable(cachedReport);
10131 } catch (RemoteException ex) {
10132 loge("Error invoking onConnectivityReportAvailable", ex);
10133 }
10134 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010135 }
10136 }
10137
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010138 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010139 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10140 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010141 sanitized.setUids(null);
10142 sanitized.setAdministratorUids(new int[0]);
10143 sanitized.setOwnerUid(Process.INVALID_UID);
10144 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010145 }
10146
Cody Kestingf1120be2020-08-03 18:01:40 -070010147 /**
10148 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10149 *
10150 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10151 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010152 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010153 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010154 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010155 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010156 mConnectivityDiagnosticsCallbacks.entrySet()) {
10157 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10158 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010159
James Mattis64b8b0f2020-11-24 17:40:49 -080010160 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010161 if (!nai.satisfies(nri.mRequests.get(0))) {
10162 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010163 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010164
10165 // UID for this callback must either be:
10166 // - INVALID_UID (which sends callbacks to all UIDs), or
10167 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10168 // notified as a result)
10169 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10170 continue;
10171 }
10172
10173 if (!checkConnectivityDiagnosticsPermissions(
10174 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10175 continue;
10176 }
10177
10178 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010179 }
10180 return results;
10181 }
10182
Cody Kesting7474f672021-05-11 14:22:40 -070010183 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10184 @NonNull NetworkAgentInfo nai) {
10185 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10186 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10187 }
10188
Cody Kesting160ef392021-05-05 13:17:22 -070010189 private boolean hasLocationPermission(String packageName, int uid) {
10190 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10191 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10192 // call in a try-catch.
10193 try {
10194 if (!mLocationPermissionChecker.checkLocationPermission(
10195 packageName, null /* featureId */, uid, null /* message */)) {
10196 return false;
10197 }
10198 } catch (SecurityException e) {
10199 return false;
10200 }
10201
10202 return true;
10203 }
10204
10205 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10206 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010207 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010208 && virtual.networkCapabilities.getOwnerUid() == uid
10209 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10210 return true;
10211 }
10212 }
10213
10214 return false;
10215 }
10216
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010217 @VisibleForTesting
10218 boolean checkConnectivityDiagnosticsPermissions(
10219 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10220 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10221 return true;
10222 }
10223
Cody Kesting160ef392021-05-05 13:17:22 -070010224 // Administrator UIDs also contains the Owner UID
10225 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10226 if (!CollectionUtils.contains(administratorUids, callbackUid)
10227 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010228 return false;
10229 }
10230
Cody Kesting7474f672021-05-11 14:22:40 -070010231 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10232 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010233 }
10234
Cody Kestingd199a9d2019-12-17 12:55:28 -080010235 @Override
10236 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010237 @NonNull IConnectivityDiagnosticsCallback callback,
10238 @NonNull NetworkRequest request,
10239 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010240 Objects.requireNonNull(callback, "callback must not be null");
10241 Objects.requireNonNull(request, "request must not be null");
10242 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10243
Cody Kesting73708bf2019-12-18 10:57:50 -080010244 if (request.legacyType != TYPE_NONE) {
10245 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10246 + " Please use NetworkCapabilities instead.");
10247 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010248 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010249 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010250
10251 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10252 // and administrator uids to be safe.
10253 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010254 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010255
10256 final NetworkRequest requestWithId =
10257 new NetworkRequest(
10258 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10259
10260 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10261 //
10262 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10263 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10264 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010265 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010266 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010267 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010268
10269 mConnectivityDiagnosticsHandler.sendMessage(
10270 mConnectivityDiagnosticsHandler.obtainMessage(
10271 ConnectivityDiagnosticsHandler
10272 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10273 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010274 }
10275
10276 @Override
10277 public void unregisterConnectivityDiagnosticsCallback(
10278 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010279 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010280 mConnectivityDiagnosticsHandler.sendMessage(
10281 mConnectivityDiagnosticsHandler.obtainMessage(
10282 ConnectivityDiagnosticsHandler
10283 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010284 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010285 0,
10286 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010287 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010288
10289 @Override
10290 public void simulateDataStall(int detectionMethod, long timestampMillis,
10291 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010292 Objects.requireNonNull(network, "network must not be null");
10293 Objects.requireNonNull(extras, "extras must not be null");
10294
paulhu3ffffe72021-09-16 10:15:22 +080010295 enforceAnyPermissionOf(mContext,
10296 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010297 android.Manifest.permission.NETWORK_STACK);
10298 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10299 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010300 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010301 }
10302
10303 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010304 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010305 throw new SecurityException("Data Stall simulation is only possible for network "
10306 + "creators");
10307 }
10308
Cody Kesting652e3ec2020-05-21 12:08:21 -070010309 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10310 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10311 // Data Stall information as a DataStallReportParcelable and passing to
10312 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10313 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010314 final DataStallReportParcelable p = new DataStallReportParcelable();
10315 p.timestampMillis = timestampMillis;
10316 p.detectionMethod = detectionMethod;
10317
10318 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10319 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10320 }
10321 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10322 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10323 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10324 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10325 }
10326
Serik Beketayevec8ad212020-12-07 22:43:07 -080010327 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010328 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010329
lucaslin66f44212021-02-23 01:12:55 +080010330 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10331 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010332 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010333 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010334 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010335 }
lucaslin37a16d92021-01-21 19:48:09 +080010336
10337 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010338 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010339 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010340 nai.clatd.interfaceLinkStateChanged(iface, up);
10341 }
10342 }
10343
10344 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010345 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010346 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010347 nai.clatd.interfaceRemoved(iface);
10348 }
lucaslin66f44212021-02-23 01:12:55 +080010349 }
10350 }
10351
lucaslin1a8b4c62021-01-21 02:02:55 +080010352 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10353
10354 /**
10355 * Class used for updating network activity tracking with netd and notify network activity
10356 * changes.
10357 */
10358 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010359 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010360 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010361 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010362 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10363 new RemoteCallbackList<>();
10364 // Indicate the current system default network activity is active or not.
10365 @GuardedBy("mActiveIdleTimers")
10366 private boolean mNetworkActive;
10367 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010368 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010369 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010370
Chalard Jean46bfbf02022-02-02 00:56:25 +090010371 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010372 public final int timeout;
10373 public final int transportType;
10374
10375 IdleTimerParams(int timeout, int transport) {
10376 this.timeout = timeout;
10377 this.transportType = transport;
10378 }
10379 }
10380
10381 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010382 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010383 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010384 mNetd = netd;
10385 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010386 }
10387
lucaslin66f44212021-02-23 01:12:55 +080010388 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10389 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10390 synchronized (mActiveIdleTimers) {
10391 mNetworkActive = active;
10392 // If there are no idle timers, it means that system is not monitoring
10393 // activity, so the system default network for those default network
10394 // unspecified apps is always considered active.
10395 //
10396 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10397 // any network activity change event. Whenever this event is received,
10398 // the mActiveIdleTimers should be always not empty. The legacy behavior
10399 // is no-op. Remove to refer to mNetworkActive only.
10400 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10401 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10402 }
10403 }
10404 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010405
lucaslin1193a5d2021-01-21 02:04:15 +080010406 // The network activity should only be updated from ConnectivityService handler thread
10407 // when mActiveIdleTimers lock is held.
10408 @GuardedBy("mActiveIdleTimers")
10409 private void reportNetworkActive() {
10410 final int length = mNetworkActivityListeners.beginBroadcast();
10411 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10412 try {
10413 for (int i = 0; i < length; i++) {
10414 try {
10415 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10416 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010417 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010418 }
10419 }
10420 } finally {
10421 mNetworkActivityListeners.finishBroadcast();
10422 }
10423 }
10424
10425 @GuardedBy("mActiveIdleTimers")
10426 public void handleReportNetworkActivity() {
10427 synchronized (mActiveIdleTimers) {
10428 reportNetworkActive();
10429 }
10430 }
10431
lucaslin1a8b4c62021-01-21 02:02:55 +080010432 // This is deprecated and only to support legacy use cases.
10433 private int transportTypeToLegacyType(int type) {
10434 switch (type) {
10435 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010436 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010437 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010438 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010439 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010440 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010441 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010442 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010443 default:
10444 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10445 }
10446 return ConnectivityManager.TYPE_NONE;
10447 }
10448
10449 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10450 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10451 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10452 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10453 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10454 final long ident = Binder.clearCallingIdentity();
10455 try {
10456 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10457 RECEIVE_DATA_ACTIVITY_CHANGE,
10458 null /* resultReceiver */,
10459 null /* scheduler */,
10460 0 /* initialCode */,
10461 null /* initialData */,
10462 null /* initialExtra */);
10463 } finally {
10464 Binder.restoreCallingIdentity(ident);
10465 }
10466 }
10467
10468 /**
10469 * Setup data activity tracking for the given network.
10470 *
10471 * Every {@code setupDataActivityTracking} should be paired with a
10472 * {@link #removeDataActivityTracking} for cleanup.
10473 */
10474 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10475 final String iface = networkAgent.linkProperties.getInterfaceName();
10476
10477 final int timeout;
10478 final int type;
10479
10480 if (networkAgent.networkCapabilities.hasTransport(
10481 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10482 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010483 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010484 10);
10485 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10486 } else if (networkAgent.networkCapabilities.hasTransport(
10487 NetworkCapabilities.TRANSPORT_WIFI)) {
10488 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010489 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010490 15);
10491 type = NetworkCapabilities.TRANSPORT_WIFI;
10492 } else {
10493 return; // do not track any other networks
10494 }
10495
lucaslinb961efc2021-01-21 02:03:17 +080010496 updateRadioPowerState(true /* isActive */, type);
10497
lucaslin1a8b4c62021-01-21 02:02:55 +080010498 if (timeout > 0 && iface != null) {
10499 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010500 synchronized (mActiveIdleTimers) {
10501 // Networks start up.
10502 mNetworkActive = true;
10503 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10504 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10505 reportNetworkActive();
10506 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010507 } catch (Exception e) {
10508 // You shall not crash!
10509 loge("Exception in setupDataActivityTracking " + e);
10510 }
10511 }
10512 }
10513
10514 /**
10515 * Remove data activity tracking when network disconnects.
10516 */
10517 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10518 final String iface = networkAgent.linkProperties.getInterfaceName();
10519 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10520
lucaslinb961efc2021-01-21 02:03:17 +080010521 if (iface == null) return;
10522
10523 final int type;
10524 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10525 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10526 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10527 type = NetworkCapabilities.TRANSPORT_WIFI;
10528 } else {
10529 return; // do not track any other networks
10530 }
10531
10532 try {
10533 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010534 synchronized (mActiveIdleTimers) {
10535 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10536 // The call fails silently if no idle timer setup for this interface
10537 mNetd.idletimerRemoveInterface(iface, params.timeout,
10538 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010539 }
lucaslinb961efc2021-01-21 02:03:17 +080010540 } catch (Exception e) {
10541 // You shall not crash!
10542 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010543 }
10544 }
10545
10546 /**
10547 * Update data activity tracking when network state is updated.
10548 */
10549 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10550 NetworkAgentInfo oldNetwork) {
10551 if (newNetwork != null) {
10552 setupDataActivityTracking(newNetwork);
10553 }
10554 if (oldNetwork != null) {
10555 removeDataActivityTracking(oldNetwork);
10556 }
10557 }
lucaslinb961efc2021-01-21 02:03:17 +080010558
10559 private void updateRadioPowerState(boolean isActive, int transportType) {
10560 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10561 switch (transportType) {
10562 case NetworkCapabilities.TRANSPORT_CELLULAR:
10563 bs.reportMobileRadioPowerState(isActive, NO_UID);
10564 break;
10565 case NetworkCapabilities.TRANSPORT_WIFI:
10566 bs.reportWifiRadioPowerState(isActive, NO_UID);
10567 break;
10568 default:
10569 logw("Untracked transport type:" + transportType);
10570 }
10571 }
lucaslin1193a5d2021-01-21 02:04:15 +080010572
10573 public boolean isDefaultNetworkActive() {
10574 synchronized (mActiveIdleTimers) {
10575 // If there are no idle timers, it means that system is not monitoring activity,
10576 // so the default network is always considered active.
10577 //
10578 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10579 // tracking is disabled (negative idle timer value configured), or no active default
10580 // network. In the latter case, this reports active but it should report inactive.
10581 return mNetworkActive || mActiveIdleTimers.isEmpty();
10582 }
10583 }
10584
10585 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10586 mNetworkActivityListeners.register(l);
10587 }
10588
10589 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10590 mNetworkActivityListeners.unregister(l);
10591 }
lucaslin012f7a12021-01-21 02:04:35 +080010592
10593 public void dump(IndentingPrintWriter pw) {
10594 synchronized (mActiveIdleTimers) {
10595 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10596 pw.println("Idle timers:");
10597 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10598 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10599 final IdleTimerParams params = ent.getValue();
10600 pw.print(" timeout="); pw.print(params.timeout);
10601 pw.print(" type="); pw.println(params.transportType);
10602 }
10603 }
10604 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010605 }
James Mattis47db0582021-01-01 14:13:35 -080010606
Daniel Brightf9e945b2020-06-15 16:10:01 -070010607 /**
10608 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10609 *
10610 * @param socketInfo the socket information
10611 * @param callback the callback to register
10612 */
10613 @Override
10614 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10615 @NonNull final IQosCallback callback) {
10616 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10617 if (nai == null || nai.networkCapabilities == null) {
10618 try {
10619 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10620 } catch (final RemoteException ex) {
10621 loge("registerQosCallbackInternal: RemoteException", ex);
10622 }
10623 return;
10624 }
10625 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10626 }
10627
10628 /**
10629 * Register a {@link IQosCallback} with base {@link QosFilter}.
10630 *
10631 * @param filter the filter to register
10632 * @param callback the callback to register
10633 * @param nai the agent information related to the filter's network
10634 */
10635 @VisibleForTesting
10636 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10637 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010638 Objects.requireNonNull(filter, "filter must be non-null");
10639 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010640
10641 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010642 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10643 // on this network is unregistered when the app loses permission or b) no QoS
10644 // callbacks are sent for restricted networks unless the app currently has permission
10645 // to access restricted networks.
10646 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010647 }
10648 mQosCallbackTracker.registerCallback(callback, filter, nai);
10649 }
10650
10651 /**
10652 * Unregisters the given callback.
10653 *
10654 * @param callback the callback to unregister
10655 */
10656 @Override
10657 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010658 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010659 mQosCallbackTracker.unregisterCallback(callback);
10660 }
James Mattis47db0582021-01-01 14:13:35 -080010661
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010662 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10663 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10664 // Enterprise device can be fully managed like device owner and such use case
10665 // also should be supported. Calling app check for work profile and fully managed device
10666 // is already done in DevicePolicyManager.
10667 // This check is an extra caution to be sure device is fully managed or not.
10668 final UserManager um = mContext.getSystemService(UserManager.class);
10669 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10670 if (um.isManagedProfile(profile.getIdentifier())) {
10671 return true;
10672 }
10673 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10674 return false;
10675 }
10676
James Mattis45d81842021-01-10 14:24:24 -080010677 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010678 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010679 *
10680 * See the documentation for the individual preferences for a description of the supported
10681 * behaviors.
10682 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010683 * @param profile If the device owner is set, any profile is allowed.
10684 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010685 * @param preferences the list of profile network preferences for the
10686 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010687 * @param listener an optional listener to listen for completion of the operation.
10688 */
10689 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010690 public void setProfileNetworkPreferences(
10691 @NonNull final UserHandle profile,
10692 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010693 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010694 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010695 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010696
10697 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010698 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10699 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10700 .build();
10701 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010702 }
10703
paulhu3ffffe72021-09-16 10:15:22 +080010704 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010705 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010706 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010707 }
10708 if (profile.getIdentifier() < 0) {
10709 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10710 + "UserHandle.CURRENT not supported)");
10711 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010712 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10713 throw new IllegalArgumentException("Profile must be a managed profile "
10714 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010715 }
paulhuaa0743d2021-05-26 21:56:03 +080010716
Chalard Jean46bfbf02022-02-02 00:56:25 +090010717 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010718 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010719 for (final ProfileNetworkPreference preference : preferences) {
10720 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010721 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010722 switch (preference.getPreference()) {
10723 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10724 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010725 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010726 if (preference.getPreferenceEnterpriseId() != 0) {
10727 throw new IllegalArgumentException(
10728 "Invalid enterprise identifier in setProfileNetworkPreferences");
10729 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010730 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010731 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10732 allowFallback = false;
10733 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010734 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010735 // This code is needed even though there is a check later on,
10736 // because isRangeAlreadyInPreferenceList assumes that every preference
10737 // has a UID list.
10738 if (hasDefaultPreference) {
10739 throw new IllegalArgumentException(
10740 "Default profile preference should not be set along with other "
10741 + "preference");
10742 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010743 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10744 throw new IllegalArgumentException(
10745 "Invalid enterprise identifier in setProfileNetworkPreferences");
10746 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010747 final Set<UidRange> uidRangeSet =
10748 getUidListToBeAppliedForNetworkPreference(profile, preference);
10749 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10750 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10751 } else {
10752 throw new IllegalArgumentException(
10753 "Overlapping uid range in setProfileNetworkPreferences");
10754 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010755 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010756 nc.addEnterpriseId(
10757 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010758 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10759 break;
10760 default:
10761 throw new IllegalArgumentException(
10762 "Invalid preference in setProfileNetworkPreferences");
10763 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010764 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10765 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010766 if (hasDefaultPreference && preferenceList.size() > 1) {
10767 throw new IllegalArgumentException(
10768 "Default profile preference should not be set along with other preference");
10769 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010770 }
10771 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010772 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010773 }
10774
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010775 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10776 @NonNull final UserHandle profile,
10777 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10778 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010779 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10780 profileNetworkPreference.getIncludedUids());
10781
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010782 if (uidRangeSet.size() > 0) {
10783 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10784 throw new IllegalArgumentException(
10785 "Allow uid range is outside the uid range of profile.");
10786 }
10787 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010788 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010789 profileNetworkPreference.getExcludedUids());
10790 if (disallowUidRangeSet.size() > 0) {
10791 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10792 throw new IllegalArgumentException(
10793 "disallow uid range is outside the uid range of profile.");
10794 }
10795 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10796 disallowUidRangeSet);
10797 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010798 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010799 uidRangeSet.add(profileUids);
10800 }
10801 }
10802 return uidRangeSet;
10803 }
10804
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010805 private boolean isEnterpriseIdentifierValid(
10806 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010807 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010808 return true;
10809 }
10810 return false;
10811 }
10812
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010813 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010814 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010815 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010816 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010817 // The NRI for a user should contain the request for capabilities.
10818 // If fallback to default network is needed then NRI should include
10819 // the request for the default network. Create an image of it to
10820 // have the correct UIDs in it (also a request can only be part of one NRI, because
10821 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010822 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10823 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010824 if (pref.allowFallback) {
10825 nrs.add(createDefaultInternetRequestForTransport(
10826 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10827 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010828 if (VDBG) {
10829 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10830 pref.capabilities.getUids()));
10831 }
10832
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010833 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010834 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010835 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010836 result.add(nri);
10837 }
10838 return result;
10839 }
10840
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010841 /**
10842 * Compare if the given UID range sets have the same UIDs.
10843 *
10844 */
10845 private boolean isRangeAlreadyInPreferenceList(
10846 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10847 @NonNull Set<UidRange> uidRangeSet) {
10848 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10849 return false;
10850 }
10851 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10852 if (UidRangeUtils.doesRangeSetOverlap(
10853 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10854 return true;
10855 }
10856 }
10857 return false;
10858 }
10859
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010860 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010861 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010862 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010863 /*
10864 * handleSetProfileNetworkPreference is always called for single user.
10865 * preferenceList only contains preferences for different uids within the same user
10866 * (enforced by getUidListToBeAppliedForNetworkPreference).
10867 * Clear all the existing preferences for the user before applying new preferences.
10868 *
10869 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010870 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010871 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010872 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010873 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10874 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010875
paulhu74128522021-09-28 02:29:03 +000010876 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10877 addPerAppDefaultNetworkRequests(
10878 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010879
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010880 // Finally, rematch.
10881 rematchAllNetworksAndRequests();
10882
10883 if (null != listener) {
10884 try {
10885 listener.onComplete();
10886 } catch (RemoteException e) {
10887 loge("Listener for setProfileNetworkPreference has died");
10888 }
10889 }
10890 }
10891
paulhu51f77dc2021-06-07 02:34:20 +000010892 @VisibleForTesting
10893 @NonNull
10894 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10895 @NonNull final Set<Integer> uids) {
10896 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10897 if (uids.size() == 0) {
10898 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10899 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10900 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10901 return nris;
10902 }
10903
10904 final List<NetworkRequest> requests = new ArrayList<>();
10905 // The NRI should be comprised of two layers:
10906 // - The request for the mobile network preferred.
10907 // - The request for the default network, for fallback.
10908 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010909 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010910 requests.add(createDefaultInternetRequestForTransport(
10911 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10912 final Set<UidRange> ranges = new ArraySet<>();
10913 for (final int uid : uids) {
10914 ranges.add(new UidRange(uid, uid));
10915 }
10916 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010917 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010918 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010919 return nris;
10920 }
10921
10922 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010923 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010924 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10925 addPerAppDefaultNetworkRequests(
10926 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010927 // Finally, rematch.
10928 rematchAllNetworksAndRequests();
10929 }
10930
Patrick Rohr2857ac42022-01-21 14:58:16 +010010931 private void handleIngressRateLimitChanged() {
10932 final long oldIngressRateLimit = mIngressRateLimit;
10933 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10934 mContext);
10935 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10936 if (canNetworkBeRateLimited(networkAgent)) {
10937 // If rate limit has previously been enabled, remove the old limit first.
10938 if (oldIngressRateLimit >= 0) {
10939 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10940 }
10941 if (mIngressRateLimit >= 0) {
10942 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10943 mIngressRateLimit);
10944 }
10945 }
10946 }
10947 }
10948
10949 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010950 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10951 if (!SdkLevel.isAtLeastT()) return false;
10952
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010953 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10954 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10955 // internet connectivity can be rate limited.
10956 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10957 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010958 return false;
10959 }
10960
10961 final String iface = networkAgent.linkProperties.getInterfaceName();
10962 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010010963 // This may happen in tests, but if there is no interface then there is nothing that
10964 // can be rate limited.
10965 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010010966 return false;
10967 }
10968 return true;
10969 }
10970
James Mattis45d81842021-01-10 14:24:24 -080010971 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010972 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10973 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010974 }
10975
10976 /**
10977 * Used by automotive devices to set the network preferences used to direct traffic at an
10978 * application level as per the given OemNetworkPreferences. An example use-case would be an
10979 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10980 * vehicle via a particular network.
10981 *
10982 * Calling this will overwrite the existing preference.
10983 *
James Mattisda32cfe2021-01-26 16:23:52 -080010984 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010985 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010986 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010987 */
James Mattis47db0582021-01-01 14:13:35 -080010988 @Override
James Mattis45d81842021-01-10 14:24:24 -080010989 public void setOemNetworkPreference(
10990 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010991 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010992
James Mattisfa270db2021-05-31 17:11:10 -070010993 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10994 // Only bypass the permission/device checks if this is a valid test request.
10995 if (isValidTestOemNetworkPreference(preference)) {
10996 enforceManageTestNetworksPermission();
10997 } else {
10998 enforceAutomotiveDevice();
10999 enforceOemNetworkPreferencesPermission();
11000 validateOemNetworkPreferences(preference);
11001 }
James Mattis45d81842021-01-10 14:24:24 -080011002
James Mattis45d81842021-01-10 14:24:24 -080011003 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11004 new Pair<>(preference, listener)));
11005 }
11006
James Mattisfa270db2021-05-31 17:11:10 -070011007 /**
11008 * Check the validity of an OEM network preference to be used for testing purposes.
11009 * @param preference the preference to validate
11010 * @return true if this is a valid OEM network preference test request.
11011 */
11012 private boolean isValidTestOemNetworkPreference(
11013 @NonNull final OemNetworkPreferences preference) {
11014 // Allow for clearing of an existing OemNetworkPreference used for testing.
11015 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11016 // changes after this check is complete. This is an unlikely scenario as calling of this API
11017 // is controlled by the OEM therefore the added complexity is not worth adding given those
11018 // circumstances. That said, it is an edge case to be aware of hence this comment.
11019 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11020 && isTestOemNetworkPreference(mOemNetworkPreferences);
11021 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11022 }
11023
11024 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11025 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11026 return prefMap.size() == 1
11027 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11028 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11029 }
11030
James Mattis45d81842021-01-10 14:24:24 -080011031 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11032 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11033 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011034 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11035 throw new IllegalArgumentException(
11036 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11037 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011038 }
11039 }
11040 }
11041
11042 private void handleSetOemNetworkPreference(
11043 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011044 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011045 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11046 if (DBG) {
11047 log("set OEM network preferences :" + preference.toString());
11048 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011049
James Mattiscb1e0362021-04-06 17:07:42 -070011050 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011051 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11052 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11053 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011054 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011055
11056 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011057 try {
11058 listener.onComplete();
11059 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011060 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011061 }
James Mattis45d81842021-01-10 14:24:24 -080011062 }
11063 }
11064
paulhu74128522021-09-28 02:29:03 +000011065 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011066 // Skip the requests which are set by other network preference. Because the uid range rules
11067 // should stay in netd.
11068 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011069 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011070 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011071 }
11072
James Mattis3ce3d3c2021-02-09 18:18:28 -080011073 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11074 ensureRunningOnConnectivityServiceThread();
11075 mDefaultNetworkRequests.addAll(nris);
11076 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11077 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011078 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011079 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11080 nrisToRegister.addAll(
11081 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11082 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011083 }
11084
11085 /**
11086 * All current requests that are tracking the default network need to be assessed as to whether
11087 * or not the current set of per-application default requests will be changing their default
11088 * network. If so, those requests will need to be updated so that they will send callbacks for
11089 * default network changes at the appropriate time. Additionally, those requests tracking the
11090 * default that were previously updated by this flow will need to be reassessed.
11091 * @return the nris which will need to be updated.
11092 */
11093 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11094 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11095 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11096 // same nri in the map's values for each of its NetworkRequest objects.
11097 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011098 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011099 // Include this nri if it is currently being tracked.
11100 if (isPerAppTrackedNri(nri)) {
11101 defaultCallbackRequests.add(nri);
11102 continue;
11103 }
11104 // We only track callbacks for requests tracking the default.
11105 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11106 continue;
11107 }
11108 // Include this nri if it will be tracked by the new per-app default requests.
11109 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011110 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011111 if (isNriGoingToBeTracked) {
11112 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011113 }
11114 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011115 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011116 }
11117
James Mattis3ce3d3c2021-02-09 18:18:28 -080011118 /**
11119 * Create nris for those network requests that are currently tracking the default network that
11120 * are being controlled by a per-application default.
11121 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11122 * foundation when creating the nri. Important items include the calling uid's original
11123 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11124 * requests are assumed to have already been validated as needing to be updated.
11125 * @return the Set of nris to use when registering network requests.
11126 */
11127 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11128 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11129 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11130 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11131 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011132 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011133
Chalard Jean9473c982021-07-29 20:03:04 +090011134 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011135 if (trackingNri == mDefaultRequest) {
11136 callbackRequestsToRegister.add(new NetworkRequestInfo(
11137 callbackRequest,
11138 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11139 continue;
11140 }
11141
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011142 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011143 callbackRequestsToRegister.add(new NetworkRequestInfo(
11144 callbackRequest,
11145 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011146 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011147 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011148 }
11149 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011150 }
11151
Chalard Jean17215832021-03-01 14:06:28 +090011152 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11153 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011154 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011155 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011156 }
11157 }
11158
James Mattis45d81842021-01-10 14:24:24 -080011159 /**
11160 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11161 */
11162 @VisibleForTesting
11163 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011164 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011165 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011166 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011167 final SparseArray<Set<Integer>> uids =
11168 createUidsFromOemNetworkPreferences(preference);
11169 for (int i = 0; i < uids.size(); i++) {
11170 final int key = uids.keyAt(i);
11171 final Set<Integer> value = uids.valueAt(i);
11172 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11173 // No need to add an nri without any requests.
11174 if (0 == nri.mRequests.size()) {
11175 continue;
11176 }
11177 nris.add(nri);
11178 }
11179
11180 return nris;
11181 }
11182
11183 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11184 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011185 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011186 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011187 final List<UserHandle> users =
11188 mContext.getSystemService(UserManager.class).getUserHandles(true);
11189 if (null == users || users.size() == 0) {
11190 if (VDBG || DDBG) {
11191 log("No users currently available for setting the OEM network preference.");
11192 }
James Mattisb6b6a432021-06-01 22:30:36 -070011193 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011194 }
James Mattis45d81842021-01-10 14:24:24 -080011195 for (final Map.Entry<String, Integer> entry :
11196 preference.getNetworkPreferences().entrySet()) {
11197 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011198 // Add the rules for all users as this policy is device wide.
11199 for (final UserHandle user : users) {
11200 try {
11201 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11202 if (!prefToUids.contains(pref)) {
11203 prefToUids.put(pref, new ArraySet<>());
11204 }
11205 prefToUids.get(pref).add(uid);
11206 } catch (PackageManager.NameNotFoundException e) {
11207 // Although this may seem like an error scenario, it is ok that uninstalled
11208 // packages are sent on a network preference as the system will watch for
11209 // package installations associated with this network preference and update
11210 // accordingly. This is done to minimize race conditions on app install.
11211 continue;
James Mattis45d81842021-01-10 14:24:24 -080011212 }
James Mattis45d81842021-01-10 14:24:24 -080011213 }
11214 }
James Mattisb6b6a432021-06-01 22:30:36 -070011215 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011216 }
11217
11218 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11219 @OemNetworkPreferences.OemNetworkPreference final int preference,
11220 @NonNull final Set<Integer> uids) {
11221 final List<NetworkRequest> requests = new ArrayList<>();
11222 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11223 switch (preference) {
11224 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11225 requests.add(createUnmeteredNetworkRequest());
11226 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011227 requests.add(createDefaultInternetRequestForTransport(
11228 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011229 break;
11230 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11231 requests.add(createUnmeteredNetworkRequest());
11232 requests.add(createOemPaidNetworkRequest());
11233 break;
11234 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11235 requests.add(createOemPaidNetworkRequest());
11236 break;
11237 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11238 requests.add(createOemPrivateNetworkRequest());
11239 break;
James Mattisfa270db2021-05-31 17:11:10 -070011240 case OEM_NETWORK_PREFERENCE_TEST:
11241 requests.add(createUnmeteredNetworkRequest());
11242 requests.add(createTestNetworkRequest());
11243 requests.add(createDefaultRequest());
11244 break;
11245 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11246 requests.add(createTestNetworkRequest());
11247 break;
James Mattis45d81842021-01-10 14:24:24 -080011248 default:
11249 // This should never happen.
11250 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11251 + " called with invalid preference of " + preference);
11252 }
11253
James Mattisfa270db2021-05-31 17:11:10 -070011254 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011255 for (final int uid : uids) {
11256 ranges.add(new UidRange(uid, uid));
11257 }
11258 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011259 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011260 }
11261
11262 private NetworkRequest createUnmeteredNetworkRequest() {
11263 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11264 .addCapability(NET_CAPABILITY_NOT_METERED)
11265 .addCapability(NET_CAPABILITY_VALIDATED);
11266 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11267 }
11268
11269 private NetworkRequest createOemPaidNetworkRequest() {
11270 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11271 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11272 .addCapability(NET_CAPABILITY_OEM_PAID)
11273 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11274 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11275 }
11276
11277 private NetworkRequest createOemPrivateNetworkRequest() {
11278 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11279 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11280 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11281 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11282 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11283 }
11284
11285 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011286 final NetworkCapabilities netcap = new NetworkCapabilities();
11287 netcap.addCapability(NET_CAPABILITY_INTERNET);
11288 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11289 return netcap;
11290 }
11291
11292 private NetworkRequest createTestNetworkRequest() {
11293 final NetworkCapabilities netcap = new NetworkCapabilities();
11294 netcap.clearAll();
11295 netcap.addTransportType(TRANSPORT_TEST);
11296 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011297 }
James Mattis47db0582021-01-01 14:13:35 -080011298 }
markchien738ad912021-12-09 18:15:45 +080011299
11300 @Override
11301 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11302 enforceNetworkStackOrSettingsPermission();
11303
11304 try {
11305 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011306 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011307 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011308 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011309 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011310 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011311 throw new IllegalStateException(e);
11312 }
11313 }
11314
11315 @Override
11316 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11317 enforceNetworkStackOrSettingsPermission();
11318
11319 try {
11320 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011321 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011322 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011323 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011324 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011325 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011326 throw new IllegalStateException(e);
11327 }
11328 }
markchiene1561fa2021-12-09 22:00:56 +080011329
11330 @Override
markchien3c04e662022-03-22 16:29:56 +080011331 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011332 enforceNetworkStackOrSettingsPermission();
11333
markchien3c04e662022-03-22 16:29:56 +080011334 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11335 int firewallRule = getFirewallRuleType(chain, rule);
11336
11337 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11338 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11339 }
11340
markchiene1561fa2021-12-09 22:00:56 +080011341 try {
markchien3c04e662022-03-22 16:29:56 +080011342 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011343 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011344 throw new IllegalStateException(e);
11345 }
11346 }
markchien98a6f952022-01-13 23:43:53 +080011347
markchien3c04e662022-03-22 16:29:56 +080011348 private int getFirewallRuleType(int chain, int rule) {
11349 final int defaultRule;
11350 switch (chain) {
11351 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011352 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11353 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011354 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011355 defaultRule = FIREWALL_RULE_ALLOW;
11356 break;
11357 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11358 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11359 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11360 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11361 defaultRule = FIREWALL_RULE_DENY;
11362 break;
11363 default:
11364 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11365 }
11366 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11367
11368 return rule;
11369 }
11370
markchien98a6f952022-01-13 23:43:53 +080011371 @Override
11372 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11373 enforceNetworkStackOrSettingsPermission();
11374
11375 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011376 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011377 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011378 throw new IllegalStateException(e);
11379 }
11380 }
11381
markchien00a0bed2022-01-13 23:46:13 +080011382 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011383 public boolean getFirewallChainEnabled(final int chain) {
11384 enforceNetworkStackOrSettingsPermission();
11385
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011386 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011387 }
11388
11389 @Override
markchien00a0bed2022-01-13 23:46:13 +080011390 public void replaceFirewallChain(final int chain, final int[] uids) {
11391 enforceNetworkStackOrSettingsPermission();
11392
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011393 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011394 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011395}