blob: 10b3dc89258abfa2e25d3f2d399888f2e14d498d [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;
he_won.hwang881307a2022-03-15 21:23:52 +0900208import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800209import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800210import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800211import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700212import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800213import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700214import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700215import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216import android.os.Looper;
217import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700218import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700219import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900220import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800221import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700222import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700223import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800224import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700225import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900226import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900227import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700228import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700229import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400230import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900232import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700233import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700234import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800236import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900237import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000238import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600239import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900240import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700241import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700242import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800243
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900244import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400245import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400246import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700247import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900248import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800249import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900250import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800251import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900252import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900253import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100254import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900255import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
256import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900257import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800258import com.android.net.module.util.NetworkCapabilitiesUtils;
Junyu Lai00d92df2022-07-05 11:01:52 +0800259import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800260import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100261import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000262import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900263import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800264import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800265import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900266import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900267import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500268import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700269import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900270import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900271import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100272import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700273import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900274import com.android.server.connectivity.MultinetworkPolicyTracker;
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.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900360 // Timeout in case the "actively prefer bad wifi" feature is on
361 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
362 // Timeout in case the "actively prefer bad wifi" feature is off
363 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900364
junyulai0ac374f2020-12-14 18:41:52 +0800365 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900366 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
367 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800368 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700369
he_won.hwang881307a2022-03-15 21:23:52 +0900370 // The maximum value for the blocking validation result, in milliseconds.
371 public static final int MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS = 10000;
372
Daniel Brightf9e945b2020-06-15 16:10:01 -0700373 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900374 @VisibleForTesting
375 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700376
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900377 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700378 @VisibleForTesting
379 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900380
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900381 @VisibleForTesting
382 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800383 @VisibleForTesting
384 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900385 // True if the cell radio of the device is capable of time-sharing.
386 @VisibleForTesting
387 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900388
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800389 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800390 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800391 private final int mReleasePendingIntentDelayMs;
392
Chalard Jean46bfbf02022-02-02 00:56:25 +0900393 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900394
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000395 @VisibleForTesting
396 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700397
Chalard Jean9473c982021-07-29 20:03:04 +0900398 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800399 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700400 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800401 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700402
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900403 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700404
junyulaif2c67e42018-08-07 19:50:45 +0800405 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000406 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
407 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800408 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900409 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800410
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900411 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900412 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000413 // The Context is created for UserHandle.ALL.
414 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900415 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900416 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700417 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700418 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800419
Chenbo Feng15416292018-11-08 17:36:21 -0800420 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800421 protected IDnsResolver mDnsResolver;
422 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800423 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700424 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900425 private final NetworkStatsManager mStatsManager;
426 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800427 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700428
Benedict Wong493e04b2018-11-09 14:45:34 -0800429 /**
430 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
431 * instances.
432 */
433 @GuardedBy("mTNSLock")
434 private TestNetworkService mTNS;
435
436 private final Object mTNSLock = new Object();
437
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700438 private String mCurrentTcpBufferSizes;
439
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900440 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800441 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900442
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500443 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400444 // Tear down networks that have no chance (e.g. even if validated) of becoming
445 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500446 // all networks have been rematched against all NetworkRequests.
447 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400448 // Don't reap networks. This should be passed when some networks have not yet been
449 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500450 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900451 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500452
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900453 private enum UnneededFor {
454 LINGER, // Determine whether this network is unneeded and should be lingered.
455 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
456 }
457
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700458 /**
paulhuaa0743d2021-05-26 21:56:03 +0800459 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800460 * should have priority. The order is passed to netd which will use it together
461 * with UID ranges to generate the corresponding IP rule. This serves to
462 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800463 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800464 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000465 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800466 *
paulhu48291862021-07-14 14:53:57 +0800467 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
468 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800469 */
paulhu48291862021-07-14 14:53:57 +0800470 // Used when sending to netd to code for "no order".
471 static final int PREFERENCE_ORDER_NONE = 0;
472 // Order for requests that don't code for a per-app preference. As it is
473 // out of the valid range, the corresponding order should be
474 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800475 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800476 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800477 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800478 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
479 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800480 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800481 static final int PREFERENCE_ORDER_OEM = 10;
482 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800483 // See {@link #setProfileNetworkPreference}.
484 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800485 static final int PREFERENCE_ORDER_PROFILE = 20;
486 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800487 // better scores are connected.
488 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800489 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800490 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900491 // Preference order that signifies the network shouldn't be set as a default network for
492 // the UIDs, only give them access to it. TODO : replace this with a boolean
493 // in NativeUidRangeConfig
494 @VisibleForTesting
495 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
496 // Bound for the lowest valid preference order.
497 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800498
499 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700500 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700501 * from one net to another. Clear happens when we get a new
502 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
503 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700504 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700505 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700506
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700507 /**
508 * used internally to reload global proxy settings
509 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700510 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700511
Robert Greenwalt34848c02011-03-25 13:09:25 -0700512 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400513 * PAC manager has received new port.
514 */
515 private static final int EVENT_PROXY_HAS_CHANGED = 16;
516
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700517 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900518 * used internally when registering NetworkProviders
519 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700520 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900521 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700522
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700523 /**
524 * used internally when registering NetworkAgents
525 * obj = Messenger
526 */
527 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
528
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700529 /**
530 * used to add a network request
531 * includes a NetworkRequestInfo
532 */
533 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
534
535 /**
536 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900537 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700538 * cancel it.
539 * includes a NetworkRequestInfo
540 */
541 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
542
543 /**
544 * used to add a network listener - no request
545 * includes a NetworkRequestInfo
546 */
547 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
548
549 /**
550 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400551 * arg1 = UID of caller
552 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700553 */
554 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
555
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700556 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900557 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700558 * obj = Messenger
559 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900560 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700561
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700562 /**
563 * used internally to expire a wakelock when transitioning
564 * from one net to another. Expire happens when we fail to find
565 * a new network (typically after 1 minute) -
566 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
567 * a replacement network.
568 */
569 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
570
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700571 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800572 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400573 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800574 */
575 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
576
577 /**
578 * used to remove a pending intent and its associated network request.
579 * arg1 = UID of caller
580 * obj = PendingIntent
581 */
582 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
583
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900584 /**
585 * used to specify whether a network should be used even if unvalidated.
586 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
587 * arg2 = whether to remember this choice in the future (1 or 0)
588 * obj = network
589 */
590 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
591
592 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700593 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900594 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700595 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900596
Paul Jensenc8873fc2015-06-17 14:15:39 -0400597 /**
598 * used to add a network listener with a pending intent
599 * obj = NetworkRequestInfo
600 */
601 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
602
Hugo Benichid6b510a2017-04-06 17:22:18 +0900603 /**
604 * used to specify whether a network should not be penalized when it becomes unvalidated.
605 */
606 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
607
608 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700609 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900610 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700611 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900612
Erik Kline31b4a9e2018-01-11 21:07:29 +0900613 // Handle changes in Private DNS settings.
614 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
615
dalyk1720e542018-03-05 12:42:22 -0500616 // Handle private DNS validation status updates.
617 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
618
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900619 /**
620 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
621 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800622 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
623 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
624 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900625 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900626 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900627
628 /**
629 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
630 * config was resolved.
631 * obj = PrivateDnsConfig
632 * arg2 = netid
633 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900634 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900635
636 /**
637 * Request ConnectivityService display provisioning notification.
638 * arg1 = Whether to make the notification visible.
639 * arg2 = NetID.
640 * obj = Intent to be launched when notification selected by user, null if !arg1.
641 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900642 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900643
644 /**
lucaslin2240ef62019-03-12 13:08:03 +0800645 * Used to specify whether a network should be used even if connectivity is partial.
646 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
647 * false)
648 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
649 * obj = network
650 */
lucaslin444d43a2020-02-20 16:56:59 +0800651 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800652
653 /**
lucasline117e2e2019-10-22 18:27:33 +0800654 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
655 * Both of the arguments are bitmasks, and the value of bits come from
656 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900657 * arg1 = unused
658 * arg2 = netId
659 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800660 */
lucaslin444d43a2020-02-20 16:56:59 +0800661 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800662
663 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900664 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
665 * arg1 = unused
666 * arg2 = netId
667 * obj = captive portal data
668 */
lucaslin444d43a2020-02-20 16:56:59 +0800669 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900670
671 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900672 * Used by setRequireVpnForUids.
673 * arg1 = whether the specified UID ranges are required to use a VPN.
674 * obj = Array of UidRange objects.
675 */
676 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
677
678 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900679 * Used internally when setting the default networks for OemNetworkPreferences.
680 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800681 */
682 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
683
684 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800685 * Used to indicate the system default network becomes active.
686 */
687 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
688
689 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900690 * Used internally when setting a network preference for a user profile.
691 * obj = Pair<ProfileNetworkPreference, Listener>
692 */
693 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
694
695 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000696 * Event to specify that reasons for why an uid is blocked changed.
697 * arg1 = uid
698 * arg2 = blockedReasons
699 */
700 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
701
702 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900703 * Event to register a new network offer
704 * obj = NetworkOffer
705 */
706 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
707
708 /**
709 * Event to unregister an existing network offer
710 * obj = INetworkOfferCallback
711 */
712 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
713
714 /**
paulhu51f77dc2021-06-07 02:34:20 +0000715 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
716 */
717 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
718
719 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800720 * Event to set temporary allow bad wifi within a limited time to override
721 * {@code config_networkAvoidBadWifi}.
722 */
723 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
724
725 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100726 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
727 */
728 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
729
730 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900731 * The initial evaluation period is over for this network.
732 *
733 * If no form of connectivity has been found on this network (valid, partial, captive portal)
734 * then the stack will now consider it to have been determined bad.
735 */
736 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
737
738 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900739 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
740 * should be shown.
741 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900742 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900743
744 /**
745 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
746 * should be hidden.
747 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900748 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900749
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800750 /**
751 * The maximum alive time to allow bad wifi configuration for testing.
752 */
753 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
754
Patrick Rohr2857ac42022-01-21 14:58:16 +0100755 /**
756 * The priority of the tc police rate limiter -- smaller value is higher priority.
757 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
758 */
759 private static final short TC_PRIO_POLICE = 1;
760
761 /**
762 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
763 */
764 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700765 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100766
Hugo Benichi47011212017-03-30 10:46:05 +0900767 private static String eventName(int what) {
768 return sMagicDecoderRing.get(what, Integer.toString(what));
769 }
770
paulhua10d8212020-11-10 15:32:56 +0800771 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900772 final DnsResolverServiceManager dsm = context.getSystemService(
773 DnsResolverServiceManager.class);
774 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800775 }
776
Cody Kesting73708bf2019-12-18 10:57:50 -0800777 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900778 @VisibleForTesting
779 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700780 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700781 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700782 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700783 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800784 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
785 @VisibleForTesting
786 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
787
Erik Kline32120082017-12-13 19:40:49 +0900788 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900789 @VisibleForTesting
790 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700791
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400792 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800793 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400794
Chalard Jean46bfbf02022-02-02 00:56:25 +0900795 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800796 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700797
Chalard Jean5d70ba42018-06-07 16:44:04 +0900798 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
799 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000800 @VisibleForTesting
801 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400802
Erik Kline05f2b402015-04-30 12:58:40 +0900803 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700804
Chalard Jean46bfbf02022-02-02 00:56:25 +0900805 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400806
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700807 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900808 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700809
Valentin Iftime9fa35092019-09-24 13:32:13 +0200810 private Set<String> mWolSupportedInterfaces;
811
Roshan Pius08c94fb2020-01-16 12:17:17 -0800812 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800813 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800814 private final AppOpsManager mAppOpsManager;
815
816 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400817
Chalard Jean46bfbf02022-02-02 00:56:25 +0900818 private final KeepaliveTracker mKeepaliveTracker;
819 private final QosCallbackTracker mQosCallbackTracker;
820 private final NetworkNotificationManager mNotifier;
821 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900822
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700823 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800824 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700825
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900826 // Sequence number for NetworkProvider IDs.
827 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
828 NetworkProvider.FIRST_PROVIDER_ID);
829
Erik Klineedf878b2015-07-09 18:24:03 +0900830 // NetworkRequest activity String log entries.
831 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
832 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
833
Hugo Benichid159fdd2016-07-11 11:05:12 +0900834 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900835 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900836 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
837
Hugo Benichi47011212017-03-30 10:46:05 +0900838 private static final int MAX_WAKELOCK_LOGS = 20;
839 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900840 private int mTotalWakelockAcquisitions = 0;
841 private int mTotalWakelockReleases = 0;
842 private long mTotalWakelockDurationMs = 0;
843 private long mMaxWakelockDurationMs = 0;
844 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900845
Hugo Benichi208c0102016-07-28 17:53:06 +0900846 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900847
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700848 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900849 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700850
Erik Kline95ecfee2016-10-02 18:02:14 +0900851 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900852 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900853
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900854 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800855 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
856 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800857
Patrick Rohr2857ac42022-01-21 14:58:16 +0100858 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
859 // configured via {@link
860 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
861 // Only the handler thread is allowed to access this field.
862 private long mIngressRateLimit = -1;
863
Robert Greenwalt802c1102014-06-02 15:32:02 -0700864 /**
865 * Implements support for the legacy "one network per network type" model.
866 *
867 * We used to have a static array of NetworkStateTrackers, one for each
868 * network type, but that doesn't work any more now that we can have,
869 * for example, more that one wifi network. This class stores all the
870 * NetworkAgentInfo objects that support a given type, but the legacy
871 * API will only see the first one.
872 *
873 * It serves two main purposes:
874 *
875 * 1. Provide information about "the network for a given type" (since this
876 * API only supports one).
877 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
878 * the first network for a given type changes, or if the default network
879 * changes.
880 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900881 @VisibleForTesting
882 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900883
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900884 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900885 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900886
Robert Greenwalt802c1102014-06-02 15:32:02 -0700887 /**
888 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
889 * Each list holds references to all NetworkAgentInfos that are used to
890 * satisfy requests for that network type.
891 *
892 * This array is built out at startup such that an unsupported network
893 * doesn't get an ArrayList instance, making this a tristate:
894 * unsupported, supported but not active and active.
895 *
896 * The actual lists are populated when we scan the network types that
897 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900898 *
899 * Threading model:
900 * - addSupportedType() is only called in the constructor
901 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
902 * They are therefore not thread-safe with respect to each other.
903 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
904 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900905 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900906 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700907 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900908 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900909 @NonNull
910 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700911
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900912 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
913 // an entry have no timer (equivalent to -1). Lazily loaded.
914 @NonNull
915 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
916
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900917 LegacyTypeTracker(@NonNull ConnectivityService service) {
918 mService = service;
919 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700920 }
921
Chiachang Wang3bc52762021-11-25 14:17:57 +0800922 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
923 // addressed.
924 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900925 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
926 final PackageManager pm = ctx.getPackageManager();
927 if (pm.hasSystemFeature(FEATURE_WIFI)) {
928 addSupportedType(TYPE_WIFI);
929 }
930 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
931 addSupportedType(TYPE_WIFI_P2P);
932 }
933 if (tm.isDataCapable()) {
934 // Telephony does not have granular support for these types: they are either all
935 // supported, or none is supported
936 addSupportedType(TYPE_MOBILE);
937 addSupportedType(TYPE_MOBILE_MMS);
938 addSupportedType(TYPE_MOBILE_SUPL);
939 addSupportedType(TYPE_MOBILE_DUN);
940 addSupportedType(TYPE_MOBILE_HIPRI);
941 addSupportedType(TYPE_MOBILE_FOTA);
942 addSupportedType(TYPE_MOBILE_IMS);
943 addSupportedType(TYPE_MOBILE_CBS);
944 addSupportedType(TYPE_MOBILE_IA);
945 addSupportedType(TYPE_MOBILE_EMERGENCY);
946 }
947 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
948 addSupportedType(TYPE_BLUETOOTH);
949 }
950 if (pm.hasSystemFeature(FEATURE_WATCH)) {
951 // TYPE_PROXY is only used on Wear
952 addSupportedType(TYPE_PROXY);
953 }
954 // Ethernet is often not specified in the configs, although many devices can use it via
955 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000956 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900957 addSupportedType(TYPE_ETHERNET);
958 }
959
960 // Always add TYPE_VPN as a supported type
961 addSupportedType(TYPE_VPN);
962 }
963
964 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700965 if (mTypeLists[type] != null) {
966 throw new IllegalStateException(
967 "legacy list for type " + type + "already initialized");
968 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900969 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700970 }
971
Robert Greenwalt802c1102014-06-02 15:32:02 -0700972 public boolean isTypeSupported(int type) {
973 return isNetworkTypeValid(type) && mTypeLists[type] != null;
974 }
975
976 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900977 synchronized (mTypeLists) {
978 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
979 return mTypeLists[type].get(0);
980 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700981 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900982 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700983 }
984
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900985 public int getRestoreTimerForType(int type) {
986 synchronized (mTypeLists) {
987 if (mRestoreTimers == null) {
988 mRestoreTimers = loadRestoreTimers();
989 }
990 return mRestoreTimers.getOrDefault(type, -1);
991 }
992 }
993
994 private ArrayMap<Integer, Integer> loadRestoreTimers() {
995 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900996 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900997 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
998 for (final String config : configs) {
999 final String[] splits = TextUtils.split(config, ",");
1000 if (splits.length != 2) {
1001 logwtf("Invalid restore timer token count: " + config);
1002 continue;
1003 }
1004 try {
1005 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1006 } catch (NumberFormatException e) {
1007 logwtf("Invalid restore timer number format: " + config, e);
1008 }
1009 }
1010 return ret;
1011 }
1012
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001013 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001014 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001015 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001016 log("Sending " + state
1017 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001018 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001019 }
1020 }
1021
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001022 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1023 // network type, to preserve previous behaviour.
1024 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1025 if (vpnNai != mService.getLegacyLockdownNai()) return;
1026
1027 if (vpnNai.declaredUnderlyingNetworks == null
1028 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1029 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1030 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1031 return;
1032 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001033 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001034 vpnNai.declaredUnderlyingNetworks[0]);
1035 if (underlyingNai == null) return;
1036
1037 final int type = underlyingNai.networkInfo.getType();
1038 final DetailedState state = DetailedState.CONNECTED;
1039 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1040 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1041 }
1042
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001043 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001044 public void add(int type, NetworkAgentInfo nai) {
1045 if (!isTypeSupported(type)) {
1046 return; // Invalid network type.
1047 }
1048 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1049
1050 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1051 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001052 return;
1053 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001054 synchronized (mTypeLists) {
1055 list.add(nai);
1056 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001057
Chalard Jean5b409c72021-02-04 13:12:59 +09001058 // Send a broadcast if this is the first network of its type or if it's the default.
1059 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001060
1061 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1062 // to preserve previous behaviour.
1063 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001064 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001065 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1066 mService.sendLegacyNetworkBroadcast(nai, state, type);
1067 }
1068
1069 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1070 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001071 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001072 }
1073
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001074 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001075 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001076 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1077 if (list == null || list.isEmpty()) {
1078 return;
1079 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001080 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001081
Hugo Benichi389633f2016-06-21 09:48:07 +09001082 synchronized (mTypeLists) {
1083 if (!list.remove(nai)) {
1084 return;
1085 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001086 }
1087
Lorenzo Colitti49767722015-05-01 00:30:10 +09001088 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001089 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1090 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001091 }
1092
1093 if (!list.isEmpty() && wasFirstNetwork) {
1094 if (DBG) log("Other network available for type " + type +
1095 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001096 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001097 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001098 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001099 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001100 }
1101 }
1102
1103 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001104 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1105 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001106 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001107 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001108 }
1109 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001110
Chalard Jean46bfbf02022-02-02 00:56:25 +09001111 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001112 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001113 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001114 final DetailedState state = nai.networkInfo.getDetailedState();
1115 for (int type = 0; type < mTypeLists.length; type++) {
1116 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001117 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001118 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001119 if (isFirst || contains && isDefault) {
1120 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001121 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001122 }
1123 }
1124 }
1125
Robert Greenwalt94e22142014-07-30 16:31:24 -07001126 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001127 pw.println("mLegacyTypeTracker:");
1128 pw.increaseIndent();
1129 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001130 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001131 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001132 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001133 pw.println();
1134 pw.println("Current state:");
1135 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001136 synchronized (mTypeLists) {
1137 for (int type = 0; type < mTypeLists.length; type++) {
1138 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1139 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001140 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001141 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001142 }
1143 }
1144 pw.decreaseIndent();
1145 pw.decreaseIndent();
1146 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001147 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001148 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001149 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001150
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001151 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001152 /**
1153 * Helper class which parses out priority arguments and dumps sections according to their
1154 * priority. If priority arguments are omitted, function calls the legacy dump command.
1155 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001156 private class LocalPriorityDump {
1157 private static final String PRIORITY_ARG = "--dump-priority";
1158 private static final String PRIORITY_ARG_HIGH = "HIGH";
1159 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1160
1161 LocalPriorityDump() {}
1162
1163 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1164 doDump(fd, pw, new String[] {DIAG_ARG});
1165 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001166 }
1167
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001168 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1169 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001170 }
1171
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001172 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1173 if (args == null) {
1174 dumpNormal(fd, pw, args);
1175 return;
1176 }
1177
1178 String priority = null;
1179 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1180 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1181 argIndex++;
1182 priority = args[argIndex];
1183 }
1184 }
1185
1186 if (PRIORITY_ARG_HIGH.equals(priority)) {
1187 dumpHigh(fd, pw);
1188 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1189 dumpNormal(fd, pw, args);
1190 } else {
1191 // ConnectivityService publishes binder service using publishBinderService() with
1192 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001193 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1194 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001195 // TODO: Integrate into signal dump.
1196 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001197 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001198 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001199 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001200
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001201 /**
1202 * Dependencies of ConnectivityService, for injection in tests.
1203 */
1204 @VisibleForTesting
1205 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001206 public int getCallingUid() {
1207 return Binder.getCallingUid();
1208 }
1209
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001210 /**
1211 * Get system properties to use in ConnectivityService.
1212 */
1213 public MockableSystemProperties getSystemProperties() {
1214 return new MockableSystemProperties();
1215 }
1216
1217 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001218 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1219 */
1220 public ConnectivityResources getResources(@NonNull Context ctx) {
1221 return new ConnectivityResources(ctx);
1222 }
1223
1224 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001225 * Create a HandlerThread to use in ConnectivityService.
1226 */
1227 public HandlerThread makeHandlerThread() {
1228 return new HandlerThread("ConnectivityServiceThread");
1229 }
1230
1231 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001232 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001233 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001234 public NetworkStackClientBase getNetworkStack() {
1235 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001236 }
1237
1238 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001239 * @see ProxyTracker
1240 */
1241 public ProxyTracker makeProxyTracker(@NonNull Context context,
1242 @NonNull Handler connServiceHandler) {
1243 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1244 }
1245
1246 /**
1247 * @see NetIdManager
1248 */
1249 public NetIdManager makeNetIdManager() {
1250 return new NetIdManager();
1251 }
1252
1253 /**
1254 * @see NetworkUtils#queryUserAccess(int, int)
1255 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001256 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1257 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001258 }
1259
1260 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001261 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1262 * requires CAP_NET_ADMIN, which the unit tests do not have.
1263 */
1264 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1265 InetSocketAddress remote) {
1266 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1267 }
1268
1269 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001270 * @see MultinetworkPolicyTracker
1271 */
1272 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1273 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1274 return new MultinetworkPolicyTracker(c, h, r);
1275 }
1276
Aaron Huang330a4c02020-10-27 03:36:19 +08001277 /**
1278 * @see BatteryStatsManager
1279 */
1280 public void reportNetworkInterfaceForTransports(Context context, String iface,
1281 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001282 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001283 context.getSystemService(BatteryStatsManager.class);
1284 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1285 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001286
1287 public boolean getCellular464XlatEnabled() {
1288 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1289 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001290
1291 /**
1292 * @see PendingIntent#intentFilterEquals
1293 */
1294 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1295 return a.intentFilterEquals(b);
1296 }
1297
1298 /**
1299 * @see LocationPermissionChecker
1300 */
1301 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1302 return new LocationPermissionChecker(context);
1303 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001304
1305 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001306 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001307 *
1308 * This method returns null in versions before T, where carrier privilege
1309 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001310 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001311 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001312 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1313 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1314 if (SdkLevel.isAtLeastT()) {
1315 return new CarrierPrivilegeAuthenticator(context, tm);
1316 } else {
1317 return null;
1318 }
1319 }
1320
1321 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001322 * @see DeviceConfigUtils#isFeatureEnabled
1323 */
1324 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1325 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1326 TETHERING_MODULE_NAME, defaultEnabled);
1327 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001328
1329 /**
1330 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001331 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001332 * @return BpfNetMaps implementation.
1333 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001334 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1335 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001336 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001337
1338 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001339 * @see ClatCoordinator
1340 */
1341 public ClatCoordinator getClatCoordinator(INetd netd) {
1342 return new ClatCoordinator(
1343 new ClatCoordinator.Dependencies() {
1344 @NonNull
1345 public INetd getNetd() {
1346 return netd;
1347 }
1348 });
1349 }
1350
1351 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001352 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1353 */
1354 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1355 final InterfaceParams params = InterfaceParams.getByName(iface);
1356 if (params == null) {
1357 // the interface might have disappeared.
1358 logw("Failed to get interface params for interface " + iface);
1359 return;
1360 }
1361 try {
1362 // converting rateInBytesPerSecond from long to int is safe here because the
1363 // setting's range is limited to INT_MAX.
1364 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001365 Log.i(TAG,
1366 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001367 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1368 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1369 } catch (IOException e) {
1370 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1371 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1372 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1373 + ") failure: ", e);
1374 }
1375 }
1376
1377 /**
1378 * Wraps {@link TcUtils#tcFilterDelDev}
1379 */
1380 public void disableIngressRateLimit(String iface) {
1381 final InterfaceParams params = InterfaceParams.getByName(iface);
1382 if (params == null) {
1383 // the interface might have disappeared.
1384 logw("Failed to get interface params for interface " + iface);
1385 return;
1386 }
1387 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001388 Log.i(TAG,
1389 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001390 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1391 } catch (IOException e) {
1392 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1393 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1394 }
1395 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001396 }
1397
junyulaie7c7d2a2021-01-26 15:29:15 +08001398 public ConnectivityService(Context context) {
1399 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001400 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1401 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001402 }
1403
1404 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001405 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1406 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001407 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001408
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001409 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001410 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001411 mSystemProperties = mDeps.getSystemProperties();
1412 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001413 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001414 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001415 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1416 // Pass limit - 1 to maintain backward compatibility.
1417 // TODO: Remove the workaround.
1418 mNetworkRequestCounter =
1419 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1420 mSystemNetworkRequestCounter =
1421 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001422
Hugo Benichi208c0102016-07-28 17:53:06 +09001423 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001424 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1425 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001426 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001427 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001428 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001429 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1430 mDefaultNetworkRequests.add(mDefaultRequest);
1431 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001432
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001433 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001434 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001435
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001436 // The default WiFi request is a background request so that apps using WiFi are
1437 // migrated to a better network (typically ethernet) when one comes up, instead
1438 // of staying on WiFi forever.
1439 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1440 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1441
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001442 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1443 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1444 NetworkRequest.Type.BACKGROUND_REQUEST);
1445
Chalard Jean0702f982021-09-16 21:50:07 +09001446 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1447 // TODO: Consider making the timer customizable.
1448 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1449 mCellularRadioTimesharingCapable =
1450 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1451
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001452 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001453 mHandlerThread.start();
1454 mHandler = new InternalHandler(mHandlerThread.getLooper());
1455 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001456 mConnectivityDiagnosticsHandler =
1457 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001458
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001459 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001460 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001461
junyulaie7c7d2a2021-01-26 15:29:15 +08001462 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001463 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001464 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001465 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001466
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001467 mNetd = netd;
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001468 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001469 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001470 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001471 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001472 mCarrierPrivilegeAuthenticator =
1473 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001474
Sudheer Shanka9967d462021-03-18 19:09:25 +00001475 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001476 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1477 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001478 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001479
1480 final PowerManager powerManager = (PowerManager) context.getSystemService(
1481 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001482 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001483 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001484
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001485 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1486 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001487 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001488 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001489 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001490 mProtectedNetworks.add(p);
1491 } else {
1492 if (DBG) loge("Ignoring protectedNetwork " + p);
1493 }
1494 }
1495
soma, kawata29444ae2019-05-23 09:30:40 +09001496 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1497
Wayne Ma2fde98c2022-01-17 18:04:05 +08001498 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001499
James Mattis02220e22021-03-13 19:27:21 -08001500 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001501 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001502 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001503 final IntentFilter userIntentFilter = new IntentFilter();
1504 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1505 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1506 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1507 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001508
James Mattis02220e22021-03-13 19:27:21 -08001509 // Listen to package add/removes for netd
1510 final IntentFilter packageIntentFilter = new IntentFilter();
1511 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1512 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1513 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1514 packageIntentFilter.addDataScheme("package");
1515 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001516 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001517
lucaslind5c2d072021-02-20 18:59:47 +08001518 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001519
Chalard Jean46bfbf02022-02-02 00:56:25 +09001520 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001521 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001522 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001523 } catch (RemoteException | ServiceSpecificException e) {
1524 loge("Error registering event listener :" + e);
1525 }
1526
Erik Kline05f2b402015-04-30 12:58:40 +09001527 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1528 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001529
junyulai7e06ad42019-03-04 22:45:36 +08001530 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001531 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001532 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001533
1534 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001535 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001536 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1537 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001538 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001539 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1540 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001541
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001542 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001543 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001544 mNetworkRanker =
1545 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1546
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001547 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001548
Chiachang Wangc1215d32020-10-20 15:38:58 +08001549 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001550 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001551
Chalard Jean28018572020-12-21 18:36:52 +09001552 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1553 // request that doesn't allow fallback to the default network. It should never be visible
1554 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1555 // arguments like the handler or the DnsResolver.
1556 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001557 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001558 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001559 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001560 new LinkProperties(), new NetworkCapabilities(),
1561 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001562 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1563 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001564
1565 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001566 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1567 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1568 // Even if it could, running on S would at least require mocking out the BPF map,
1569 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1570 // the bpf syscall. http://aosp/1907693
1571 if (SdkLevel.isAtLeastT()) {
1572 mDscpPolicyTracker = new DscpPolicyTracker();
1573 }
Tyler Wear72388212021-09-09 14:49:02 -07001574 } catch (ErrnoException e) {
1575 loge("Unable to create DscpPolicyTracker");
1576 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001577
1578 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1579 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001580 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001581
Xiao Ma0a171c02022-01-23 16:14:51 +00001582 /**
1583 * Check whether or not the device supports Ethernet transport.
1584 */
1585 public static boolean deviceSupportsEthernet(final Context context) {
1586 final PackageManager pm = context.getPackageManager();
1587 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1588 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1589 }
1590
Chalard Jean46adcf32018-04-18 20:18:38 +09001591 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001592 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1593 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001594 }
1595
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001596 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1597 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001598 final NetworkCapabilities netCap = new NetworkCapabilities();
1599 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001600 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001601 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001602 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001603 return netCap;
1604 }
1605
James Mattis45d81842021-01-10 14:24:24 -08001606 private NetworkRequest createDefaultRequest() {
1607 return createDefaultInternetRequestForTransport(
1608 TYPE_NONE, NetworkRequest.Type.REQUEST);
1609 }
1610
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001611 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001612 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001613 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001614 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001615 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001616 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001617 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001618 netCap.addTransportType(transportType);
1619 }
James Mattis45d81842021-01-10 14:24:24 -08001620 return createNetworkRequest(type, netCap);
1621 }
1622
1623 private NetworkRequest createNetworkRequest(
1624 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001625 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001626 }
1627
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001628 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1629 NetworkRequest.Type type) {
1630 final NetworkCapabilities netCap = new NetworkCapabilities();
1631 netCap.clearAll();
1632 netCap.addCapability(capability);
1633 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1634 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1635 }
1636
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001637 // Used only for testing.
1638 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001639 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001640 // changing ContentResolver to make registerContentObserver non-final).
1641 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1642 // by subclassing SettingsObserver.
1643 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001644 void updateAlwaysOnNetworks() {
1645 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001646 }
1647
Erik Kline9a62f012018-03-21 07:18:33 -07001648 // See FakeSettingsProvider comment above.
1649 @VisibleForTesting
1650 void updatePrivateDnsSettings() {
1651 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1652 }
1653
paulhu51f77dc2021-06-07 02:34:20 +00001654 @VisibleForTesting
1655 void updateMobileDataPreferredUids() {
1656 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1657 }
1658
Patrick Rohr2857ac42022-01-21 14:58:16 +01001659 @VisibleForTesting
1660 void updateIngressRateLimit() {
1661 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1662 }
1663
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001664 private void handleAlwaysOnNetworkRequest(
1665 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001666 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001667 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001668 handleAlwaysOnNetworkRequest(networkRequest, enable);
1669 }
1670
1671 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001672 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001673 if (enable == isEnabled) {
1674 return; // Nothing to do.
1675 }
1676
1677 if (enable) {
1678 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001679 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001680 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001681 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001682 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001683 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1684 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001685 }
1686 }
1687
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001688 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001689 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1690 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1691 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1692 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001693 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1694 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001695 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001696 }
1697
paulhu51f77dc2021-06-07 02:34:20 +00001698 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001699 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001700 private void registerSettingsCallbacks() {
1701 // Watch for global HTTP proxy changes.
1702 mSettingsObserver.observe(
1703 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1704 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1705
Chalard Jean46bfbf02022-02-02 00:56:25 +09001706 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001707 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001708 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001709 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1710
Chalard Jean46bfbf02022-02-02 00:56:25 +09001711 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001712 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001713 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001714 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001715
1716 // Watch for mobile data preferred uids changes.
1717 mSettingsObserver.observe(
1718 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1719 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001720
1721 // Watch for ingress rate limit changes.
1722 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001723 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001724 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1725 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001726 }
1727
Erik Kline31b4a9e2018-01-11 21:07:29 +09001728 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001729 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1730 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001731 }
1732 }
1733
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001734 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001735 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1736 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001737 return mNextNetworkRequestId++;
1738 }
1739
junyulai74f9a8b2018-06-13 15:00:37 +08001740 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001741 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001742 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001743 if (network == null) {
1744 return null;
1745 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001746 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001747 }
1748
1749 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001750 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001751 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001752 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001753 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001754
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001755 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001756 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001757 private NetworkAgentInfo getVpnForUid(int uid) {
1758 synchronized (mNetworkForNetId) {
1759 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1760 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001761 if (nai.isVPN() && nai.everConnected()
1762 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001763 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001764 }
1765 }
1766 }
1767 return null;
1768 }
1769
Chalard Jean46bfbf02022-02-02 00:56:25 +09001770 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001771 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001772 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001773 final NetworkAgentInfo nai = getVpnForUid(uid);
1774 if (nai != null) return nai.declaredUnderlyingNetworks;
1775 return null;
1776 }
1777
Lorenzo Colittia7574052021-01-19 01:33:05 +09001778 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001779 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001780
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001781 final Network[] networks = getVpnUnderlyingNetworks(uid);
1782 if (networks != null) {
1783 // getUnderlyingNetworks() returns:
1784 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1785 // empty array => the VPN explicitly said "no default network".
1786 // non-empty array => the VPN specified one or more default networks; we use the
1787 // first one.
1788 if (networks.length > 0) {
1789 nai = getNetworkAgentInfoForNetwork(networks[0]);
1790 } else {
1791 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001792 }
1793 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001794 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001795 }
1796
1797 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001798 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001799 */
paulhu7aeba372020-12-30 00:42:19 +08001800 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1801 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001802 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001803 if (ignoreBlocked) {
1804 return false;
1805 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001806 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001807 final long ident = Binder.clearCallingIdentity();
1808 try {
1809 final boolean metered = nc == null ? true : nc.isMetered();
1810 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1811 } finally {
1812 Binder.restoreCallingIdentity(ident);
1813 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001814 }
1815
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001816 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001817 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1818 return;
1819 }
Hugo Benichi47011212017-03-30 10:46:05 +09001820 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001821 synchronized (mBlockedAppUids) {
1822 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001823 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001824 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001825 blocked = false;
1826 } else {
1827 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001828 }
1829 }
Hugo Benichi47011212017-03-30 10:46:05 +09001830 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1831 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1832 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001833 }
1834
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001835 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001836 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1837 return;
1838 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001839 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001840 final int requestId = nri.getActiveRequest() != null
1841 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001842 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001843 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001844 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001845 }
1846
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001847 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001848 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001849 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001850 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001851 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001852 @NonNull
1853 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1854 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001855 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1856 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1857 // but only exists if an app asks about them or requests them. Ensure the requesting app
1858 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001859 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001860 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1861 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1862 null /* extraInfo */);
1863 }
1864 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001865 return filtered;
1866 }
1867
1868 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1869 boolean ignoreBlocked) {
1870 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1871 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001872 }
1873
1874 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001875 * Return NetworkInfo for the active (i.e., connected) network interface.
1876 * It is assumed that at most one network is active at a time. If more
1877 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001878 * @return the info for the active network, or {@code null} if none is
1879 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001880 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001881 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001882 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001883 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001884 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001885 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001886 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1887 if (nai == null) return null;
1888 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1889 maybeLogBlockedNetworkInfo(networkInfo, uid);
1890 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001891 }
1892
Paul Jensen1f567382015-02-13 14:18:39 -05001893 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001894 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001895 public Network getActiveNetwork() {
1896 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001897 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001898 }
1899
1900 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001901 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001902 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001903 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001904 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001905 }
1906
Chalard Jean46bfbf02022-02-02 00:56:25 +09001907 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001908 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001909 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1910 if (vpnNai != null) {
1911 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1912 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1913 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001914 }
Paul Jensen1f567382015-02-13 14:18:39 -05001915 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001916
James Mattis2516da32021-01-31 17:06:19 -08001917 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001918 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1919 ignoreBlocked)) {
1920 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001921 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001922 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001923 }
1924
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001925 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001926 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001927 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001928 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001929 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1930 if (nai == null) return null;
1931 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001932 }
1933
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001934 /** Returns a NetworkInfo object for a network that doesn't exist. */
1935 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1936 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1937 getNetworkTypeName(networkType), "" /* subtypeName */);
1938 info.setIsAvailable(true);
1939 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1940 // background data is restricted.
1941 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1942 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1943 ? DetailedState.BLOCKED
1944 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001945 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1946 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001947 return info;
1948 }
1949
Lorenzo Colittia7574052021-01-19 01:33:05 +09001950 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001951 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1952 return null;
1953 }
1954 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001955 if (nai == null) {
1956 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001957 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001958 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1959 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001960 }
1961
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001962 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001963 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001964 public NetworkInfo getNetworkInfo(int networkType) {
1965 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001966 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001967 if (getVpnUnderlyingNetworks(uid) != null) {
1968 // A VPN is active, so we may need to return one of its underlying networks. This
1969 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001970 // getNetworkAgentInfoForUid.
1971 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1972 if (nai == null) return null;
1973 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1974 if (networkInfo.getType() == networkType) {
1975 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001976 }
1977 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001978 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001979 }
1980
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001981 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001982 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001983 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001984 enforceAccessPermission();
Junyu Lai163cb982022-09-16 10:40:48 +08001985 if (uid != mDeps.getCallingUid()) {
1986 enforceNetworkStackPermission(mContext);
1987 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001988 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001989 if (nai == null) return null;
1990 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001991 }
1992
1993 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001994 public NetworkInfo[] getAllNetworkInfo() {
1995 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001996 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001997 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1998 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001999 NetworkInfo info = getNetworkInfo(networkType);
2000 if (info != null) {
2001 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002002 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002003 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002004 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002005 }
2006
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002007 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002008 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002009 public Network getNetworkForType(int networkType) {
2010 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002011 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2012 return null;
2013 }
2014 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2015 if (nai == null) {
2016 return null;
2017 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002018 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002019 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2020 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002021 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002022 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002023 }
2024
2025 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002026 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002027 public Network[] getAllNetworks() {
2028 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002029 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002030 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002031 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002032 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002033 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002034 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002035 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002036 }
2037
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002038 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002039 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002040 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002041 // The basic principle is: if an app's traffic could possibly go over a
2042 // network, without the app doing anything multinetwork-specific,
2043 // (hence, by "default"), then include that network's capabilities in
2044 // the array.
2045 //
2046 // In the normal case, app traffic only goes over the system's default
2047 // network connection, so that's the only network returned.
2048 //
2049 // With a VPN in force, some app traffic may go into the VPN, and thus
2050 // over whatever underlying networks the VPN specifies, while other app
2051 // traffic may go over the system default network (e.g.: a split-tunnel
2052 // VPN, or an app disallowed by the VPN), so the set of networks
2053 // returned includes the VPN's underlying networks and the system
2054 // default.
2055 enforceAccessPermission();
2056
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002057 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002058
James Mattis2516da32021-01-31 17:06:19 -08002059 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2060 if (!nri.isBeingSatisfied()) {
2061 continue;
2062 }
2063 final NetworkAgentInfo nai = nri.getSatisfier();
2064 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2065 if (null != nc
2066 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2067 && !result.containsKey(nai.network)) {
2068 result.put(
2069 nai.network,
2070 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002071 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002072 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2073 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002074 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002075 }
2076
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002077 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002078 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002079 if (null != networks) {
2080 for (final Network network : networks) {
2081 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2082 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002083 result.put(
2084 network,
2085 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002086 nc,
2087 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002088 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002089 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002090 }
2091 }
2092 }
2093
2094 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2095 out = result.values().toArray(out);
2096 return out;
2097 }
2098
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002099 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002100 public boolean isNetworkSupported(int networkType) {
2101 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002102 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002103 }
2104
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002105 /**
2106 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002107 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002108 * @return the ip properties for the active network, or {@code null} if
2109 * none is active
2110 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002111 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002112 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002113 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002114 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002115 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2116 if (nai == null) return null;
2117 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002118 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002119 }
2120
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002121 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002122 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002123 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002124 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002125 final LinkProperties lp = getLinkProperties(nai);
2126 if (lp == null) return null;
2127 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002128 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002129 }
2130
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002131 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002132 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002133 public LinkProperties getLinkProperties(Network network) {
2134 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002135 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2136 if (lp == null) return null;
2137 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002138 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002139 }
2140
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002141 @Nullable
2142 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002143 if (nai == null) {
2144 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002145 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002146 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002147 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002148 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002149 }
2150
lucaslinc582d502022-01-27 09:07:00 +08002151 @Override
2152 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002153 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002154 @NonNull String packageName, @Nullable String callingAttributionTag) {
2155 Objects.requireNonNull(packageName);
2156 Objects.requireNonNull(lp);
2157 enforceNetworkStackOrSettingsPermission();
2158 if (!checkAccessPermission(-1 /* pid */, uid)) {
2159 return null;
2160 }
2161 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2162 }
2163
Qingxi Lib2748102020-01-08 12:51:49 -08002164 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2165 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2166 }
2167
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002168 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002169 if (nai == null) return null;
2170 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002171 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002172 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002173 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002174 }
2175
2176 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002177 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2178 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002179 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002180 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002181 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002182 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002183 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002184 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002185 }
2186
lucaslinc582d502022-01-27 09:07:00 +08002187 @Override
lucaslind2b06132022-03-02 10:56:57 +08002188 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2189 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2190 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002191 Objects.requireNonNull(nc);
2192 Objects.requireNonNull(packageName);
2193 enforceNetworkStackOrSettingsPermission();
2194 if (!checkAccessPermission(-1 /* pid */, uid)) {
2195 return null;
2196 }
2197 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2198 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2199 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2200 callingAttributionTag);
2201 }
2202
lucaslin69e1aa92022-03-22 18:15:09 +08002203 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2204 if (nc.getUnderlyingNetworks() != null
2205 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2206 nc.setUnderlyingNetworks(null);
2207 }
2208 }
2209
Qingxi Libb8da982020-01-17 17:54:27 -08002210 @VisibleForTesting
2211 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002212 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002213 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2214 // this would be expensive (one more permission check every time any NC callback is
2215 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2216 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2217 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002218 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002219 if (!checkSettingsPermission(callerPid, callerUid)) {
2220 newNc.setUids(null);
2221 newNc.setSSID(null);
2222 }
Etan Cohen107ae952018-12-30 17:59:59 -08002223 if (newNc.getNetworkSpecifier() != null) {
2224 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2225 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002226 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2227 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2228 newNc.setAdministratorUids(new int[0]);
2229 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002230 if (!checkAnyPermissionOf(
2231 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002232 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002233 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002234 }
lucaslin69e1aa92022-03-22 18:15:09 +08002235 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002236
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002237 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002238 }
2239
Roshan Pius98f59ec2021-02-23 08:47:39 -08002240 /**
2241 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002242 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002243 * NetworkCapabilities.
2244 * Note: This wrapper does not support any sort of invalidation and thus must not be
2245 * persistent or long-lived. It may only be used for the time necessary to
2246 * compute the redactions required by one particular NetworkCallback or
2247 * synchronous call.
2248 */
2249 private class RedactionPermissionChecker {
2250 private final int mCallingPid;
2251 private final int mCallingUid;
2252 @NonNull private final String mCallingPackageName;
2253 @Nullable private final String mCallingAttributionTag;
2254
2255 private Boolean mHasLocationPermission = null;
2256 private Boolean mHasLocalMacAddressPermission = null;
2257 private Boolean mHasSettingsPermission = null;
2258
2259 RedactionPermissionChecker(int callingPid, int callingUid,
2260 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2261 mCallingPid = callingPid;
2262 mCallingUid = callingUid;
2263 mCallingPackageName = callingPackageName;
2264 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002265 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002266
2267 private boolean hasLocationPermissionInternal() {
2268 final long token = Binder.clearCallingIdentity();
2269 try {
2270 return mLocationPermissionChecker.checkLocationPermission(
2271 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2272 null /* message */);
2273 } finally {
2274 Binder.restoreCallingIdentity(token);
2275 }
2276 }
2277
2278 /**
2279 * Returns whether the app holds location permission or not (might return cached result
2280 * if the permission was already checked before).
2281 */
2282 public boolean hasLocationPermission() {
2283 if (mHasLocationPermission == null) {
2284 // If there is no cached result, perform the check now.
2285 mHasLocationPermission = hasLocationPermissionInternal();
2286 }
2287 return mHasLocationPermission;
2288 }
2289
2290 /**
2291 * Returns whether the app holds local mac address permission or not (might return cached
2292 * result if the permission was already checked before).
2293 */
2294 public boolean hasLocalMacAddressPermission() {
2295 if (mHasLocalMacAddressPermission == null) {
2296 // If there is no cached result, perform the check now.
2297 mHasLocalMacAddressPermission =
2298 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2299 }
2300 return mHasLocalMacAddressPermission;
2301 }
2302
2303 /**
2304 * Returns whether the app holds settings permission or not (might return cached
2305 * result if the permission was already checked before).
2306 */
2307 public boolean hasSettingsPermission() {
2308 if (mHasSettingsPermission == null) {
2309 // If there is no cached result, perform the check now.
2310 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2311 }
2312 return mHasSettingsPermission;
2313 }
2314 }
2315
2316 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2317 @NetworkCapabilities.NetCapability long redaction) {
2318 return (redactions & redaction) != 0;
2319 }
2320
2321 /**
2322 * Use the provided |applicableRedactions| to check the receiving app's
2323 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2324 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2325 * before being sent to the corresponding app.
2326 */
2327 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2328 @NetworkCapabilities.RedactionType long applicableRedactions,
2329 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2330 boolean includeLocationSensitiveInfo) {
2331 long redactions = applicableRedactions;
2332 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2333 if (includeLocationSensitiveInfo
2334 && redactionPermissionChecker.hasLocationPermission()) {
2335 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2336 }
2337 }
2338 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2339 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2340 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2341 }
2342 }
2343 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2344 if (redactionPermissionChecker.hasSettingsPermission()) {
2345 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2346 }
2347 }
2348 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002349 }
2350
Qingxi Lib2748102020-01-08 12:51:49 -08002351 @VisibleForTesting
2352 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002353 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002354 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002355 int callingPid, int callingUid, @NonNull String callingPkgName,
2356 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002357 if (nc == null) {
2358 return null;
2359 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002360 // Avoid doing location permission check if the transport info has no location sensitive
2361 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002362 final RedactionPermissionChecker redactionPermissionChecker =
2363 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2364 callingAttributionTag);
2365 final long redactions = retrieveRequiredRedactions(
2366 nc.getApplicableRedactions(), redactionPermissionChecker,
2367 includeLocationSensitiveInfo);
2368 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002369 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002370 // TODO : calling UID is redacted because apps should generally not know what UID is
2371 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002372 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002373 newNc.setOwnerUid(INVALID_UID);
2374 return newNc;
2375 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002376 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2377 if (nc.hasTransport(TRANSPORT_VPN)) {
2378 // Owner UIDs already checked above. No need to re-check.
2379 return newNc;
2380 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002381 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2382 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002383 // compatibility for older apps.
2384 if (!includeLocationSensitiveInfo
2385 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002386 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002387 newNc.setOwnerUid(INVALID_UID);
2388 return newNc;
2389 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002390 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002391 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002392 newNc.setOwnerUid(INVALID_UID);
2393 }
Qingxi Lib2748102020-01-08 12:51:49 -08002394 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002395 }
2396
lucaslinc582d502022-01-27 09:07:00 +08002397 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002398 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2399 LinkProperties lp, int callerPid, int callerUid) {
2400 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002401 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2402 // this would be expensive (one more permission check every time any LP callback is
2403 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2404 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2405 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002406
2407 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2408 final boolean needsSanitization =
2409 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2410 if (!needsSanitization) {
2411 return new LinkProperties(lp);
2412 }
2413
2414 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002415 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002416 }
2417
2418 final LinkProperties newLp = new LinkProperties(lp);
2419 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2420 // object gets parceled.
2421 newLp.setCaptivePortalApiUrl(null);
2422 newLp.setCaptivePortalData(null);
2423 return newLp;
2424 }
2425
Roshan Pius08c94fb2020-01-16 12:17:17 -08002426 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2427 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002428 // There is no need to track the effective UID of the request here. If the caller
2429 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002430 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002431 // Unprivileged apps can only pass in null or their own UID.
2432 if (nc.getUids() == null) {
2433 // If the caller passes in null, the callback will also match networks that do not
2434 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2435 // In this case, redact everything in the request immediately. This ensures that the
2436 // app is not able to get any redacted information by filing an unredacted request
2437 // and observing whether the request matches something.
2438 if (nc.getNetworkSpecifier() != null) {
2439 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2440 }
2441 } else {
2442 nc.setSingleUid(callerUid);
2443 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002444 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002445 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002446 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002447
2448 // Clear owner UID; this can never come from an app.
2449 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002450 }
2451
Chalard Jean38354d12018-03-20 19:13:57 +09002452 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002453 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002454 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2455 }
2456 }
2457
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002458 @Override
2459 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2460 enforceAccessPermission();
2461 final int callerUid = Binder.getCallingUid();
2462 final long token = Binder.clearCallingIdentity();
2463 try {
2464 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2465 } finally {
2466 Binder.restoreCallingIdentity(token);
2467 }
2468 }
2469
junyulaiebd15162021-03-03 12:09:05 +08002470 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002471 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002472 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002473 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002474 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002475
Serik Beketayev05130302021-01-15 16:47:25 -08002476 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002477 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002478 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2479 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002480 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002481 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002482 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002483 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2484 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002485 }
2486 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002487 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002488 }
2489
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002490 @Override
junyulaiebd15162021-03-03 12:09:05 +08002491 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002492 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002493 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002494 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002495
2496 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2497 for (Network network : getAllNetworks()) {
2498 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002499 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002500 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2501 // NetworkCapabilities, which may contain UIDs of apps to which the
2502 // network applies. Should the UIDs be cleared so as not to leak or
2503 // interfere ?
2504 result.add(nai.getNetworkStateSnapshot());
2505 }
2506 }
2507 return result;
2508 }
2509
2510 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002511 public boolean isActiveNetworkMetered() {
2512 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002513
Qingxi Lib2748102020-01-08 12:51:49 -08002514 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002515 if (caps != null) {
2516 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2517 } else {
2518 // Always return the most conservative value
2519 return true;
2520 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002521 }
2522
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002523 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002524 * Ensures that the system cannot call a particular method.
2525 */
2526 private boolean disallowedBecauseSystemCaller() {
2527 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002528 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2529 // for devices launched with Q and above. However, existing devices upgrading to Q and
2530 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002531 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002532 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002533 log("This method exists only for app backwards compatibility"
2534 + " and must not be called by system services.");
2535 return true;
2536 }
2537 return false;
2538 }
2539
paulhub2c28682021-08-18 18:35:54 +08002540 private int getAppUid(final String app, final UserHandle user) {
2541 final PackageManager pm =
2542 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2543 final long token = Binder.clearCallingIdentity();
2544 try {
2545 return pm.getPackageUid(app, 0 /* flags */);
2546 } catch (PackageManager.NameNotFoundException e) {
2547 return -1;
2548 } finally {
2549 Binder.restoreCallingIdentity(token);
2550 }
2551 }
2552
2553 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2554 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2555 if (getAppUid(packageName, user) != callingUid) {
2556 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2557 }
2558 }
2559
Lorenzo Colitti23862912018-09-28 11:31:55 +09002560 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002561 * Ensure that a network route exists to deliver traffic to the specified
2562 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002563 * @param networkType the type of the network over which traffic to the
2564 * specified host is to be routed
2565 * @param hostAddress the IP address of the host to which the route is
2566 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002567 * @return {@code true} on success, {@code false} on failure
2568 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002569 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002570 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2571 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002572 if (disallowedBecauseSystemCaller()) {
2573 return false;
2574 }
paulhub2c28682021-08-18 18:35:54 +08002575 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002576 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002577 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002578 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002579 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002580
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002581 InetAddress addr;
2582 try {
2583 addr = InetAddress.getByAddress(hostAddress);
2584 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002585 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002586 return false;
2587 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002588
The Android Open Source Project28527d22009-03-03 19:31:44 -08002589 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002590 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002591 return false;
2592 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002593
2594 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2595 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002596 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002597 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2598 } else {
2599 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2600 }
2601 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002602 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002603
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002604 DetailedState netState;
2605 synchronized (nai) {
2606 netState = nai.networkInfo.getDetailedState();
2607 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002608
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002609 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002610 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002611 log("requestRouteToHostAddress on down network "
2612 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002613 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002614 }
2615 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002616 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002617
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002618 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002619 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002620 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002621 LinkProperties lp;
2622 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002623 synchronized (nai) {
2624 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002625 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002626 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002627 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002628 if (DBG) {
2629 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2630 }
Wink Saville32506bc2013-06-29 21:10:57 -07002631 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002632 } finally {
2633 Binder.restoreCallingIdentity(token);
2634 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002635 }
2636
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002637 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002638 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002639 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002640 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002641 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002642 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002643 if (bestRoute.getGateway().equals(addr)) {
2644 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002645 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002646 } else {
2647 // if we will connect to this through another route, add a direct route
2648 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002649 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002650 }
2651 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002652 if (DBG) log("Adding legacy route " + bestRoute +
2653 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002654
2655 final String dst = bestRoute.getDestinationLinkAddress().toString();
2656 final String nextHop = bestRoute.hasGateway()
2657 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002658 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002659 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2660 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002661 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002662 return false;
2663 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002664 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002665 }
2666
paulhu7c0a2e62021-01-08 00:51:49 +08002667 class DnsResolverUnsolicitedEventCallback extends
2668 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002669 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002670 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002671 try {
2672 mHandler.sendMessage(mHandler.obtainMessage(
2673 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002674 new PrivateDnsValidationUpdate(event.netId,
2675 InetAddresses.parseNumericAddress(event.ipAddress),
2676 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002677 } catch (IllegalArgumentException e) {
2678 loge("Error parsing ip address in validation event");
2679 }
2680 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002681
2682 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002683 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2684 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002685 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2686 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2687 // event callback for certain nai. e.g. cellular. Register here to pass to
2688 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002689 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002690 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2691 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002692 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002693 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002694 }
2695 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002696
2697 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002698 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2699 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2700 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002701 }
dalyk1720e542018-03-05 12:42:22 -05002702
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002703 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002704 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002705 return this.VERSION;
2706 }
2707
2708 @Override
2709 public String getInterfaceHash() {
2710 return this.HASH;
2711 }
paulhu7c0a2e62021-01-08 00:51:49 +08002712 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002713
2714 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002715 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2716 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002717
paulhu7c0a2e62021-01-08 00:51:49 +08002718 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002719 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002720 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002721 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002722 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002723 }
2724 }
2725
Sudheer Shanka9967d462021-03-18 19:09:25 +00002726 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002727 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002728 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2730 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002731 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002732 };
2733
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002734 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002735 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002736 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002737 }
2738
paulhu1a407652019-03-22 16:35:06 +08002739 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2740 for (String permission : permissions) {
2741 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2742 return true;
2743 }
2744 }
2745 return false;
2746 }
2747
Paul Jensen83f5d572014-08-29 09:54:01 -04002748 private void enforceInternetPermission() {
2749 mContext.enforceCallingOrSelfPermission(
2750 android.Manifest.permission.INTERNET,
2751 "ConnectivityService");
2752 }
2753
The Android Open Source Project28527d22009-03-03 19:31:44 -08002754 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002755 mContext.enforceCallingOrSelfPermission(
2756 android.Manifest.permission.ACCESS_NETWORK_STATE,
2757 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002758 }
2759
lucaslinc582d502022-01-27 09:07:00 +08002760 private boolean checkAccessPermission(int pid, int uid) {
2761 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2762 == PERMISSION_GRANTED;
2763 }
2764
paulhua6ee2122021-02-22 15:40:43 +08002765 /**
2766 * Performs a strict and comprehensive check of whether a calling package is allowed to
2767 * change the state of network, as the condition differs for pre-M, M+, and
2768 * privileged/preinstalled apps. The caller is expected to have either the
2769 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2770 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2771 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2772 * permission and cannot be revoked. See http://b/23597341
2773 *
2774 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2775 * of this app will be updated to the current time.
2776 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002777 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002778 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2779 == PackageManager.PERMISSION_GRANTED) {
2780 return;
2781 }
2782
2783 if (callingPkg == null) {
2784 throw new SecurityException("Calling package name is null.");
2785 }
2786
2787 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2788 final int uid = mDeps.getCallingUid();
2789 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2790 callingPkg, callingAttributionTag, null /* message */);
2791
2792 if (mode == AppOpsManager.MODE_ALLOWED) {
2793 return;
2794 }
2795
2796 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2797 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2798 return;
2799 }
2800
2801 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2802 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2803 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002804 }
2805
Charles He9369e612017-05-15 17:07:18 +01002806 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002807 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002808 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002809 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002810 }
2811
paulhu8e96a752019-08-12 16:25:11 +08002812 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002813 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002814 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002815 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002816 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002817 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002818 }
2819
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002820 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002821 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002822 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002823 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002824 android.Manifest.permission.NETWORK_SETTINGS,
2825 android.Manifest.permission.NETWORK_FACTORY,
2826 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2827 }
2828
2829 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002830 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002831 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002832 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002833 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2834 android.Manifest.permission.NETWORK_FACTORY,
2835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2836 }
2837
lucaslin69e1aa92022-03-22 18:15:09 +08002838 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2839 return PERMISSION_GRANTED == mContext.checkPermission(
2840 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2841 || PERMISSION_GRANTED == mContext.checkPermission(
2842 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2843 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002844 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002845 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002846 }
2847
Chalard Jean9a396cc2018-02-21 18:43:54 +09002848 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002849 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002850 android.Manifest.permission.NETWORK_SETTINGS,
2851 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002852 }
2853
2854 private boolean checkSettingsPermission(int pid, int uid) {
2855 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002856 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2857 || PERMISSION_GRANTED == mContext.checkPermission(
2858 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002859 }
2860
paulhu8e96a752019-08-12 16:25:11 +08002861 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002862 enforceNetworkStackPermissionOr(mContext,
2863 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002864 }
2865
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002866 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002867 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002868 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002869 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002870 }
2871
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002872 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002873 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002874 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2875 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002876 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002877 }
2878
James Mattis8378aec2021-01-26 14:05:36 -08002879 private void enforceOemNetworkPreferencesPermission() {
2880 mContext.enforceCallingOrSelfPermission(
2881 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2882 "ConnectivityService");
2883 }
2884
James Mattisfa270db2021-05-31 17:11:10 -07002885 private void enforceManageTestNetworksPermission() {
2886 mContext.enforceCallingOrSelfPermission(
2887 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2888 "ConnectivityService");
2889 }
2890
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002891 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002892 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002893 android.Manifest.permission.NETWORK_STACK,
2894 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002895 }
2896
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002897 private boolean checkNetworkStackPermission(int pid, int uid) {
2898 return checkAnyPermissionOf(pid, uid,
2899 android.Manifest.permission.NETWORK_STACK,
2900 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2901 }
2902
paulhu1a407652019-03-22 16:35:06 +08002903 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2904 return checkAnyPermissionOf(pid, uid,
2905 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002906 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2907 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002908 }
2909
Paul Hu8fc2a552022-05-04 18:44:42 +08002910 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2911 boolean checkUidsAllowedList) {
2912 if (PermissionUtils.checkAnyPermissionOf(mContext,
2913 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2914 return true;
2915 }
2916
2917 // fallback to ConnectivityInternalPermission
2918 // TODO: Remove this fallback check after all apps have declared
2919 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2920 if (PermissionUtils.checkAnyPermissionOf(mContext,
2921 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2922 return true;
2923 }
2924
2925 // Check whether uid is in allowed on restricted networks list.
2926 if (checkUidsAllowedList
2927 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2928 return true;
2929 }
2930 return false;
2931 }
2932
2933 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2934 final int callingUid = mDeps.getCallingUid();
2935 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2936 throw new SecurityException("ConnectivityService: user " + callingUid
2937 + " has no permission to access restricted network.");
2938 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002939 }
2940
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002941 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002942 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002943 }
2944
Roshan Pius98f59ec2021-02-23 08:47:39 -08002945 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2946 return PERMISSION_GRANTED == mContext.checkPermission(
2947 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2948 }
2949
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002950 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002951 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002952 }
2953
2954 private void sendInetConditionBroadcast(NetworkInfo info) {
2955 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2956 }
2957
Wink Saville4f0de1e2011-08-04 15:01:58 -07002958 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002959 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002960 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002961 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002962 if (info.isFailover()) {
2963 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2964 info.setFailover(false);
2965 }
2966 if (info.getReason() != null) {
2967 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2968 }
2969 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002970 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2971 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002972 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002973 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002974 return intent;
2975 }
2976
2977 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2978 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2979 }
2980
Chiachang Wang3bc52762021-11-25 14:17:57 +08002981 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2982 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002983 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002984 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002985 if (!mSystemReady
2986 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002987 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002988 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002989 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002990 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002991 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002992 }
2993
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002994 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002995 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002996 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002997 final NetworkInfo ni = intent.getParcelableExtra(
2998 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002999 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3000 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
3001 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003002 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003003 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003004 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003005 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003009 }
3010 }
3011
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003012 /**
Aaron Huang96011892020-06-27 07:18:23 +08003013 * Called by SystemServer through ConnectivityManager when the system is ready.
3014 */
3015 @Override
3016 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003017 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003018 throw new SecurityException("Calling Uid is not system uid.");
3019 }
3020 systemReadyInternal();
3021 }
3022
3023 /**
3024 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003025 */
3026 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003027 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003028 // Load flags after PackageManager is ready to query module version
3029 mFlags.loadFlags(mDeps, mContext);
3030
Aaron Huang9a57acf2020-12-08 10:03:29 +08003031 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3032 // listening network request which is sent by MultipathPolicyTracker won't be added
3033 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3034 // be called after PermissionMonitor#startMonitoring().
3035 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3036 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3037 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003038 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003039 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003040 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003041
Hugo Benichie5220992017-04-26 14:53:28 +09003042 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003043 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003044 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003045 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003046 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003047 }
3048 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003049
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003050 // Create network requests for always-on networks.
3051 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003052
3053 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003054 // Note that updating can be skipped here if the list is empty only because no uid
3055 // rules are applied before system ready. Normally, the empty uid list means to clear
3056 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003057 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3058 updateMobileDataPreferredUids();
3059 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003060
3061 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3062 if (SdkLevel.isAtLeastT()) {
3063 mBpfNetMaps.setPullAtomCallback(mContext);
3064 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003065 }
3066
The Android Open Source Project28527d22009-03-03 19:31:44 -08003067 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003068 * Start listening for default data network activity state changes.
3069 */
3070 @Override
3071 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003072 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003073 }
3074
3075 /**
3076 * Stop listening for default data network activity state changes.
3077 */
3078 @Override
3079 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003080 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003081 }
3082
3083 /**
3084 * Check whether the default network radio is currently active.
3085 */
3086 @Override
3087 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003088 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003089 }
3090
3091 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003092 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003093 * and set it on it's iface.
3094 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003095 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3096 final String iface = newLp.getInterfaceName();
3097 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003098 if (oldLp == null && mtu == 0) {
3099 // Silently ignore unset MTU value.
3100 return;
3101 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003102 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3103 if (VDBG) log("identical MTU - not setting");
3104 return;
3105 }
paulhucbbc3db2019-03-08 16:35:20 +08003106 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003107 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003108 return;
3109 }
sy.yun4aa73922013-09-02 05:24:09 +09003110
w19976e714f1d2014-08-05 15:18:11 -07003111 // Cannot set MTU without interface name
3112 if (TextUtils.isEmpty(iface)) {
3113 loge("Setting MTU size with null iface.");
3114 return;
3115 }
3116
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003117 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003118 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003119 mNetd.interfaceSetMtu(iface, mtu);
3120 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003121 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003122 }
3123 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003124
Chenbo Feng15416292018-11-08 17:36:21 -08003125 @VisibleForTesting
3126 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003127
lucaslin821c9782018-11-28 19:27:52 +08003128 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003129 String[] values = null;
3130 if (tcpBufferSizes != null) {
3131 values = tcpBufferSizes.split(",");
3132 }
3133
3134 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003135 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003136 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3137 values = tcpBufferSizes.split(",");
3138 }
3139
3140 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3141
3142 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003143 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003144
Chenbo Feng15416292018-11-08 17:36:21 -08003145 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3146 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3147 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003148 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003149 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003150 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003151 }
3152 }
3153
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003154 @Override
3155 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003156 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003157 NETWORK_RESTORE_DELAY_PROP_NAME);
3158 if(restoreDefaultNetworkDelayStr != null &&
3159 restoreDefaultNetworkDelayStr.length() != 0) {
3160 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003161 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003162 } catch (NumberFormatException e) {
3163 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003164 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003165 // if the system property isn't set, use the value for the apn type
3166 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3167
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003168 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3169 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003170 }
3171 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003172 }
3173
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003174 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003175 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003176 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003177 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003178 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003179 // Start gathering diagnostic information.
3180 netDiags.add(new NetworkDiagnostics(
3181 nai.network,
3182 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003183 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003184 DIAG_TIME_MS));
3185 }
3186
3187 for (NetworkDiagnostics netDiag : netDiags) {
3188 pw.println();
3189 netDiag.waitForMeasurements();
3190 netDiag.dump(pw);
3191 }
3192 }
3193
The Android Open Source Project28527d22009-03-03 19:31:44 -08003194 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003195 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3196 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003197 if (!checkDumpPermission(mContext, TAG, writer)) return;
3198
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003199 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003200 }
3201
lucaslin99473f62020-12-10 15:10:54 +08003202 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3203 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3204 != PackageManager.PERMISSION_GRANTED) {
3205 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003206 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003207 + " due to missing android.permission.DUMP permission");
3208 return false;
3209 } else {
3210 return true;
3211 }
3212 }
3213
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003214 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003215 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003216
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003217 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003218 dumpNetworkDiagnostics(pw);
3219 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003220 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003221 dumpNetworks(pw);
3222 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003223 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003224 dumpNetworkRequests(pw);
3225 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003226 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3227 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3228 dumpTrafficController(pw, fd, verbose);
3229 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003230 }
Erik Kline9647f382015-06-05 17:47:34 +09003231
Junyu Lai0da479b2022-04-20 15:06:29 +08003232 pw.println("NetworkProviders for:");
3233 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003234 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003235 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003236 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003237 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003238 pw.println();
3239
Chalard Jean5b409c72021-02-04 13:12:59 +09003240 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003241 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003242 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003243 pw.println("none");
3244 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003245 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003246 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003247 pw.println();
3248
James Mattis8b298a02021-06-01 22:34:04 -07003249 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003250 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003251 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003252 pw.decreaseIndent();
3253 pw.println();
3254
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003255 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003256 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003257 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003258 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003259 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003260
junyulaif2c67e42018-08-07 19:50:45 +08003261 pw.println("Status for known UIDs:");
3262 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003263 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003264 for (int i = 0; i < size; i++) {
3265 // Don't crash if the array is modified while dumping in bugreports.
3266 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003267 final int uid = mUidBlockedReasons.keyAt(i);
3268 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3269 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003270 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003271 } catch (ArrayIndexOutOfBoundsException e) {
3272 pw.println(" ArrayIndexOutOfBoundsException");
3273 } catch (ConcurrentModificationException e) {
3274 pw.println(" ConcurrentModificationException");
3275 }
3276 }
3277 pw.println();
3278 pw.decreaseIndent();
3279
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003280 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003281 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003282 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003283 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003284 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003285
Junyu Lai0da479b2022-04-20 15:06:29 +08003286 pw.println("Network Offers:");
3287 pw.increaseIndent();
3288 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3289 pw.println(offerInfo.offer);
3290 }
3291 pw.decreaseIndent();
3292 pw.println();
3293
Robert Greenwalt94e22142014-07-30 16:31:24 -07003294 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003295
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003296 pw.println();
markchien5e866652019-09-30 14:40:57 +08003297 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003298
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003299 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003300 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003301
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003302 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003303
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003304 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003305 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003306 pw.println("mNetworkRequestInfoLogs (most recent first):");
3307 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003308 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003309 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003310
3311 pw.println();
3312 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3313 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003314 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003315 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003316
3317 pw.println();
3318 pw.println("NetTransition WakeLock activity (most recent first):");
3319 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003320 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3321 pw.println("total releases: " + mTotalWakelockReleases);
3322 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3323 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3324 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3325 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3326 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3327 }
James Mattiscb1e0362021-04-06 17:07:42 -07003328 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003329
3330 pw.println();
3331 pw.println("bandwidth update requests (by uid):");
3332 pw.increaseIndent();
3333 synchronized (mBandwidthRequests) {
3334 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3335 pw.println("[" + mBandwidthRequests.keyAt(i)
3336 + "]: " + mBandwidthRequests.valueAt(i));
3337 }
3338 }
3339 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003340 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003341
James Mattiscb1e0362021-04-06 17:07:42 -07003342 pw.println();
3343 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3344 pw.increaseIndent();
3345 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003346 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003347 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003348
3349 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003350
3351 pw.println();
3352 pw.println("Permission Monitor:");
3353 pw.increaseIndent();
3354 mPermissionMonitor.dump(pw);
3355 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003356
3357 pw.println();
3358 pw.println("Legacy network activity:");
3359 pw.increaseIndent();
3360 mNetworkActivityTracker.dump(pw);
3361 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003362 }
3363
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003364 private void dumpNetworks(IndentingPrintWriter pw) {
3365 for (NetworkAgentInfo nai : networksSortedById()) {
3366 pw.println(nai.toString());
3367 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003368 pw.println("Nat464Xlat:");
3369 pw.increaseIndent();
3370 nai.dumpNat464Xlat(pw);
3371 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003372 pw.println(String.format(
3373 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3374 nai.numForegroundNetworkRequests(),
3375 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3376 nai.numBackgroundNetworkRequests(),
3377 nai.numNetworkRequests()));
3378 pw.increaseIndent();
3379 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3380 pw.println(nai.requestAt(i).toString());
3381 }
3382 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003383 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003384 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003385 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003386 pw.decreaseIndent();
3387 pw.decreaseIndent();
3388 }
3389 }
3390
James Mattis8b298a02021-06-01 22:34:04 -07003391 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3392 if (!mProfileNetworkPreferences.isEmpty()) {
3393 pw.println("Profile preferences:");
3394 pw.increaseIndent();
3395 pw.println(mProfileNetworkPreferences.preferences);
3396 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003397 }
James Mattis8b298a02021-06-01 22:34:04 -07003398 if (!mOemNetworkPreferences.isEmpty()) {
3399 pw.println("OEM preferences:");
3400 pw.increaseIndent();
3401 pw.println(mOemNetworkPreferences);
3402 pw.decreaseIndent();
3403 }
3404 if (!mMobileDataPreferredUids.isEmpty()) {
3405 pw.println("Mobile data preferred UIDs:");
3406 pw.increaseIndent();
3407 pw.println(mMobileDataPreferredUids);
3408 pw.decreaseIndent();
3409 }
James Mattis45d81842021-01-10 14:24:24 -08003410
James Mattis8b298a02021-06-01 22:34:04 -07003411 pw.println("Default requests:");
3412 pw.increaseIndent();
3413 dumpPerAppDefaultRequests(pw);
3414 pw.decreaseIndent();
3415 }
3416
3417 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003418 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3419 if (mDefaultRequest == defaultRequest) {
3420 continue;
3421 }
3422
James Mattis8b298a02021-06-01 22:34:04 -07003423 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3424 final String networkOutput;
3425 if (null == satisfier) {
3426 networkOutput = "null";
3427 } else if (mNoServiceNetwork.equals(satisfier)) {
3428 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003429 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003430 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003431 }
James Mattis8b298a02021-06-01 22:34:04 -07003432 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3433 ? "" : " asUid: " + defaultRequest.mAsUid;
3434 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3435 + defaultRequest.mPid + asUidString + "]";
3436 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3437 + " Preference order: " + defaultRequest.mPreferenceOrder
3438 + " Tracked UIDs: " + defaultRequest.getUids();
3439 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003440 }
3441 }
3442
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003443 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003444 NetworkRequestInfo[] infos = null;
3445 while (infos == null) {
3446 try {
3447 infos = requestsSortedById();
3448 } catch (ConcurrentModificationException e) {
3449 // mNetworkRequests should only be accessed from handler thread, except dump().
3450 // As dump() is never called in normal usage, it would be needlessly expensive
3451 // to lock the collection only for its benefit. Instead, retry getting the
3452 // requests if ConcurrentModificationException is thrown during dump().
3453 }
3454 }
3455 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003456 pw.println(nri.toString());
3457 }
3458 }
3459
Ken Chene6d511f2022-01-25 11:10:42 +08003460 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3461 boolean verbose) {
3462 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003463 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003464 } catch (ServiceSpecificException e) {
3465 pw.println(e.getMessage());
3466 } catch (IOException e) {
3467 loge("Dump BPF maps failed, " + e);
3468 }
3469 }
3470
Chalard Jean524f0b12021-10-25 21:11:56 +09003471 private void dumpAllRequestInfoLogsToLogcat() {
3472 try (PrintWriter logPw = new PrintWriter(new Writer() {
3473 @Override
3474 public void write(final char[] cbuf, final int off, final int len) {
3475 // This method is called with 0-length and 1-length arrays for empty strings
3476 // or strings containing only the DEL character.
3477 if (len <= 1) return;
3478 Log.e(TAG, new String(cbuf, off, len));
3479 }
3480 @Override public void flush() {}
3481 @Override public void close() {}
3482 })) {
3483 mNetworkRequestInfoLogs.dump(logPw);
3484 }
3485 }
3486
Hugo Benichia480ba52018-09-03 08:19:02 +09003487 /**
3488 * Return an array of all current NetworkAgentInfos sorted by network id.
3489 */
3490 private NetworkAgentInfo[] networksSortedById() {
3491 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003492 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003493 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003494 return networks;
3495 }
3496
3497 /**
3498 * Return an array of all current NetworkRequest sorted by request id.
3499 */
James Mattis258ea3c2020-11-15 15:04:40 -08003500 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003501 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003502 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003503 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003504 // Sort the array based off the NRI containing the min requestId in its requests.
3505 Arrays.sort(requests,
3506 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3507 Comparator.comparingInt(req -> req.requestId)).requestId
3508 )
3509 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003510 return requests;
3511 }
3512
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003513 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003514 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003515 if (officialNai != null && officialNai.equals(nai)) return true;
3516 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003517 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003518 " - " + nai);
3519 }
3520 return false;
3521 }
3522
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003523 private boolean isDisconnectRequest(Message msg) {
3524 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3525 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3526 return info.getState() == NetworkInfo.State.DISCONNECTED;
3527 }
3528
Robert Greenwalt2034b912009-08-12 16:08:25 -07003529 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003530 private class NetworkStateTrackerHandler extends Handler {
3531 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003532 super(looper);
3533 }
3534
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003535 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003536 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3537 final NetworkAgentInfo nai = arg.first;
3538 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003539 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003540 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003541 }
3542 return;
3543 }
3544
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003545 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003546 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003547 return;
3548 }
3549
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003550 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003551 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003552 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3553 final NetworkCapabilities sanitized =
3554 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003555 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003556 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003557 break;
3558 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003559 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003560 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003561 processLinkPropertiesFromAgent(nai, newLp);
3562 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003563 break;
3564 }
3565 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003566 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003567 updateNetworkInfo(nai, info);
3568 break;
3569 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003570 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003571 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003572 break;
3573 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003574 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003575 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003576 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003577 // Note that if the NAI had been connected, this would affect the
3578 // score, and therefore would require re-mixing the score and performing
3579 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003580 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003581 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3582 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003583 // Mark the network as temporarily accepting partial connectivity so that it
3584 // will be validated (and possibly become default) even if it only provides
3585 // partial internet access. Note that if user connects to partial connectivity
3586 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3587 // out of wifi coverage) and if the same wifi is available again, the device
3588 // will auto connect to this wifi even though the wifi has "no internet".
3589 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003590 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003591 break;
3592 }
junyulai011b1f12019-01-03 18:50:15 +08003593 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003594 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003595 break;
3596 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003597 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003598 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003599 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003600
3601 if (isLegacyLockdownNai(nai)
3602 && (underlying == null || underlying.size() != 1)) {
3603 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3604 + " must have exactly one underlying network: " + underlying);
3605 }
3606
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003607 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3608 nai.declaredUnderlyingNetworks = (underlying != null)
3609 ? underlying.toArray(new Network[0]) : null;
3610
3611 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3612 if (DBG) {
3613 log(nai.toShortString() + " changed underlying networks to "
3614 + Arrays.toString(nai.declaredUnderlyingNetworks));
3615 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003616 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003617 notifyIfacesChangedForNetworkStats();
3618 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003619 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003620 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003621 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3622 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3623 nai.teardownDelayMs = msg.arg1;
3624 } else {
3625 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3626 }
Chalard Jean550b5212021-03-05 23:07:53 +09003627 break;
3628 }
3629 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3630 nai.setLingerDuration((int) arg.second);
3631 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003632 }
Tyler Wear72388212021-09-09 14:49:02 -07003633 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3634 DscpPolicy policy = (DscpPolicy) arg.second;
3635 if (mDscpPolicyTracker != null) {
3636 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3637 }
3638 break;
3639 }
3640 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3641 if (mDscpPolicyTracker != null) {
3642 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3643 }
3644 break;
3645 }
3646 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3647 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003648 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003649 }
3650 break;
3651 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003652 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003653 // If nai is not yet created, or is already destroyed, ignore.
3654 if (!shouldDestroyNativeNetwork(nai)) break;
3655
3656 final int timeoutMs = (int) arg.second;
3657 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3658 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3659 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3660 }
3661
3662 // Marking a network awaiting replacement is used to ensure that any requests
3663 // satisfied by the network do not switch to another network until a
3664 // replacement is available or the wait for a replacement times out.
3665 // If the network is inactive (i.e., nascent or lingering), then there are no
3666 // such requests, and there is no point keeping it. Just tear it down.
3667 // Note that setLingerDuration(0) cannot be used to do this because the network
3668 // could be nascent.
3669 nai.clearInactivityState();
3670 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3671 Log.d(TAG, nai.toShortString()
3672 + " marked awaiting replacement is unneeded, tearing down instead");
3673 teardownUnneededNetwork(nai);
3674 break;
3675 }
3676
3677 Log.d(TAG, "Marking " + nai.toShortString()
3678 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3679 destroyNativeNetwork(nai);
3680
3681 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3682 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3683 // consider the fact that the network could already have disconnected or been
3684 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3685 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3686 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3687 mKeepaliveTracker.handleStopAllKeepalives(nai,
3688 SocketKeepalive.ERROR_INVALID_NETWORK);
3689
3690 nai.updateScoreForNetworkAgentUpdate();
3691 // This rematch is almost certainly not going to result in any changes, because
3692 // the destroyed flag is only just above the "current satisfier wins"
3693 // tie-breaker. But technically anything that affects scoring should rematch.
3694 rematchAllNetworksAndRequests();
3695 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3696 break;
3697 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003698 }
3699 }
3700
3701 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003702 final int netId = msg.arg2;
3703 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003704 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003705 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003706 switch (msg.what) {
3707 default:
3708 return false;
lucasline117e2e2019-10-22 18:27:33 +08003709 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003710 if (nai == null) {
3711 break;
3712 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003713 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3714 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003715 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003716 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003717 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003718 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003719 if (probePrivateDnsCompleted) {
3720 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3721 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003722 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003723 }
3724 // Only show the notification when the private DNS is broken and the
3725 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003726 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003727 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3728 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003729 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003730 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3731 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3732 // private DNS is broken, it means this network is being reevaluated.
3733 // Either probing private DNS is not necessary any more or it hasn't been
3734 // done yet. In either case, the networkCapabilities should be updated to
3735 // reflect the new status.
3736 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003737 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003738 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003739 }
3740 break;
3741 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003742 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003743 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3744
Erik Kline31b4a9e2018-01-11 21:07:29 +09003745 if (nai == null) break;
3746
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003747 handleNetworkTested(nai, results.mTestResult,
3748 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003749 break;
3750 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003751 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003752 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003753 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003754 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003755 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003756 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003757 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3758 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003759 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003760 if (nai == null) {
3761 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3762 break;
3763 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003764 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003765 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003766 (PendingIntent) msg.obj,
3767 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003768 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003769 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003770 break;
3771 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003772 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003773 if (nai == null) break;
3774
Erik Kline9a62f012018-03-21 07:18:33 -07003775 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003776 break;
3777 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003778 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003779 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003780 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003781 break;
3782 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003783 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003784 return true;
3785 }
3786
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003787 private void handleNetworkTested(
3788 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003789 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3790 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003791 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003792
3793 // If there is any kind of working networking, then the NAI has been evaluated
3794 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3795 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003796 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003797 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003798 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3799 // any callback that receives onAvailable for that rematch receives an extra caps
3800 // callback. To prevent that, update the score in the agent so the updates below won't
3801 // see an update to both caps and score at the same time.
3802 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003803 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();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003815 final boolean wasPortal = nai.captivePortalDetected();
3816 nai.setPartialConnectivity(partial);
3817 nai.setCaptivePortalDetected(portal);
3818 nai.updateScoreForNetworkAgentUpdate();
3819 final boolean partialConnectivityChanged = (wasPartial != partial);
3820 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003821
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003822 if (DBG) {
3823 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3824 ? " with redirect to " + redirectUrl
3825 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003826 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003827 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003828 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003829 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003830 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003831 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003832 if (valid) {
3833 handleFreshlyValidatedNetwork(nai);
3834 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3835 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003836 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003837 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003838 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003839 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003840 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003841 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003842 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003843 NotificationType.PRIVATE_DNS_BROKEN);
3844 // If network becomes valid, the hasShownBroken should be reset for
3845 // that network so that the notification will be fired when the private
3846 // DNS is broken again.
3847 nai.networkAgentConfig.hasShownBroken = false;
3848 }
3849 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003850 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09003851 } else if (portalChanged) {
3852 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3853 == getCaptivePortalMode()) {
3854 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3855 nai.onPreventAutomaticReconnect();
3856 teardownUnneededNetwork(nai);
3857 return;
3858 } else {
3859 updateCapabilitiesForNetwork(nai);
3860 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09003861 } else if (becameEvaluated) {
3862 // If valid or partial connectivity changed, updateCapabilities* has
3863 // done the rematch.
3864 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003865 }
3866 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003867
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003868 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003869 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003870 nai.onValidationStatusChanged(
3871 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3872 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003873
3874 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003875 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003876 // immediately. Re-notify partial connectivity silently if no internet
3877 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003878 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003879 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003880 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
3881 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003882 }
3883
Chalard Jean254bd162022-08-25 13:04:51 +09003884 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003885 handleNetworkUnvalidated(nai);
3886 }
3887 }
3888
Calvin Ondada1452016-10-11 15:10:46 -07003889 private int getCaptivePortalMode() {
3890 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003891 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3892 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003893 }
3894
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003895 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3896 switch (msg.what) {
3897 default:
3898 return false;
3899 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3900 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3901 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3902 handleLingerComplete(nai);
3903 }
3904 break;
3905 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003906 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3907 handleNetworkAgentRegistered(msg);
3908 break;
3909 }
3910 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3911 handleNetworkAgentDisconnected(msg);
3912 break;
3913 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003914 }
3915 return true;
3916 }
3917
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003918 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003919 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003920 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003921 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003922 maybeHandleNetworkAgentMessage(msg);
3923 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003924 }
3925 }
3926
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003927 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003928 private final int mNetId;
3929 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003930
3931 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003932 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003933 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003934 }
3935
3936 @Override
3937 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3938 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003939 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003940 }
3941
3942 @Override
3943 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003944 // Legacy version of notifyNetworkTestedWithExtras.
3945 // Would only be called if the system has a NetworkStack module older than the
3946 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003947 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003948 }
3949
3950 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003951 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003952 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3953 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003954 final Message msg = mTrackerHandler.obtainMessage(
3955 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003956 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003957 new NetworkTestedResults(
3958 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003959 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003960
3961 // Invoke ConnectivityReport generation for this Network test event.
3962 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3963 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003964
Cody Kestingf1120be2020-08-03 18:01:40 -07003965 // NetworkMonitor reports the network validation result as a bitmask while
3966 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3967 // logical value for ConnectivityDiagnostics.
3968 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3969 p.result);
3970
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003971 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003972 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003973 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3974 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3975
Aaron Huang959d3642021-01-21 15:47:41 +08003976 ConnectivityReportEvent reportEvent =
3977 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3978 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003979 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003980 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003981 }
3982
3983 @Override
3984 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3985 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3986 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003987 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003988 }
3989
3990 @Override
lucasline117e2e2019-10-22 18:27:33 +08003991 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3992 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3993 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003994 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003995 }
3996
3997 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003998 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3999 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4000 EVENT_CAPPORT_DATA_CHANGED,
4001 0, mNetId, data));
4002 }
4003
4004 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004005 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004006 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004007 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004008
4009 final PendingIntent pendingIntent;
4010 // Only the system server can register notifications with package "android"
4011 final long token = Binder.clearCallingIdentity();
4012 try {
paulhu7746e4e2020-06-09 19:07:03 +08004013 pendingIntent = PendingIntent.getBroadcast(
4014 mContext,
4015 0 /* requestCode */,
4016 intent,
4017 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004018 } finally {
4019 Binder.restoreCallingIdentity(token);
4020 }
4021 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4022 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004023 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004024 }
4025
4026 @Override
4027 public void hideProvisioningNotification() {
4028 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004029 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004030 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004031
4032 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004033 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004034 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004035 }
4036
4037 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004038 public int getInterfaceVersion() {
4039 return this.VERSION;
4040 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004041
4042 @Override
4043 public String getInterfaceHash() {
4044 return this.HASH;
4045 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004046 }
4047
Cody Kestingf1120be2020-08-03 18:01:40 -07004048 /**
4049 * Converts the given NetworkMonitor-specific validation result bitmask to a
4050 * ConnectivityDiagnostics-specific validation result int.
4051 */
4052 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4053 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4054 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4055 }
4056 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4057 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4058 }
4059 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4060 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4061 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4062 }
4063
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004064 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004065 log("Data stall detected with methods: " + p.detectionMethod);
4066
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004067 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004068 int detectionMethod = 0;
4069 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4070 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4071 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4072 }
4073 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4074 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4075 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4076 p.tcpMetricsCollectionPeriodMillis);
4077 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004078 }
4079
Cody Kestingf53a0752020-04-15 12:33:28 -07004080 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004081 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004082 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004083
4084 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4085 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4086 // the cost of going through two handlers.
4087 mConnectivityDiagnosticsHandler.sendMessage(msg);
4088 }
4089
Cody Kestingb37958e2020-05-15 10:36:01 -07004090 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4091 return (p.detectionMethod & detectionMethod) != 0;
4092 }
4093
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004094 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4095 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004096 }
4097
Erik Klinea73af002018-06-26 18:53:43 +09004098 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4099 if (nai == null) return;
4100 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4101 // in order to restart a validation pass from within netd.
4102 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4103 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004104 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004105 }
4106 }
4107
Erik Kline31b4a9e2018-01-11 21:07:29 +09004108 private void handlePrivateDnsSettingsChanged() {
4109 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4110
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004111 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004112 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004113 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004114 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4115 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004116 }
4117 }
4118
Erik Kline9a62f012018-03-21 07:18:33 -07004119 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4120 // Private DNS only ever applies to networks that might provide
4121 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004122 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004123
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004124 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004125 // schedule DNS resolutions. If a DNS resolution is required the
4126 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004127 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004128
4129 // With Private DNS bypass support, we can proceed to update the
4130 // Private DNS config immediately, even if we're in strict mode
4131 // and have not yet resolved the provider name into a set of IPs.
4132 updatePrivateDns(nai, cfg);
4133 }
4134
4135 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4136 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004137 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004138 }
4139
dalyk1720e542018-03-05 12:42:22 -05004140 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4141 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4142 if (nai == null) {
4143 return;
4144 }
4145 mDnsManager.updatePrivateDnsValidation(update);
4146 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4147 }
4148
paulhu7c0a2e62021-01-08 00:51:49 +08004149 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004150 int prefixLength) {
4151 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4152 if (nai == null) return;
4153
paulhu7c0a2e62021-01-08 00:51:49 +08004154 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4155 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004156
4157 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004158 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004159 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004160 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004161 prefixLength);
4162 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004163 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004164 return;
4165 }
4166 }
4167
Lorenzo Colittid523d142020-04-01 20:16:30 +09004168 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004169 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4170 }
4171
Hai Shalome58bdc62021-01-11 18:45:34 -08004172 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004173 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004174 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004175 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4176 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4177 }
4178
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004179 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004180 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004181 * @param nai the agent info to update
4182 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004183 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004184 */
junyulai2b6f0c22021-02-03 20:15:30 +08004185 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4186 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4187 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004188 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004189 // one lingered request, set inactive.
4190 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004191 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004192 if (DBG) log("Unsetting inactive " + nai.toShortString());
4193 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004194 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004195 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004196 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004197 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4198 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004199 }
junyulai2b6f0c22021-02-03 20:15:30 +08004200 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004201 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004202 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004203 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004204 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004205 }
4206
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004207 private void handleNetworkAgentRegistered(Message msg) {
4208 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4209 if (!mNetworkAgentInfos.contains(nai)) {
4210 return;
4211 }
4212
4213 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4214 if (VDBG) log("NetworkAgent registered");
4215 } else {
4216 loge("Error connecting NetworkAgent");
4217 mNetworkAgentInfos.remove(nai);
4218 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004219 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004220 synchronized (mNetworkForNetId) {
4221 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004222 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004223 mNetIdManager.releaseNetId(nai.network.getNetId());
4224 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004225 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004226 }
4227 }
4228 }
Paul Jensend5f53392014-11-25 15:26:53 -05004229
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004230 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004231 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004232 }
4233
he_won.hwang881307a2022-03-15 21:23:52 +09004234 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004235 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004236 if (SdkLevel.isAtLeastT()) return false;
4237 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4238 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4239 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4240 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004241 final long currentTimeMs = SystemClock.elapsedRealtime();
4242 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004243 if (timeSinceLastRoam <= blockTimeOut) {
4244 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4245 return true;
4246 }
4247 }
4248 return false;
4249 }
4250
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004251 private void handleNetworkAgentDisconnected(Message msg) {
4252 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004253 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004254 }
4255
Chalard Jeand9fffc32018-05-11 20:19:20 +09004256 // Destroys a network, remove references to it from the internal state managed by
4257 // ConnectivityService, free its interfaces and clean up.
4258 // Must be called on the Handler thread.
4259 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004260 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004261
4262 if (!mNetworkAgentInfos.contains(nai)) return;
4263
Chalard Jeand9fffc32018-05-11 20:19:20 +09004264 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004265 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004266 }
lucaslinb25c9a62019-02-12 15:30:13 +08004267 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004268 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004269 // A network agent has disconnected.
4270 // TODO - if we move the logic to the network agent (have them disconnect
4271 // because they lost all their requests or because their score isn't good)
4272 // then they would disconnect organically, report their new state and then
4273 // disconnect the channel.
4274 if (nai.networkInfo.isConnected()) {
4275 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4276 null, null);
4277 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004278 final boolean wasDefault = isDefaultNetwork(nai);
4279 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004280 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004281 }
4282 notifyIfacesChangedForNetworkStats();
4283 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4284 // by other networks that are already connected. Perhaps that can be done by
4285 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4286 // of rematchAllNetworksAndRequests
4287 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004288 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004289
4290 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004291 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4292 // Disable wakeup packet monitoring for each interface.
4293 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4294 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004295 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004296 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004297 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004298 synchronized (mNetworkForNetId) {
4299 // Remove the NetworkAgent, but don't mark the netId as
4300 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004301 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004302 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004303 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004304 // Remove all previously satisfied requests.
4305 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004306 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004307 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004308 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004309 if (currentNetwork != null
4310 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004311 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004312 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4313 // rematch not to keep disconnected agents instead of setting it here ; this
4314 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004315 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004316 for (final NetworkOfferInfo noi : mNetworkOffers) {
4317 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004318 }
James Mattise3ef1912020-12-20 11:09:58 -08004319
Chalard Jean5b409c72021-02-04 13:12:59 +09004320 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004321 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004322 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004323 // network, because while incorrect this is the closest to the old (also
4324 // incorrect) behavior.
4325 mNetworkActivityTracker.updateDataActivityTracking(
4326 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004327 ensureNetworkTransitionWakelock(nai.toShortString());
4328 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004329 }
4330 }
junyulai2b6f0c22021-02-03 20:15:30 +08004331 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004332 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004333 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004334 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004335 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004336 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004337 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004338
4339 // Immediate teardown.
4340 if (nai.teardownDelayMs == 0) {
4341 destroyNetwork(nai);
4342 return;
4343 }
4344
4345 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004346 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304347 try {
4348 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4349 } catch (RemoteException e) {
4350 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4351 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004352 }
4353 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4354 }
4355
4356 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004357 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004358 // Tell netd to clean up the configuration for this network
4359 // (routing rules, DNS, etc).
4360 // This may be slow as it requires a lot of netd shelling out to ip and
4361 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004362 // after we've rematched networks with requests (which might change the default
4363 // network or service a new request from an app), so network traffic isn't interrupted
4364 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004365 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004366 }
Chalard Jean254bd162022-08-25 13:04:51 +09004367 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004368 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4369 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4370 // false if the network was never created.
4371 // TODO: delete when S is no longer supported.
4372 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004373 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004374 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004375 }
4376
Ken Chen6df7a902021-04-09 15:08:42 +08004377 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004378 try {
4379 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004380 final NativeNetworkConfig config;
4381 if (nai.isVPN()) {
4382 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004383 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004384 return false;
4385 }
4386 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4387 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004388 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004389 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004390 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004391 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004392 getNetworkPermission(nai.networkCapabilities),
4393 false /* secure */,
4394 VpnManager.TYPE_VPN_NONE,
4395 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004396 }
Ken Chen6df7a902021-04-09 15:08:42 +08004397 mNetd.networkCreate(config);
4398 mDnsResolver.createNetworkCache(nai.network.getNetId());
4399 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4400 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004401 return true;
4402 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004403 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004404 return false;
4405 }
4406 }
4407
Ken Chen6df7a902021-04-09 15:08:42 +08004408 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004409 if (mDscpPolicyTracker != null) {
4410 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4411 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004412 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004413 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004414 } catch (RemoteException | ServiceSpecificException e) {
4415 loge("Exception destroying network(networkDestroy): " + e);
4416 }
4417 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004418 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004419 } catch (RemoteException | ServiceSpecificException e) {
4420 loge("Exception destroying network: " + e);
4421 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004422 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4423 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4424 // gets created, could add data to DnsManager data structures that will never get deleted.
4425 mDnsManager.removeNetwork(nai.network);
4426
4427 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004428 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004429 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4430 }
4431
Chalard Jean254bd162022-08-25 13:04:51 +09004432 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004433 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004434 }
4435
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004436 // If this method proves to be too slow then we can maintain a separate
4437 // pendingIntent => NetworkRequestInfo map.
4438 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4439 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004440 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4441 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4442 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004443 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004444 return entry.getValue();
4445 }
4446 }
4447 return null;
4448 }
4449
Chalard Jean524f0b12021-10-25 21:11:56 +09004450 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4451 if (SdkLevel.isAtLeastT()) {
4452 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4453 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4454 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4455 // bug is fixed.
4456 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004457 throw new IllegalStateException("This NRI is already registered. New : " + nri
4458 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004459 }
4460 }
4461 }
4462 }
4463
Chalard Jeanac9ace02022-01-26 16:54:05 +09004464 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4465 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004466 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004467 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4468 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004469 }
4470 return false;
4471 }
4472
James Mattisf7027322020-12-13 16:28:14 -08004473 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004474 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004475 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4476 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4477 final NetworkRequestInfo existingRequest =
4478 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004479 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004480 if (DBG) {
4481 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4482 + nri.mRequests.get(0) + " because their intents matched.");
4483 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004484 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004485 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004486 }
Erik Kline05f2b402015-04-30 12:58:40 +09004487 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004488 }
4489
James Mattisf7027322020-12-13 16:28:14 -08004490 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004491 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004492 }
4493
James Mattis3ce3d3c2021-02-09 18:18:28 -08004494 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004495 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004496 for (final NetworkRequestInfo nri : nris) {
4497 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004498 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004499 for (final NetworkRequest req : nri.mRequests) {
4500 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004501 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004502 if (req.isListen()) {
4503 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4504 if (req.networkCapabilities.hasSignalStrength()
4505 && network.satisfiesImmutableCapabilitiesOf(req)) {
4506 updateSignalStrengthThresholds(network, "REGISTER", req);
4507 }
James Mattisf7027322020-12-13 16:28:14 -08004508 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004509 }
4510 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004511
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004512 // If this NRI has a satisfier already, it is replacing an older request that
4513 // has been removed. Track it.
4514 final NetworkRequest activeRequest = nri.getActiveRequest();
4515 if (null != activeRequest) {
4516 // If there is an active request, then for sure there is a satisfier.
4517 nri.getSatisfier().addRequest(activeRequest);
4518 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004519 }
James Mattisf7027322020-12-13 16:28:14 -08004520
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004521 if (mFlags.noRematchAllRequestsOnRegister()) {
4522 rematchNetworksAndRequests(nris);
4523 } else {
4524 rematchAllNetworksAndRequests();
4525 }
James Mattis45d81842021-01-10 14:24:24 -08004526
Chalard Jean0354d8c2021-01-12 10:58:56 +09004527 // Requests that have not been matched to a network will not have been sent to the
4528 // providers, because the old satisfier and the new satisfier are the same (null in this
4529 // case). Send these requests to the providers.
4530 for (final NetworkRequestInfo nri : nris) {
4531 for (final NetworkOfferInfo noi : mNetworkOffers) {
4532 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004533 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004534 }
4535 }
4536
James Mattisf7027322020-12-13 16:28:14 -08004537 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4538 final int callingUid) {
4539 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004540 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004541 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4542 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4543 handleReleaseNetworkRequest(
4544 nri.mRequests.get(0),
4545 callingUid,
4546 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004547 }
4548 }
4549
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004550 // Determines whether the network is the best (or could become the best, if it validated), for
4551 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4552 // on the value of reason:
4553 //
4554 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4555 // then it should be torn down.
4556 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4557 // then it should be lingered.
4558 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004559 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004560
Chalard Jean254bd162022-08-25 13:04:51 +09004561 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004562 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4563 return false;
4564 }
4565
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004566 final int numRequests;
4567 switch (reason) {
4568 case TEARDOWN:
4569 numRequests = nai.numRequestNetworkRequests();
4570 break;
4571 case LINGER:
4572 numRequests = nai.numForegroundNetworkRequests();
4573 break;
4574 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004575 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004576 return true;
4577 }
4578
Chalard Jean947acd42021-03-08 22:29:27 +09004579 if (numRequests > 0) return false;
4580
Paul Jensende49eb12015-06-25 15:30:08 -04004581 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004582 if (reason == UnneededFor.LINGER
4583 && !nri.isMultilayerRequest()
4584 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004585 // Background requests don't affect lingering.
4586 continue;
4587 }
4588
James Mattis3d229892020-11-16 16:46:28 -08004589 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004590 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004591 }
4592 }
Paul Jensende49eb12015-06-25 15:30:08 -04004593 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004594 }
4595
James Mattis3d229892020-11-16 16:46:28 -08004596 private boolean isNetworkPotentialSatisfier(
4597 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4598 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004599 // request, return immediately. For multilayer requests, check to see if any of the
4600 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004601 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4602 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004603 return false;
4604 }
4605 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004606 // This multilayer listen request is satisfied therefore no further requests need to be
4607 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004608 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004609 return false;
4610 }
James Mattis3d229892020-11-16 16:46:28 -08004611 // As non-multilayer listen requests have already returned, the below would only happen
4612 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004613 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004614 continue;
4615 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004616 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004617 // there is hope for it to become one if it validated, then it is needed.
4618 if (candidate.satisfies(req)) {
4619 // As soon as a network is found that satisfies a request, return. Specifically for
4620 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4621 // is important so as to not evaluate lower priority requests further in
4622 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004623 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4624 ? nri.getSatisfier() : null;
4625 // Note that this catches two important cases:
4626 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4627 // is currently satisfying the request. This is desirable when
4628 // cellular ends up validating but WiFi does not.
4629 // 2. Unvalidated WiFi will not be reaped when validated cellular
4630 // is currently satisfying the request. This is desirable when
4631 // WiFi ends up validating and out scoring cellular.
4632 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004633 }
4634 }
4635
4636 return false;
4637 }
4638
Erik Kline0c04b742016-07-07 16:50:58 +09004639 private NetworkRequestInfo getNriForAppRequest(
4640 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004641 // Looking up the app passed param request in mRequests isn't possible since it may return
4642 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4643 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004644 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4645 // to avoid potential race conditions when validating a package->uid mapping when sending
4646 // the callback on the very low-chance that an application shuts down prior to the callback
4647 // being sent.
4648 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4649 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004650
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004651 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004652 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004653 log(String.format("UID %d attempted to %s for unowned request %s",
4654 callingUid, requestedOperation, nri));
4655 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004656 }
Erik Kline0c04b742016-07-07 16:50:58 +09004657 }
4658
4659 return nri;
4660 }
4661
James Mattisf7027322020-12-13 16:28:14 -08004662 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4663 final String callingMethod) {
4664 if (nri.isMultilayerRequest()) {
4665 throw new IllegalStateException(
4666 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004667 }
4668 }
4669
James Mattisf7027322020-12-13 16:28:14 -08004670 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004671 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004672 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4673 // single NetworkRequest and thus does not apply to multilayer requests.
4674 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4675 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004676 return;
4677 }
James Mattis2516da32021-01-31 17:06:19 -08004678 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004679 return;
4680 }
James Mattisf7027322020-12-13 16:28:14 -08004681 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4682 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004683 }
4684 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004685 callCallbackForRequest(
4686 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004687 }
4688
James Mattisf7027322020-12-13 16:28:14 -08004689 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4690 final int callingUid,
4691 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004692 final NetworkRequestInfo nri =
4693 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4694 if (nri == null) {
4695 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004696 }
James Mattisf7027322020-12-13 16:28:14 -08004697 if (VDBG || (DBG && request.isRequest())) {
4698 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004699 }
4700 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004701 if (callOnUnavailable) {
4702 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4703 }
Erik Kline155a59a2015-11-25 12:49:38 +09004704 }
Erik Kline0c04b742016-07-07 16:50:58 +09004705
James Mattisa076c532020-12-02 14:12:41 -08004706 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004707 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004708 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004709 if (null == mNetworkRequests.remove(req)) {
4710 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4711 continue;
4712 }
James Mattisa076c532020-12-02 14:12:41 -08004713 if (req.isListen()) {
4714 removeListenRequestFromNetworks(req);
4715 }
4716 }
James Mattis8f036802021-06-20 16:26:01 -07004717 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004718 if (mDefaultNetworkRequests.remove(nri)) {
4719 // If this request was one of the defaults, then the UID rules need to be updated
4720 // WARNING : if the app(s) for which this network request is the default are doing
4721 // traffic, this will kill their connected sockets, even if an equivalent request
4722 // is going to be reinstated right away ; unconnected traffic will go on the default
4723 // until the new default is set, which will happen very soon.
4724 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4725 // remove ranges for those requests that won't have a replacement
4726 final NetworkAgentInfo satisfier = nri.getSatisfier();
4727 if (null != satisfier) {
4728 try {
paulhu0e79d952021-06-09 16:11:35 +08004729 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4730 satisfier.network.getNetId(),
4731 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004732 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004733 } catch (RemoteException e) {
4734 loge("Exception setting network preference default network", e);
4735 }
4736 }
4737 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004738 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004739 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004740 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004741
4742 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004743 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004744 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004745 }
4746 }
4747
Chalard Jean0354d8c2021-01-12 10:58:56 +09004748 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4749 // needed for this offer.
4750 for (final NetworkOfferInfo noi : mNetworkOffers) {
4751 for (final NetworkRequest req : nri.mRequests) {
4752 if (req.isRequest() && noi.offer.neededFor(req)) {
4753 noi.offer.onNetworkUnneeded(req);
4754 }
4755 }
4756 }
James Mattisa076c532020-12-02 14:12:41 -08004757 }
4758
James Mattis3ce3d3c2021-02-09 18:18:28 -08004759 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4760 for (final NetworkRequestInfo nri : nris) {
4761 if (mDefaultRequest == nri) {
4762 // Make sure we never remove the default request.
4763 continue;
4764 }
4765 handleRemoveNetworkRequest(nri);
4766 }
4767 }
4768
James Mattisa076c532020-12-02 14:12:41 -08004769 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4770 // listens don't have a singular affected Network. Check all networks to see
4771 // if this listen request applies and remove it.
4772 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4773 nai.removeRequest(req.requestId);
4774 if (req.networkCapabilities.hasSignalStrength()
4775 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4776 updateSignalStrengthThresholds(nai, "RELEASE", req);
4777 }
4778 }
4779 }
4780
4781 /**
4782 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4783 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4784 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4785 */
4786 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4787 boolean wasKept = false;
4788 final NetworkAgentInfo nai = nri.getSatisfier();
4789 if (nai != null) {
4790 final int requestLegacyType = nri.getActiveRequest().legacyType;
4791 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4792 nai.removeRequest(nri.getActiveRequest().requestId);
4793 if (VDBG || DDBG) {
4794 log(" Removing from current network " + nai.toShortString()
4795 + ", leaving " + nai.numNetworkRequests() + " requests.");
4796 }
4797 // If there are still lingered requests on this network, don't tear it down,
4798 // but resume lingering instead.
4799 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004800 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004801 notifyNetworkLosing(nai, now);
4802 }
4803 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4804 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4805 teardownUnneededNetwork(nai);
4806 } else {
4807 wasKept = true;
4808 }
James Mattisa076c532020-12-02 14:12:41 -08004809 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4810 // Went from foreground to background.
4811 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004812 }
4813
Erik Kline0c04b742016-07-07 16:50:58 +09004814 // Maintain the illusion. When this request arrived, we might have pretended
4815 // that a network connected to serve it, even though the network was already
4816 // connected. Now that this request has gone away, we might have to pretend
4817 // that the network disconnected. LegacyTypeTracker will generate that
4818 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004819 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004820 boolean doRemove = true;
4821 if (wasKept) {
4822 // check if any of the remaining requests for this network are for the
4823 // same legacy type - if so, don't remove the nai
4824 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4825 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004826 if (otherRequest.legacyType == requestLegacyType
4827 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004828 if (DBG) log(" still have other legacy request - leaving");
4829 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004830 }
4831 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004832 }
4833
Erik Kline0c04b742016-07-07 16:50:58 +09004834 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004835 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004836 }
4837 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004838 }
4839 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004840
Junyu Lai00d92df2022-07-05 11:01:52 +08004841 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004842 return checkAnyPermissionOf(
4843 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4844 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4845 }
4846
Lorenzo Colittid6459092016-07-04 12:55:44 +09004847 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004848 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004849 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004850 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004851 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004852 }
4853
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004854 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004855 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4856 enforceNetworkStackSettingsOrSetup();
4857 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4858 encodeBool(accept), encodeBool(always), network));
4859 }
4860
4861 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004862 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004863 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004864 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4865 }
4866
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004867 @Override
4868 public void setTestAllowBadWifiUntil(long timeMs) {
4869 enforceSettingsPermission();
4870 if (!Build.isDebuggable()) {
4871 throw new IllegalStateException("Does not support in non-debuggable build");
4872 }
4873
4874 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4875 throw new IllegalArgumentException("It should not exceed "
4876 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4877 }
4878
4879 mHandler.sendMessage(
4880 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4881 }
4882
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004883 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4884 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4885 " accept=" + accept + " always=" + always);
4886
4887 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4888 if (nai == null) {
4889 // Nothing to do.
4890 return;
4891 }
4892
Chalard Jean254bd162022-08-25 13:04:51 +09004893 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004894 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004895 return;
4896 }
4897
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004898 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004899 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004900 }
4901
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004902 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4903 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004904 // If network becomes partial connectivity and user already accepted to use this
4905 // network, we should respect the user's option and don't need to popup the
4906 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004907 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004908 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004909 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004910 }
4911
4912 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004913 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004914 }
4915
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004916 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004917 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004918 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004919 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004920 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004921 }
4922
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004923 }
4924
lucaslin2240ef62019-03-12 13:08:03 +08004925 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4926 boolean always) {
4927 if (DBG) {
4928 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4929 + " always=" + always);
4930 }
4931
4932 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4933 if (nai == null) {
4934 // Nothing to do.
4935 return;
4936 }
4937
Chalard Jean254bd162022-08-25 13:04:51 +09004938 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004939 // The network validated while the dialog box was up. Take no action.
4940 return;
4941 }
4942
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004943 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4944 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004945 }
4946
4947 // TODO: Use the current design or save the user choice into IpMemoryStore.
4948 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004949 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004950 }
4951
4952 if (!accept) {
4953 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004954 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004955 // Tear down the network.
4956 teardownUnneededNetwork(nai);
4957 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004958 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4959 // result in a partial connectivity result which will be processed by
4960 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004961 //
4962 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4963 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004964 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004965 }
4966 }
4967
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004968 private void handleSetAvoidUnvalidated(Network network) {
4969 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09004970 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004971 // Nothing to do. The network either disconnected or revalidated.
4972 return;
4973 }
Chalard Jean254bd162022-08-25 13:04:51 +09004974 if (0L == nai.getAvoidUnvalidated()) {
4975 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09004976 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004977 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004978 }
4979 }
4980
Chalard Jean5fb43c72022-09-08 19:03:14 +09004981 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09004982 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09004983 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004984 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09004985 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004986 }
4987
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004988 @Override
4989 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004990 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004991 mHandler.post(() -> {
4992 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4993 if (nai == null) return;
4994 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004995 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004996 });
4997 }
4998
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004999 /**
5000 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5001 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005002 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005003 * @param appExtras Bundle to use as intent extras for the captive portal application.
5004 * Must be treated as opaque to avoid preventing the captive portal app to
5005 * update its arguments.
5006 */
5007 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005008 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005009 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5010 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005011
5012 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5013 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005014 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5015 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005016 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5017
lucaslin75ff7022020-12-17 04:14:35 +08005018 final long token = Binder.clearCallingIdentity();
5019 try {
5020 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5021 } finally {
5022 Binder.restoreCallingIdentity(token);
5023 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005024 }
5025
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005026 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5027 private final Network mNetwork;
5028
5029 private CaptivePortalImpl(Network network) {
5030 mNetwork = network;
5031 }
5032
5033 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005034 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005035 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5036 enforceSettingsPermission();
5037 }
5038
Chiachang Wang938bfba2020-01-09 13:50:55 +08005039 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005040 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005041 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005042 }
5043
5044 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005045 public void appRequest(final int request) {
5046 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5047 if (nm == null) return;
5048
5049 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005050 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005051 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005052 }
5053 }
5054
5055 @Nullable
5056 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5057 // getNetworkAgentInfoForNetwork is thread-safe
5058 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5059 if (nai == null) return null;
5060
5061 // nai.networkMonitor() is thread-safe
5062 return nai.networkMonitor();
5063 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005064 }
5065
Hugo Benichic9048bc2016-09-14 23:23:08 +00005066 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005067 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005068 }
5069
Chalard Jean020b93a2022-09-01 13:20:14 +09005070 private boolean activelyPreferBadWifi() {
5071 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5072 }
5073
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005074 /**
5075 * Return whether the device should maintain continuous, working connectivity by switching away
5076 * from WiFi networks having no connectivity.
5077 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5078 */
5079 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005080 if (!checkNetworkStackPermission()) {
5081 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5082 }
5083 return avoidBadWifi();
5084 }
5085
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005086 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005087 ensureRunningOnConnectivityServiceThread();
5088 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005089 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005090 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005091 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005092 if (avoidBadWifi) {
5093 // If the device is now avoiding bad wifi, remove notifications that might have
5094 // been put up when the device didn't.
5095 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5096 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005097 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005098 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5099 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5100 for (final NetworkOfferInfo noi : offersToUpdate) {
5101 updateOfferScore(noi.offer);
5102 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005103 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005104 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005105 }
5106
Erik Kline95ecfee2016-10-02 18:02:14 +09005107 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005108 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005109 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005110 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005111 if (!configRestrict) {
5112 pw.println("Bad Wi-Fi avoidance: unrestricted");
5113 return;
5114 }
5115
5116 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5117 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005118 pw.println("Config restrict: " + configRestrict);
5119 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005120
Chalard Jeane0fdea32022-09-14 21:44:22 +09005121 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005122 String description;
5123 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005124 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005125 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005126 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005127 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005128 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005129 description = "avoid";
5130 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005131 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005132 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005133 pw.println("Avoid bad wifi setting: " + description);
5134 final Boolean configValue = mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi();
5135 if (null == configValue) {
5136 description = "unset";
5137 } else if (configValue) {
5138 description = "force true";
5139 } else {
5140 description = "force false";
5141 }
5142 pw.println("Actively prefer bad wifi conf: " + description);
5143 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005144 pw.println("Network overrides:");
5145 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005146 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005147 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005148 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005149 }
5150 }
5151 pw.decreaseIndent();
5152 pw.decreaseIndent();
5153 }
5154
paulhu7746e4e2020-06-09 19:07:03 +08005155 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5156 // unify the method.
5157 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5158 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5159 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5160 return settingsComponent != null
5161 ? settingsComponent.getPackageName() : "com.android.settings";
5162 }
5163
lucaslinb1e8e382019-01-24 15:55:30 +08005164 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005165 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005166 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005167 switch (type) {
5168 case NO_INTERNET:
5169 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005170 // High priority because it is only displayed for explicitly selected networks.
5171 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005172 break;
lucasline117e2e2019-10-22 18:27:33 +08005173 case PRIVATE_DNS_BROKEN:
5174 action = Settings.ACTION_WIRELESS_SETTINGS;
5175 // High priority because we should let user know why there is no internet.
5176 highPriority = true;
5177 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005178 case LOST_INTERNET:
5179 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005180 // High priority because it could help the user avoid unexpected data usage.
5181 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005182 break;
lucaslin2240ef62019-03-12 13:08:03 +08005183 case PARTIAL_CONNECTIVITY:
5184 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005185 // Don't bother the user with a high-priority notification if the network was not
5186 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005187 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005188 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005189 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005190 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005191 return;
5192 }
5193
5194 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005195 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005196 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005197 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005198 // Some OEMs have their own Settings package. Thus, need to get the current using
5199 // Settings package name instead of just use default name "com.android.settings".
5200 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5201 intent.setClassName(settingsPkgName,
5202 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005203 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005204
paulhu2af50222020-10-11 22:52:27 +08005205 PendingIntent pendingIntent = PendingIntent.getActivity(
5206 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005207 0 /* requestCode */,
5208 intent,
paulhu2af50222020-10-11 22:52:27 +08005209 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005210
Serik Beketayevec8ad212020-12-07 22:43:07 -08005211 mNotifier.showNotification(
5212 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005213 }
5214
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005215 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5216 // Don't prompt if the network is validated, and don't prompt on captive portals
5217 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005218 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005219 return false;
5220 }
5221
5222 // If a network has partial connectivity, always prompt unless the user has already accepted
5223 // partial connectivity and selected don't ask again. This ensures that if the device
5224 // automatically connects to a network that has partial Internet access, the user will
5225 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005226 // because we have prompted them.
5227 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005228 return true;
5229 }
5230
5231 // If a network has no Internet access, only prompt if the network was explicitly selected
5232 // and if the user has not already told us to use the network regardless of whether it
5233 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005234 if (nai.networkAgentConfig.explicitlySelected
5235 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005236 return true;
5237 }
5238
5239 return false;
5240 }
5241
Chalard Jean5fb43c72022-09-08 19:03:14 +09005242 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5243 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005244
Chalard Jean5fb43c72022-09-08 19:03:14 +09005245 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5246 if (null == nai) return;
5247
5248 if (nai.setEvaluated()) {
5249 // If setEvaluated() returned true, the network never had any form of connectivity.
5250 // This may have an impact on request matching if bad WiFi avoidance is off and the
5251 // network was found not to have Internet access.
5252 nai.updateScoreForNetworkAgentUpdate();
5253 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005254
5255 // Also, if this is WiFi and it should be preferred actively, now is the time to
5256 // prompt the user that they walked past and connected to a bad WiFi.
5257 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5258 && !avoidBadWifi()
5259 && activelyPreferBadWifi()) {
5260 // The notification will be removed if the network validates or disconnects.
5261 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5262 return;
5263 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005264 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005265
Chalard Jean5fb43c72022-09-08 19:03:14 +09005266 if (!shouldPromptUnvalidated(nai)) return;
5267
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005268 // Stop automatically reconnecting to this network in the future. Automatically connecting
5269 // to a network that provides no or limited connectivity is not useful, because the user
5270 // cannot use that network except through the notification shown by this method, and the
5271 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005272 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005273
Chalard Jean254bd162022-08-25 13:04:51 +09005274 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005275 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005276 } else {
5277 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5278 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005279 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005280
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005281 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5282 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005283 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005284
lucaslin2240ef62019-03-12 13:08:03 +08005285 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5286 return;
5287 }
5288
5289 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005290 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005291 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005292 }
5293
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005294 @Override
5295 public int getMultipathPreference(Network network) {
5296 enforceAccessPermission();
5297
5298 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005299 if (nai != null && nai.networkCapabilities
5300 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005301 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5302 }
5303
Aaron Huang9a57acf2020-12-08 10:03:29 +08005304 final NetworkPolicyManager netPolicyManager =
5305 mContext.getSystemService(NetworkPolicyManager.class);
5306
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005307 final long token = Binder.clearCallingIdentity();
5308 final int networkPreference;
5309 try {
5310 networkPreference = netPolicyManager.getMultipathPreference(network);
5311 } finally {
5312 Binder.restoreCallingIdentity(token);
5313 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005314 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005315 return networkPreference;
5316 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005317 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5318 }
5319
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005320 @Override
5321 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005322 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005323 }
5324
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005325 private class InternalHandler extends Handler {
5326 public InternalHandler(Looper looper) {
5327 super(looper);
5328 }
5329
5330 @Override
5331 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005332 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005333 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005334 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005335 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005336 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005337 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005338 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005339 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005340 break;
5341 }
Jason Monka69f1b02013-10-10 14:02:51 -04005342 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005343 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5344 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005345 break;
5346 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005347 case EVENT_REGISTER_NETWORK_PROVIDER: {
5348 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005349 break;
5350 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005351 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5352 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005353 break;
5354 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005355 case EVENT_REGISTER_NETWORK_OFFER: {
5356 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5357 break;
5358 }
5359 case EVENT_UNREGISTER_NETWORK_OFFER: {
5360 final NetworkOfferInfo offer =
5361 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5362 if (null != offer) {
5363 handleUnregisterNetworkOffer(offer);
5364 }
5365 break;
5366 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005367 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005368 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5369 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5370 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005371 break;
5372 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005373 case EVENT_REGISTER_NETWORK_REQUEST:
5374 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005375 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005376 break;
5377 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005378 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5379 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005380 handleRegisterNetworkRequestWithIntent(msg);
5381 break;
5382 }
Erik Kline155a59a2015-11-25 12:49:38 +09005383 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5384 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5385 handleTimedOutNetworkRequest(nri);
5386 break;
5387 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005388 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5389 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5390 break;
5391 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005392 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005393 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5394 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005395 break;
5396 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005397 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005398 Network network = (Network) msg.obj;
5399 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005400 break;
5401 }
lucaslin2240ef62019-03-12 13:08:03 +08005402 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5403 Network network = (Network) msg.obj;
5404 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5405 toBool(msg.arg2));
5406 break;
5407 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005408 case EVENT_SET_AVOID_UNVALIDATED: {
5409 handleSetAvoidUnvalidated((Network) msg.obj);
5410 break;
5411 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005412 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5413 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005414 break;
5415 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005416 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5417 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005418 break;
5419 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005420 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005421 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005422 mKeepaliveTracker.handleStartKeepalive(msg);
5423 break;
5424 }
5425 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005426 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005427 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5428 int slot = msg.arg1;
5429 int reason = msg.arg2;
5430 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5431 break;
5432 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005433 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5434 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5435 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005436 break;
5437 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005438 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5439 handlePrivateDnsSettingsChanged();
5440 break;
dalyk1720e542018-03-05 12:42:22 -05005441 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5442 handlePrivateDnsValidationUpdate(
5443 (PrivateDnsValidationUpdate) msg.obj);
5444 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005445 case EVENT_UID_BLOCKED_REASON_CHANGED:
5446 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005447 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005448 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5449 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5450 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005451 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005452 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5453 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005454 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005455 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005456 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005457 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005458 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5459 IOnCompleteListener> arg =
5460 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5461 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005462 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005463 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005464 }
lucaslin1193a5d2021-01-21 02:04:15 +08005465 case EVENT_REPORT_NETWORK_ACTIVITY:
5466 mNetworkActivityTracker.handleReportNetworkActivity();
5467 break;
paulhu51f77dc2021-06-07 02:34:20 +00005468 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5469 handleMobileDataPreferredUidsChanged();
5470 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005471 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5472 final long timeMs = ((Long) msg.obj).longValue();
5473 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5474 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005475 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5476 handleIngressRateLimitChanged();
5477 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005478 }
5479 }
5480 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005481
Lorenzo Colittid6459092016-07-04 12:55:44 +09005482 @Override
markchien5776f962019-12-16 20:15:20 +08005483 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005484 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005485 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005486 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5487 Context.TETHERING_SERVICE);
5488 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005489 }
5490
Lorenzo Colittid6459092016-07-04 12:55:44 +09005491 @Override
markchien5776f962019-12-16 20:15:20 +08005492 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005493 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005494 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005495 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5496 Context.TETHERING_SERVICE);
5497 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005498 }
5499
Lorenzo Colittid6459092016-07-04 12:55:44 +09005500 @Override
markchien5776f962019-12-16 20:15:20 +08005501 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005502 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005503 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005504 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5505 Context.TETHERING_SERVICE);
5506 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005507 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005508
markchien5776f962019-12-16 20:15:20 +08005509
Lorenzo Colittid6459092016-07-04 12:55:44 +09005510 @Override
markchien5776f962019-12-16 20:15:20 +08005511 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005512 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005513 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005514 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5515 Context.TETHERING_SERVICE);
5516
5517 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005518 }
5519
Lorenzo Colittid6459092016-07-04 12:55:44 +09005520 @Override
markchien5776f962019-12-16 20:15:20 +08005521 @Deprecated
5522 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005523 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005524 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5525 Context.TETHERING_SERVICE);
5526
5527 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005528 }
5529
Udam Saini8f7d6a72017-06-07 12:06:28 -07005530 @Override
markchien5776f962019-12-16 20:15:20 +08005531 @Deprecated
5532 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005533 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005534 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5535 Context.TETHERING_SERVICE);
5536 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005537 }
5538
Robert Greenwalte0b00512014-07-02 09:59:16 -07005539 // Called when we lose the default network and have no replacement yet.
5540 // This will automatically be cleared after X seconds or a new default network
5541 // becomes CONNECTED, whichever happens first. The timer is started by the
5542 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005543 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005544 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005545 if (mNetTransitionWakeLock.isHeld()) {
5546 return;
5547 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005548 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005549 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5550 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005551 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005552 mWakelockLogs.log("ACQUIRE for " + forWhom);
5553 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005554 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005555 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005556 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005557 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005558
Hugo Benichi471b62a2017-03-30 23:18:10 +09005559 // Called when we gain a new default network to release the network transition wakelock in a
5560 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5561 // message is cancelled.
5562 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005563 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005564 if (!mNetTransitionWakeLock.isHeld()) {
5565 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005566 }
5567 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005568 // Cancel self timeout on wakelock hold.
5569 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5570 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5571 mHandler.sendMessageDelayed(msg, 1000);
5572 }
5573
5574 // Called when either message of ensureNetworkTransitionWakelock or
5575 // scheduleReleaseNetworkTransitionWakelock is processed.
5576 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5577 String event = eventName(eventId);
5578 synchronized (this) {
5579 if (!mNetTransitionWakeLock.isHeld()) {
5580 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005581 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005582 return;
5583 }
5584 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005585 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5586 mTotalWakelockDurationMs += lockDuration;
5587 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5588 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005589 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005590 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005591 }
5592
Robert Greenwalt986c7412010-09-08 15:24:47 -07005593 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005594 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005595 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005596 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005597 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005598 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005599 }
5600
Lorenzo Colittid6459092016-07-04 12:55:44 +09005601 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005602 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005603 enforceAccessPermission();
5604 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005605 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005606 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005607
5608 final NetworkAgentInfo nai;
5609 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005610 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005611 } else {
5612 nai = getNetworkAgentInfoForNetwork(network);
5613 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005614
5615 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005616 mHandler.obtainMessage(
5617 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005618 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005619
Hugo Benichid6b510a2017-04-06 17:22:18 +09005620 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005621 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005622 if (nai == null
5623 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005624 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005625 return;
5626 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005627 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005628 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005629 mConnectivityDiagnosticsHandler.sendMessage(
5630 mConnectivityDiagnosticsHandler.obtainMessage(
5631 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5632 new ReportedNetworkConnectivityInfo(
5633 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005634 return;
5635 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005636 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005637 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005638 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005639 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005640 // Validating a network that has not yet connected could result in a call to
5641 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005642 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005643 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005644 }
paulhu7aeba372020-12-30 00:42:19 +08005645 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5646 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005647 return;
5648 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005649
5650 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5651 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5652 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5653 // completed.
5654 mConnectivityDiagnosticsHandler.sendMessage(
5655 mConnectivityDiagnosticsHandler.obtainMessage(
5656 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5657 new ReportedNetworkConnectivityInfo(
5658 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005659 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005660 }
5661
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005662 // TODO: call into netd.
5663 private boolean queryUserAccess(int uid, Network network) {
5664 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5665 if (nai == null) return false;
5666
5667 // Any UID can use its default network.
5668 if (nai == getDefaultNetworkForUid(uid)) return true;
5669
5670 // Privileged apps can use any network.
5671 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5672 return true;
5673 }
5674
5675 // An unprivileged UID can use a VPN iff the VPN applies to it.
5676 if (nai.isVPN()) {
5677 return nai.networkCapabilities.appliesToUid(uid);
5678 }
5679
5680 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5681 // sockets, i.e., if it is the owner.
5682 final NetworkAgentInfo vpn = getVpnForUid(uid);
5683 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5684 && uid != vpn.networkCapabilities.getOwnerUid()) {
5685 return false;
5686 }
5687
5688 // The UID's permission must be at least sufficient for the network. Since the restricted
5689 // permission was already checked above, that just leaves background networks.
5690 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5691 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5692 }
5693
5694 // Unrestricted network. Anyone gets to use it.
5695 return true;
5696 }
5697
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005698 /**
5699 * Returns information about the proxy a certain network is using. If given a null network, it
5700 * it will return the proxy for the bound network for the caller app or the default proxy if
5701 * none.
5702 *
5703 * @param network the network we want to get the proxy information for.
5704 * @return Proxy information if a network has a proxy configured, or otherwise null.
5705 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005706 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005707 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005708 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005709 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005710 if (network == null) {
5711 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005712 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005713 true);
5714 if (activeNetwork == null) {
5715 return null;
5716 }
5717 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005718 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005719 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5720 // caller may not have.
5721 return getLinkPropertiesProxyInfo(network);
5722 }
5723 // No proxy info available if the calling UID does not have network access.
5724 return null;
5725 }
5726
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005727
5728 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005729 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5730 if (nai == null) return null;
5731 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005732 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5733 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005734 }
5735 }
5736
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005737 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005738 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005739 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005740 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005741 }
5742
Chalard Jean777e2e52018-06-07 18:02:37 +09005743 @Override
5744 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005745 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005746 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005747 }
5748
Jason Monk4d5e20f2014-04-25 15:00:09 -04005749 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005750 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005751 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005752 proxy = null;
5753 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005754 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005755 }
5756
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005757 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5758 // when any network changes proxy.
5759 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5760 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005761 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005762 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5763 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5764
Chalard Jean7d97afc2018-06-07 17:41:29 +09005765 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005766 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005767 }
5768 }
5769
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005770 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005771 final private HashMap<Uri, Integer> mUriEventMap;
5772 final private Context mContext;
5773 final private Handler mHandler;
5774
5775 SettingsObserver(Context context, Handler handler) {
5776 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005777 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005778 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005779 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005780 }
5781
Erik Kline05f2b402015-04-30 12:58:40 +09005782 void observe(Uri uri, int what) {
5783 mUriEventMap.put(uri, what);
5784 final ContentResolver resolver = mContext.getContentResolver();
5785 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005786 }
5787
5788 @Override
5789 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005790 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005791 }
5792
5793 @Override
5794 public void onChange(boolean selfChange, Uri uri) {
5795 final Integer what = mUriEventMap.get(uri);
5796 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005797 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005798 } else {
5799 loge("No matching event to send for URI=" + uri);
5800 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005801 }
5802 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005803
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005804 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005805 Log.d(TAG, s);
5806 }
5807
5808 private static void logw(String s) {
5809 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005810 }
5811
Daniel Brightf9e945b2020-06-15 16:10:01 -07005812 private static void logwtf(String s) {
5813 Log.wtf(TAG, s);
5814 }
5815
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005816 private static void logwtf(String s, Throwable t) {
5817 Log.wtf(TAG, s, t);
5818 }
5819
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005820 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005821 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005822 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005823
Hugo Benichi39621362017-02-11 17:04:43 +09005824 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005825 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005826 }
5827
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005828 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005829 * Return the information of all ongoing VPNs.
5830 *
5831 * <p>This method is used to update NetworkStatsService.
5832 *
5833 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005834 */
junyulai2050bed2021-01-23 09:46:34 +08005835 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005836 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005837 if (mLockdownEnabled) {
5838 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005839 }
junyulai2050bed2021-01-23 09:46:34 +08005840 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005841 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005842 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005843 if (info != null) {
5844 infoList.add(info);
5845 }
5846 }
junyulai2050bed2021-01-23 09:46:34 +08005847 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005848 }
5849
5850 /**
5851 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005852 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005853 */
junyulai2050bed2021-01-23 09:46:34 +08005854 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005855 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005856 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5857 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005858 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5859 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5860 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005861 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5862 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005863 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005864 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005865 }
5866 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005867
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005868 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005869
5870 List<String> interfaces = new ArrayList<>();
5871 for (Network network : underlyingNetworks) {
5872 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5873 if (underlyingNai == null) continue;
5874 LinkProperties lp = underlyingNai.linkProperties;
5875 for (String iface : lp.getAllInterfaceNames()) {
5876 if (!TextUtils.isEmpty(iface)) {
5877 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005878 }
5879 }
Benedict Wong34857f82019-06-12 17:46:15 +00005880 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005881
5882 if (interfaces.isEmpty()) return null;
5883
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005884 // Must be non-null or NetworkStatsService will crash.
5885 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5886 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005887 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005888 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005889
junyulai2050bed2021-01-23 09:46:34 +08005890 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5891 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005892 }
5893
James Mattisd31bdfa2020-12-23 16:37:26 -08005894 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005895 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5896 Network[] underlyingNetworks) {
5897 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005898 if (underlyingNetworks == null && defaultNetwork != null) {
5899 // null underlying networks means to track the default.
5900 underlyingNetworks = new Network[] { defaultNetwork };
5901 }
5902 return underlyingNetworks;
5903 }
5904
5905 // Returns true iff |network| is an underlying network of |nai|.
5906 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5907 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5908 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005909 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005910 final Network[] underlying = underlyingNetworksOrDefault(
5911 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005912 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005913 }
5914
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005915 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005916 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005917 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005918 * When underlying networks change, such networks may have to update capabilities to reflect
5919 * things like the metered bit, their transports, and so on. The capabilities are calculated
5920 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005921 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005922 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005923 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005924 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005925 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005926 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005927 }
5928 }
5929 }
5930
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005931 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5932 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5933 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5934 // a VPN is not up.
5935 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5936 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5937 for (UidRange range : blockedUidRanges) {
5938 if (range.contains(uid)) return true;
5939 }
5940 return false;
5941 }
5942
5943 @Override
5944 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005945 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005946 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5947 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5948 }
5949
5950 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5951 if (DBG) {
5952 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5953 + Arrays.toString(ranges));
5954 }
5955 // Cannot use a Set since the list of UID ranges might contain duplicates.
5956 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5957 for (int i = 0; i < ranges.length; i++) {
5958 if (requireVpn) {
5959 newVpnBlockedUidRanges.add(ranges[i]);
5960 } else {
5961 newVpnBlockedUidRanges.remove(ranges[i]);
5962 }
5963 }
5964
5965 try {
5966 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5967 } catch (RemoteException | ServiceSpecificException e) {
5968 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5969 + Arrays.toString(ranges) + "): netd command failed: " + e);
5970 }
5971
Motomu Utsumib08654c2022-05-11 05:56:26 +00005972 if (SdkLevel.isAtLeastT()) {
5973 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5974 }
5975
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005976 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5977 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005978 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5979 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005980 }
5981
5982 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5983 }
5984
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005985 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005986 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005987 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005988 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005989 }
5990
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005991 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5992 return mLockdownEnabled
5993 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5994 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005995 }
5996
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005997 private NetworkAgentInfo getLegacyLockdownNai() {
5998 if (!mLockdownEnabled) {
5999 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006000 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006001 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006002 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6003 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006004
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006005 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006006 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6007 // a local variable. There is no need to make a copy because its contents cannot change.
6008 final Network[] underlying = nai.declaredUnderlyingNetworks;
6009 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006010 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006011 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006012
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006013 // The legacy lockdown VPN always uses the default network.
6014 // If the VPN's underlying network is no longer the current default network, it means that
6015 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006016 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6017 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006018 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006019 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006020 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006021 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006022
6023 return nai;
6024 };
6025
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006026 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6027 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6028 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006029 private DetailedState getLegacyLockdownState(DetailedState origState) {
6030 if (origState != DetailedState.CONNECTED) {
6031 return origState;
6032 }
6033 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6034 ? DetailedState.CONNECTING
6035 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006036 }
6037
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006038 private void filterForLegacyLockdown(NetworkInfo ni) {
6039 if (!mLockdownEnabled || !ni.isConnected()) return;
6040 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6041 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6042 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6043 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6044 // network, this time with a state of CONNECTED.
6045 //
6046 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6047 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6048 // is not too far off the truth, since an always-on VPN, when not connected, is always
6049 // trying to reconnect.
6050 if (getLegacyLockdownNai() == null) {
6051 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6052 }
6053 }
6054
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006055 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006056 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006057 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006058 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006059 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6060 return;
6061 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006062 final long ident = Binder.clearCallingIdentity();
6063 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006064 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006065 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006066 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006067 } finally {
6068 Binder.restoreCallingIdentity(ident);
6069 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006070 }
Wink Savillecb117d32013-08-29 14:57:08 -07006071
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006072 @Override
6073 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006074 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006075 final long ident = Binder.clearCallingIdentity();
6076 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006077 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006078 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006079 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6080 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006081 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006082 } finally {
6083 Binder.restoreCallingIdentity(ident);
6084 }
6085 }
6086
James Mattis02220e22021-03-13 19:27:21 -08006087 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006088 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006089 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6090 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6091 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006092 }
6093
James Mattis02220e22021-03-13 19:27:21 -08006094 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006095 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006096 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006097 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006098 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006099 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006100 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6101 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6102 }
junyulaid91e7052020-08-28 13:44:33 +08006103 }
6104
James Mattis02220e22021-03-13 19:27:21 -08006105 private void onPackageChanged(@NonNull final String packageName) {
6106 // This is necessary in case a package is added or removed, but also when it's replaced to
6107 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6108 // as one in the preferences, then it should follow the same routing as that other package,
6109 // which means updating the rules is never to be needed in this case (whether it joins or
6110 // leaves a UID with a preference).
6111 if (isMappedInOemNetworkPreference(packageName)) {
6112 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6113 }
6114 }
6115
6116 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006117 @Override
6118 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006119 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006120 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006121 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006122
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006123 // User should be filled for below intents, check the existence.
6124 if (user == null) {
6125 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6126 return;
6127 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006128
Lorenzo Colitticd675292021-02-04 17:32:07 +09006129 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006130 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006131 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006132 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006133 } else {
junyulaid91e7052020-08-28 13:44:33 +08006134 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006135 }
6136 }
6137 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006138
James Mattis02220e22021-03-13 19:27:21 -08006139 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6140 @Override
6141 public void onReceive(Context context, Intent intent) {
6142 ensureRunningOnConnectivityServiceThread();
6143 switch (intent.getAction()) {
6144 case Intent.ACTION_PACKAGE_ADDED:
6145 case Intent.ACTION_PACKAGE_REMOVED:
6146 case Intent.ACTION_PACKAGE_REPLACED:
6147 onPackageChanged(intent.getData().getSchemeSpecificPart());
6148 break;
6149 default:
6150 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6151 }
6152 }
6153 };
6154
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006155 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006156 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006157
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006158 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006159 public final String name;
6160 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006161 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006162 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006163
lifraf3a3492021-03-10 13:58:14 +08006164 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6165 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006166 this.name = name;
6167 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006168 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006169 mDeathRecipient = deathRecipient;
6170
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006171 if (mDeathRecipient == null) {
6172 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006173 }
6174 }
6175
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006176 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006177 try {
6178 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6179 } catch (RemoteException e) {
6180 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006181 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006182 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006183 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006184
James Mattis4fce5d12020-11-12 15:53:42 -08006185 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6186 for (int i = 0; i < requests.size(); i++) {
6187 ensureNetworkRequestHasType(requests.get(i));
6188 }
6189 }
6190
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006191 private void ensureNetworkRequestHasType(NetworkRequest request) {
6192 if (request.type == NetworkRequest.Type.NONE) {
6193 throw new IllegalArgumentException(
6194 "All NetworkRequests in ConnectivityService must have a type");
6195 }
6196 }
6197
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006198 /**
6199 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006200 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006201 */
James Mattis258ea3c2020-11-15 15:04:40 -08006202 @VisibleForTesting
6203 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006204 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6205 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006206 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006207
James Mattisa076c532020-12-02 14:12:41 -08006208 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6209 void setSatisfier(
6210 @Nullable final NetworkAgentInfo satisfier,
6211 @Nullable final NetworkRequest activeRequest) {
6212 mSatisfier = satisfier;
6213 mActiveRequest = activeRequest;
6214 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006215
James Mattisd31bdfa2020-12-23 16:37:26 -08006216 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006217 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006218 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006219 private NetworkAgentInfo mSatisfier;
6220 NetworkAgentInfo getSatisfier() {
6221 return mSatisfier;
6222 }
6223
6224 // The request in mRequests assigned to a network agent. This is null if none of the
6225 // requests in mRequests can be satisfied. This member has the constraint of only being
6226 // accessible on the handler thread.
6227 @Nullable
6228 private NetworkRequest mActiveRequest;
6229 NetworkRequest getActiveRequest() {
6230 return mActiveRequest;
6231 }
6232
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006233 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006234 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006235 @Nullable
6236 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006237
6238 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006239 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006240 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006241 final int mPid;
6242 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006243 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006244 @Nullable
6245 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006246
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006247 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006248 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006249
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006250 // Effective UID of this request. This is different from mUid when a privileged process
6251 // files a request on behalf of another UID. This UID is used to determine blocked status,
6252 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6253 // maximum limit of registered callbacks per UID.
6254 final int mAsUid;
6255
paulhu48291862021-07-14 14:53:57 +08006256 // Preference order of this request.
6257 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006258
James Mattis3ce3d3c2021-02-09 18:18:28 -08006259 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6260 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6261 // maintained for keying off of. This is only a concern when the original nri
6262 // mNetworkRequests changes which happens currently for apps that register callbacks to
6263 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6264 // that match the per-app default nri that currently tracks the calling app's uid so that
6265 // callbacks are fired at the appropriate time. When the callbacks fire,
6266 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6267 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6268 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6269 @NonNull
6270 private final NetworkRequest mNetworkRequestForCallback;
6271 NetworkRequest getNetworkRequestForCallback() {
6272 return mNetworkRequestForCallback;
6273 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006274
James Mattisd31bdfa2020-12-23 16:37:26 -08006275 /**
6276 * Get the list of UIDs this nri applies to.
6277 */
6278 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006279 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006280 // networkCapabilities.getUids() returns a defensive copy.
6281 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006282 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6283 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006284 }
6285
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006286 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6287 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006288 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006289 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006290 }
6291
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006292 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006293 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006294 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006295 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006296 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006297 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006298 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006299 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006300 mBinder = null;
6301 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006302 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006303 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006304 mPerUidCounter = getRequestCounter(this);
6305 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006306 /**
6307 * Location sensitive data not included in pending intent. Only included in
6308 * {@link NetworkCallback}.
6309 */
6310 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006311 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006312 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006313 }
6314
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006315 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006316 @Nullable final IBinder binder,
6317 @NetworkCallback.Flag int callbackFlags,
6318 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006319 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6320 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006321 }
6322
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006323 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006324 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006325 @Nullable final IBinder binder,
6326 @NetworkCallback.Flag int callbackFlags,
6327 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006328 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006329 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006330 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006331 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006332 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006333 mBinder = binder;
6334 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006335 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006336 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006337 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006338 mPerUidCounter = getRequestCounter(this);
6339 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006340 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006341 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006342 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006343 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006344 }
6345
James Mattis3ce3d3c2021-02-09 18:18:28 -08006346 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6347 @NonNull final List<NetworkRequest> r) {
6348 super();
6349 ensureAllNetworkRequestsHaveType(r);
6350 mRequests = initializeRequests(r);
6351 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006352 final NetworkAgentInfo satisfier = nri.getSatisfier();
6353 if (null != satisfier) {
6354 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6355 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006356 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006357 // As this code creates a new NRI with a new set of requests, figure out which of
6358 // the list of requests should be the active request. It is always the first
6359 // request of the list that can be satisfied by the satisfier since the order of
6360 // requests is a priority order.
6361 // Note even in the presence of a satisfier there may not be an active request,
6362 // when the satisfier is the no-service network.
6363 NetworkRequest activeRequest = null;
6364 for (final NetworkRequest candidate : r) {
6365 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6366 activeRequest = candidate;
6367 break;
6368 }
6369 }
6370 setSatisfier(satisfier, activeRequest);
6371 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006372 mMessenger = nri.mMessenger;
6373 mBinder = nri.mBinder;
6374 mPid = nri.mPid;
6375 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006376 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006377 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006378 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006379 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006380 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006381 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006382 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006383 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006384 }
6385
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006386 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006387 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006388 }
6389
paulhue9913722021-05-26 15:19:20 +08006390 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006391 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006392 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006393 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006394 }
6395
James Mattis2516da32021-01-31 17:06:19 -08006396 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6397 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6398 // false.
6399 boolean isBeingSatisfied() {
6400 return (null != mSatisfier && null != mActiveRequest);
6401 }
6402
James Mattis3d229892020-11-16 16:46:28 -08006403 boolean isMultilayerRequest() {
6404 return mRequests.size() > 1;
6405 }
6406
James Mattis45d81842021-01-10 14:24:24 -08006407 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6408 // Creating a defensive copy to prevent the sender from modifying the list being
6409 // reflected in the return value of this method.
6410 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006411 return Collections.unmodifiableList(tempRequests);
6412 }
6413
James Mattisb1392002021-03-31 13:57:52 -07006414 void linkDeathRecipient() {
6415 if (null != mBinder) {
6416 try {
6417 mBinder.linkToDeath(this, 0);
6418 } catch (RemoteException e) {
6419 binderDied();
6420 }
6421 }
6422 }
6423
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006424 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006425 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006426 try {
6427 mBinder.unlinkToDeath(this, 0);
6428 } catch (NoSuchElementException e) {
6429 // Temporary workaround for b/194394697 pending analysis of additional logs
6430 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6431 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006432 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006433 }
6434
paulhu48291862021-07-14 14:53:57 +08006435 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6436 // Compare two preference orders.
6437 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006438 }
6439
paulhu48291862021-07-14 14:53:57 +08006440 int getPreferenceOrderForNetd() {
6441 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6442 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6443 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006444 }
paulhu48291862021-07-14 14:53:57 +08006445 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006446 }
6447
James Mattis4fce5d12020-11-12 15:53:42 -08006448 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006449 public void binderDied() {
6450 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006451 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006452 // As an immutable collection, mRequests cannot change by the time the
6453 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6454 // is acceptable. Use handleReleaseNetworkRequest and not directly
6455 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6456 // the app already unregistered the request.
6457 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6458 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006459 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006460
James Mattis4fce5d12020-11-12 15:53:42 -08006461 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006462 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006463 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6464 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006465 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006466 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006467 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006468 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006469 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006470 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006471 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006472 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006473 }
6474
Junyu Lai00d92df2022-07-05 11:01:52 +08006475 // Keep backward compatibility since the ServiceSpecificException is used by
6476 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6477 public static class RequestInfoPerUidCounter extends PerUidCounter {
6478 RequestInfoPerUidCounter(int maxCountPerUid) {
6479 super(maxCountPerUid);
6480 }
6481
6482 @Override
6483 public synchronized void incrementCountOrThrow(int uid) {
6484 try {
6485 super.incrementCountOrThrow(uid);
6486 } catch (IllegalStateException e) {
6487 throw new ServiceSpecificException(
6488 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6489 "Uid " + uid + " exceeded its allotted requests limit");
6490 }
6491 }
6492
6493 @Override
6494 public synchronized void decrementCountOrThrow(int uid) {
6495 throw new UnsupportedOperationException("Use decrementCount instead.");
6496 }
6497
6498 public synchronized void decrementCount(int uid) {
6499 try {
6500 super.decrementCountOrThrow(uid);
6501 } catch (IllegalStateException e) {
6502 logwtf("Exception when decrement per uid request count: ", e);
6503 }
6504 }
6505 }
6506
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006507 // This checks that the passed capabilities either do not request a
6508 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006509 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006510 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006511 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006512 throw new SecurityException("Insufficient permissions to request a specific SSID");
6513 }
paulhu1a407652019-03-22 16:35:06 +08006514
6515 if (nc.hasSignalStrength()
6516 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6517 throw new SecurityException(
6518 "Insufficient permissions to request a specific signal strength");
6519 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006520 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006521
junyulai2217bec2021-04-14 23:33:31 +08006522 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006523 enforceNetworkFactoryPermission();
6524 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006525 }
6526
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006527 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006528 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006529 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006530 // mNetworkRequests may contain the same value multiple times in case of
6531 // multilayer requests. It won't matter in this case because the thresholds
6532 // will then be the same and be deduplicated as they enter the `thresholds` set.
6533 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006534 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6535 for (final NetworkRequest req : nri.mRequests) {
6536 if (req.networkCapabilities.hasSignalStrength()
6537 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6538 thresholds.add(req.networkCapabilities.getSignalStrength());
6539 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006540 }
6541 }
6542 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006543 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006544 }
6545
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006546 private void updateSignalStrengthThresholds(
6547 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006548 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006549
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006550 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006551 String detail;
6552 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6553 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6554 } else {
6555 detail = reason;
6556 }
6557 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006558 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006559 }
6560
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006561 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006562 }
6563
Chalard Jeandd421992021-12-16 23:16:02 +09006564 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006565 if (nc == null) {
6566 return;
6567 }
6568 NetworkSpecifier ns = nc.getNetworkSpecifier();
6569 if (ns == null) {
6570 return;
6571 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006572 if (ns instanceof MatchAllNetworkSpecifier) {
6573 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6574 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006575 }
6576
Chalard Jeandd421992021-12-16 23:16:02 +09006577 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006578 ensureValidNetworkSpecifier(nc);
6579 if (nc.isPrivateDnsBroken()) {
6580 throw new IllegalArgumentException("Can't request broken private DNS");
6581 }
Chalard Jeande665262022-02-25 16:12:12 +09006582 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006583 throw new IllegalArgumentException("Can't request access UIDs");
6584 }
lucasline117e2e2019-10-22 18:27:33 +08006585 }
6586
Chalard Jeandd421992021-12-16 23:16:02 +09006587 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6588 ensureListenableCapabilities(nc);
6589 final String badCapability = nc.describeFirstNonRequestableCapability();
6590 if (badCapability != null) {
6591 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6592 }
6593 }
6594
Chiachang Wang3bc52762021-11-25 14:17:57 +08006595 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6596 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006597 private boolean isTargetSdkAtleast(int version, int callingUid,
6598 @NonNull String callingPackageName) {
6599 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006600 final PackageManager pm =
6601 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006602 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006603 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006604 if (callingVersion < version) return false;
6605 } catch (PackageManager.NameNotFoundException e) { }
6606 return true;
6607 }
6608
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006609 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006610 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006611 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006612 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006613 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006614 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006615 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6616 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006617 throw new SecurityException("Insufficient permissions to specify legacy type");
6618 }
markchienfac84a22020-03-18 21:16:15 +08006619 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006620 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006621 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006622 // Privileged callers can track the default network of another UID by passing in a UID.
6623 if (asUid != Process.INVALID_UID) {
6624 enforceSettingsPermission();
6625 } else {
6626 asUid = callingUid;
6627 }
junyulaiad010792021-01-11 16:53:38 +08006628 final NetworkRequest.Type reqType;
6629 try {
6630 reqType = NetworkRequest.Type.values()[reqTypeInt];
6631 } catch (ArrayIndexOutOfBoundsException e) {
6632 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6633 }
6634 switch (reqType) {
6635 case TRACK_DEFAULT:
6636 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006637 // is unused and will be replaced by ones appropriate for the UID (usually, the
6638 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006639 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006640 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006641 enforceAccessPermission();
6642 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006643 case TRACK_SYSTEM_DEFAULT:
6644 enforceSettingsPermission();
6645 networkCapabilities = new NetworkCapabilities(defaultNc);
6646 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006647 case BACKGROUND_REQUEST:
6648 enforceNetworkStackOrSettingsPermission();
6649 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006650 case REQUEST:
6651 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6652 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006653 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006654 // TODO: this is incorrect. We mark the request as metered or not depending on
6655 // the state of the app when the request is filed, but we never change the
6656 // request if the app changes network state. http://b/29964605
6657 enforceMeteredApnPolicy(networkCapabilities);
6658 break;
junyulai1b1c8742021-03-12 20:05:08 +08006659 case LISTEN_FOR_BEST:
6660 enforceAccessPermission();
6661 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6662 break;
junyulaiad010792021-01-11 16:53:38 +08006663 default:
6664 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006665 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006666 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006667 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006668 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006669
junyulai1b1c8742021-03-12 20:05:08 +08006670 // Enforce FOREGROUND if the caller does not have permission to use background network.
6671 if (reqType == LISTEN_FOR_BEST) {
6672 restrictBackgroundRequestForCaller(networkCapabilities);
6673 }
6674
6675 // Set the UID range for this request to the single UID of the requester, unless the
6676 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006677 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6678 // are no visible methods to set the UIDs, an app could use reflection to try and get
6679 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006680 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006681 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6682 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006683
Etan Cohen85000162017-02-05 10:42:27 -08006684 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006685 throw new IllegalArgumentException("Bad timeout specified");
6686 }
Etan Cohen9786d922015-11-18 10:56:15 -08006687
James Mattis3ce3d3c2021-02-09 18:18:28 -08006688 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006689 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006690 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006691 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006692 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006693 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006694
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006695 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6696 // copied from the default request above. (This is necessary to ensure, for example, that
6697 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6698 // changes don't alter request matching.
6699 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6700 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006701 throw new IllegalStateException(
6702 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006703 + networkCapabilities + " vs. " + defaultNc);
6704 }
6705
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006707 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006708 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006709 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006710 }
6711 return networkRequest;
6712 }
6713
James Mattis3ce3d3c2021-02-09 18:18:28 -08006714 /**
6715 * Return the nri to be used when registering a network request. Specifically, this is used with
6716 * requests registered to track the default request. If there is currently a per-app default
6717 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6718 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006719 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6720 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006721 * @param nr the network request for the nri.
6722 * @param msgr the messenger for the nri.
6723 * @param binder the binder for the nri.
6724 * @param callingAttributionTag the calling attribution tag for the nri.
6725 * @return the nri to register.
6726 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006727 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006728 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006729 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006730 @Nullable String callingAttributionTag) {
6731 final List<NetworkRequest> requests;
6732 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6733 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006734 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006735 } else {
6736 requests = Collections.singletonList(nr);
6737 }
Roshan Pius951c0032020-12-22 15:10:42 -08006738 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006739 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006740 }
6741
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006742 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006743 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006744 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006745 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6746 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6747 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6748 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006749 }
junyulai96bd9fe2022-03-08 17:36:42 +08006750 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006751 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006752 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006753 }
6754 }
6755
fenglu3f357402015-03-20 11:29:56 -07006756 @Override
fenglub00f4882015-04-21 17:12:05 -07006757 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006758 enforceAccessPermission();
6759 NetworkAgentInfo nai = null;
6760 if (network == null) {
6761 return false;
6762 }
6763 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006764 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006765 }
6766 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006767 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006768 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006769 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006770 Integer uidReqs = mBandwidthRequests.get(uid);
6771 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006772 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006773 }
6774 mBandwidthRequests.put(uid, ++uidReqs);
6775 }
fenglu3f357402015-03-20 11:29:56 -07006776 return true;
6777 }
6778 return false;
6779 }
6780
Felipe Leme0a5ae422016-06-20 16:36:29 -07006781 private boolean isSystem(int uid) {
6782 return uid < Process.FIRST_APPLICATION_UID;
6783 }
fenglu3f357402015-03-20 11:29:56 -07006784
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006785 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006786 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006787 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006788 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006789 return;
6790 }
Hugo Benichi39621362017-02-11 17:04:43 +09006791 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6792 // Policy already enforced.
6793 return;
6794 }
paulhuaf50d7d2020-12-24 19:47:34 +08006795 final long ident = Binder.clearCallingIdentity();
6796 try {
6797 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6798 // If UID is restricted, don't allow them to bring up metered APNs.
6799 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6800 }
6801 } finally {
6802 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006803 }
6804 }
6805
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006806 @Override
6807 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006808 PendingIntent operation, @NonNull String callingPackageName,
6809 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006810 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006811 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006812 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006813 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006814 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006815 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006816 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006817 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006818 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006819 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6820 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006821
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006822 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006823 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006824 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6825 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006826 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006827 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6828 nri));
6829 return networkRequest;
6830 }
6831
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006832 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6833 mHandler.sendMessageDelayed(
6834 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006835 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006836 }
6837
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006838 @Override
6839 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006840 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006841 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006842 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006843 }
6844
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006845 // In order to implement the compatibility measure for pre-M apps that call
6846 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6847 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6848 // This ensures it has permission to do so.
6849 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6850 if (nc == null) {
6851 return false;
6852 }
6853 int[] transportTypes = nc.getTransportTypes();
6854 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6855 return false;
6856 }
6857 try {
6858 mContext.enforceCallingOrSelfPermission(
6859 android.Manifest.permission.ACCESS_WIFI_STATE,
6860 "ConnectivityService");
6861 } catch (SecurityException e) {
6862 return false;
6863 }
6864 return true;
6865 }
6866
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006867 @Override
6868 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006869 Messenger messenger, IBinder binder,
6870 @NetworkCallback.Flag int callbackFlags,
6871 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006872 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006873 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6874 enforceAccessPermission();
6875 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006876
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006877 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006878 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006879 Binder.getCallingPid(), callingUid, callingPackageName);
6880 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006881 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6882 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6883 // onLost and onAvailable callbacks when networks move in and out of the background.
6884 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6885 // can't request networks.
6886 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006887 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006888
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006889 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006890 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006891 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006892 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006893 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006894 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006895
6896 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6897 return networkRequest;
6898 }
6899
6900 @Override
6901 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006902 PendingIntent operation, @NonNull String callingPackageName,
6903 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006904 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006905 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006906 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6907 enforceAccessPermission();
6908 }
Chalard Jeandd421992021-12-16 23:16:02 +09006909 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006910 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006911 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006912 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006913 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006914
6915 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006916 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006917 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6918 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006919 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006920
WeiZhang1cc3f172021-06-03 19:02:04 -05006921 mHandler.sendMessage(mHandler.obtainMessage(
6922 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006923 }
6924
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006925 /** Returns the next Network provider ID. */
6926 public final int nextNetworkProviderId() {
6927 return mNextNetworkProviderId.getAndIncrement();
6928 }
6929
Erik Kline0c04b742016-07-07 16:50:58 +09006930 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006931 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006932 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006933 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006934 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006935 }
6936
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006937 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6938 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006939 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6940 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6941 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006942 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006943 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006944 return;
6945 }
6946
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006947 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6948 mNetworkProviderInfos.put(npi.messenger, npi);
6949 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006950 }
6951
6952 @Override
6953 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006954 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006955 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006956 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006957 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006958 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6959 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006960 }
6961
6962 @Override
6963 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006964 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006965 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006966 }
6967
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006968 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006969 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006970 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6971 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006972 Objects.requireNonNull(score);
6973 Objects.requireNonNull(caps);
6974 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006975 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006976 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006977 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6978 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006979 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6980 }
6981
Chalard Jeanbb902a52021-08-18 01:35:19 +09006982 private void updateOfferScore(final NetworkOffer offer) {
6983 final boolean yieldToBadWiFi =
6984 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6985 final NetworkOffer newOffer = new NetworkOffer(
6986 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6987 offer.caps, offer.callback, offer.providerId);
6988 if (offer.equals(newOffer)) return;
6989 handleRegisterNetworkOffer(newOffer);
6990 }
6991
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006992 @Override
6993 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006994 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006995 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6996 }
6997
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006998 private void handleUnregisterNetworkProvider(Messenger messenger) {
6999 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7000 if (npi == null) {
7001 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007002 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007003 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007004 // Unregister all the offers from this provider
7005 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7006 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007007 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007008 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7009 toRemove.add(noi);
7010 }
7011 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007012 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007013 handleUnregisterNetworkOffer(noi);
7014 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007015 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007016 }
7017
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007018 @Override
James Mattisf7027322020-12-13 16:28:14 -08007019 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007020 if (request.hasTransport(TRANSPORT_TEST)) {
7021 enforceNetworkFactoryOrTestNetworksPermission();
7022 } else {
7023 enforceNetworkFactoryPermission();
7024 }
James Mattisf7027322020-12-13 16:28:14 -08007025 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7026 if (nri != null) {
7027 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7028 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7029 mHandler.post(() -> handleReleaseNetworkRequest(
7030 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7031 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007032 }
7033
Paul Jensen1f567382015-02-13 14:18:39 -05007034 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7035 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007036 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007037 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007038 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007039 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007040 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007041
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007042 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007043 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007044 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007045
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007046 // UID ranges for users that are currently blocked by VPNs.
7047 // This array is accessed and iterated on multiple threads without holding locks, so its
7048 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7049 // (on the handler thread).
7050 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7051
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007052 // Must only be accessed on the handler thread
7053 @NonNull
7054 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7055
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007056 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007057 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007058
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007059 // Current OEM network preferences. This object must only be written to on the handler thread.
7060 // Since it is immutable and always non-null, other threads may read it if they only care
7061 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007062 @NonNull
7063 private OemNetworkPreferences mOemNetworkPreferences =
7064 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007065 // Current per-profile network preferences. This object follows the same threading rules as
7066 // the OEM network preferences above.
7067 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007068 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7069 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007070
paulhu51f77dc2021-06-07 02:34:20 +00007071 // A set of UIDs that should use mobile data preferentially if available. This object follows
7072 // the same threading rules as the OEM network preferences above.
7073 @NonNull
7074 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7075
James Mattiscb1e0362021-04-06 17:07:42 -07007076 // OemNetworkPreferences activity String log entries.
7077 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7078 @NonNull
7079 private final LocalLog mOemNetworkPreferencesLogs =
7080 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7081
James Mattis02220e22021-03-13 19:27:21 -08007082 /**
7083 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7084 * @param packageName the package name to check existence of a mapping for.
7085 * @return true if a mapping exists, false otherwise
7086 */
7087 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7088 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7089 }
7090
James Mattise3ef1912020-12-20 11:09:58 -08007091 // The always-on request for an Internet-capable network that apps without a specific default
7092 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007093 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007094 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007095 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007096 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007097 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007098 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007099 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007100
James Mattisd31bdfa2020-12-23 16:37:26 -08007101 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7102 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7103 }
7104
7105 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007106 * Return the default network request currently tracking the given uid.
7107 * @param uid the uid to check.
7108 * @return the NetworkRequestInfo tracking the given uid.
7109 */
7110 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007111 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007112 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007113 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007114 // Checking the first request is sufficient as only multilayer requests will have more
7115 // than one request and for multilayer, all requests will track the same uids.
7116 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007117 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007118 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007119 highestPriorityNri = nri;
7120 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007121 }
7122 }
paulhuaa0743d2021-05-26 21:56:03 +08007123 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007124 }
7125
7126 /**
7127 * Get a copy of the network requests of the default request that is currently tracking the
7128 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007129 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7130 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007131 * @param requestorUid the uid to check the default for.
7132 * @param requestorPackageName the requestor's package name.
7133 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7134 */
7135 @NonNull
7136 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007137 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007138 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007139 getDefaultRequestTrackingUid(asUid).mRequests,
7140 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007141 }
7142
7143 /**
7144 * Copy the given nri's NetworkRequest collection.
7145 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007146 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7147 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007148 * @param requestorUid the uid to set on the copied collection.
7149 * @param requestorPackageName the package name to set on the copied collection.
7150 * @return the copied NetworkRequest collection.
7151 */
7152 @NonNull
7153 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007154 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7155 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007156 final List<NetworkRequest> requests = new ArrayList<>();
7157 for (final NetworkRequest nr : requestsToCopy) {
7158 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007159 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007160 nr.legacyType, nextNetworkRequestId(), nr.type));
7161 }
7162 return requests;
7163 }
7164
7165 @NonNull
7166 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007167 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7168 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007169 // These capabilities are for a TRACK_DEFAULT callback, so:
7170 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7171 // mDefaultRequest and a per-UID default request.
7172 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007173 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007174 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007175 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7176 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007177 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007178 restrictRequestUidsForCallerAndSetRequestorInfo(
7179 netCap, requestorUid, requestorPackageName);
7180 return netCap;
7181 }
7182
7183 /**
7184 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7185 * @param nr the network request to check for equality against.
7186 * @return the nri if one exists, null otherwise.
7187 */
7188 @Nullable
7189 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7190 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7191 if (nri.getNetworkRequestForCallback().equals(nr)) {
7192 return nri;
7193 }
7194 }
7195 return null;
7196 }
7197
7198 /**
7199 * Check if an nri is currently being managed by per-app default networking.
7200 * @param nri the nri to check.
7201 * @return true if this nri is currently being managed by per-app default networking.
7202 */
7203 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7204 // nri.mRequests.get(0) is only different from the original request filed in
7205 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7206 // functionality therefore if these two don't match, it means this particular nri is
7207 // currently being managed by a per-app default.
7208 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7209 }
7210
7211 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007212 * Determine if an nri is a managed default request that disallows default networking.
7213 * @param nri the request to evaluate
7214 * @return true if device-default networking is disallowed
7215 */
7216 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7217 // Check if this nri is a managed default that supports the default network at its
7218 // lowest priority request.
7219 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7220 final NetworkCapabilities lowestPriorityNetCap =
7221 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7222 return isPerAppDefaultRequest(nri)
7223 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7224 lowestPriorityNetCap));
7225 }
7226
Erik Kline05f2b402015-04-30 12:58:40 +09007227 // Request used to optionally keep mobile data active even when higher
7228 // priority networks like Wi-Fi are active.
7229 private final NetworkRequest mDefaultMobileDataRequest;
7230
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007231 // Request used to optionally keep wifi data active even when higher
7232 // priority networks like ethernet are active.
7233 private final NetworkRequest mDefaultWifiRequest;
7234
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007235 // Request used to optionally keep vehicle internal network always active
7236 private final NetworkRequest mDefaultVehicleRequest;
7237
James Mattisd31bdfa2020-12-23 16:37:26 -08007238 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7239 // network with no service. This NAI should never be matched against, nor should any public API
7240 // ever return the associated network. For this reason, this NAI is not in the list of available
7241 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7242 // default requests that don't support using the device default network which will ultimately
7243 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7244 @VisibleForTesting
7245 final NetworkAgentInfo mNoServiceNetwork;
7246
Chalard Jean5b409c72021-02-04 13:12:59 +09007247 // The NetworkAgentInfo currently satisfying the default request, if any.
7248 private NetworkAgentInfo getDefaultNetwork() {
7249 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007250 }
7251
James Mattis2516da32021-01-31 17:06:19 -08007252 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007253 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007254 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7255 // Currently, all network requests will have the same uids therefore checking the first
7256 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007257 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007258 if (null == uids) {
7259 continue;
7260 }
7261 for (final UidRange range : uids) {
7262 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007263 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007264 highestPriorityNri = nri;
7265 }
James Mattis2516da32021-01-31 17:06:19 -08007266 }
7267 }
7268 }
paulhuaa0743d2021-05-26 21:56:03 +08007269 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007270 }
7271
Varun Ananddf569952019-02-06 10:13:38 -08007272 @Nullable
7273 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7274 return nai != null ? nai.network : null;
7275 }
7276
7277 private void ensureRunningOnConnectivityServiceThread() {
7278 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7279 throw new IllegalStateException(
7280 "Not running on ConnectivityService thread: "
7281 + Thread.currentThread().getName());
7282 }
7283 }
7284
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007285 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007286 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7287 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007288 }
7289
Chalard Jean29d06db2018-05-02 21:14:54 +09007290 /**
7291 * Register a new agent with ConnectivityService to handle a network.
7292 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007293 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007294 * @param networkInfo the initial info associated with this network. It can be updated later :
7295 * see {@link #updateNetworkInfo}.
7296 * @param linkProperties the initial link properties of this network. They can be updated
7297 * later : see {@link #updateLinkProperties}.
7298 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007299 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007300 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007301 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007302 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007303 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007304 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007305 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007306 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007307 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7308 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007309 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7310 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7311 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007312 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007313 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007314 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007315 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007316 } else {
7317 enforceNetworkFactoryPermission();
7318 }
7319
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007320 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007321 final long token = Binder.clearCallingIdentity();
7322 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007323 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007324 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007325 } finally {
7326 Binder.restoreCallingIdentity(token);
7327 }
7328 }
7329
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007330 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007331 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007332 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7333 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007334
Chalard Jeandbc46952022-02-02 00:14:18 +09007335 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7336 // and mutate them at any time.
7337 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7338 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7339 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7340
Chalard Jean366c5252022-01-25 18:27:53 +09007341 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007342 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007343 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7344 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007345 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007346 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007347 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007348 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7349 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007350
Chalard Jeandbc46952022-02-02 00:14:18 +09007351 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007352 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007353 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007354 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007355 mDeps.getNetworkStack().makeNetworkMonitor(
7356 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007357 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7358 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007359 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007360 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007361 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007362 }
7363
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007364 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007365 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007366 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007367 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007368 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007369 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7370 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7371 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007372
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007373 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007374
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007375 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007376 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007377 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007378 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007379
7380 try {
7381 networkMonitor.start();
7382 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007383 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007384 }
Chalard Jean366c5252022-01-25 18:27:53 +09007385
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007386 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007387 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007388 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007389 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007390 }
7391
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007392 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7393 @NonNull public final NetworkOffer offer;
7394
7395 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7396 this.offer = offer;
7397 }
7398
7399 @Override
7400 public void binderDied() {
7401 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7402 }
7403 }
7404
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007405 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7406 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7407 if (npi.providerId == providerId) return true;
7408 }
7409 return false;
7410 }
7411
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007412 /**
7413 * Register or update a network offer.
7414 * @param newOffer The new offer. If the callback member is the same as an existing
7415 * offer, it is an update of that offer.
7416 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007417 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007418 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7419 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007420 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007421 // This may actually happen if a provider updates its score or registers and then
7422 // immediately unregisters. The offer would still be in the handler queue, but the
7423 // provider would have been removed.
7424 if (DBG) log("Received offer from an unregistered provider");
7425 return;
7426 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007427 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7428 if (null != existingOffer) {
7429 handleUnregisterNetworkOffer(existingOffer);
7430 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007431 if (DBG) {
7432 // handleUnregisterNetworkOffer has already logged the old offer
7433 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7434 }
7435 } else {
7436 if (DBG) {
7437 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7438 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007439 }
7440 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7441 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007442 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007443 } catch (RemoteException e) {
7444 noi.binderDied();
7445 return;
7446 }
7447 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007448 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007449 }
7450
7451 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7452 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007453 if (DBG) {
7454 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7455 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007456
7457 // If the provider removes the offer and dies immediately afterwards this
7458 // function may be called twice in a row, but the array will no longer contain
7459 // the offer.
7460 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007461 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007462 }
7463
7464 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7465 @NonNull final INetworkOfferCallback callback) {
7466 ensureRunningOnConnectivityServiceThread();
7467 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007468 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007469 }
7470 return null;
7471 }
7472
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007473 /**
7474 * Called when receiving LinkProperties directly from a NetworkAgent.
7475 * Stores into |nai| any data coming from the agent that might also be written to the network's
7476 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7477 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007478 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007479 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007480 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7481 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007482 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007483 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007484 }
7485
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007486 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007487 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007488 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007489
Lorenzo Colittid523d142020-04-01 20:16:30 +09007490 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7491 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7492 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007493 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007494
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007495 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007496
7497 // update filtering rules, need to happen after the interface update so netd knows about the
7498 // new interface (the interface name -> index map becomes initialized)
7499 updateVpnFiltering(newLp, oldLp, networkAgent);
7500
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007501 updateMtu(newLp, oldLp);
7502 // TODO - figure out what to do for clat
7503// for (LinkProperties lp : newLp.getStackedLinks()) {
7504// updateMtu(lp, null);
7505// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007506 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007507 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7508 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007509
Erik Klineb9888902016-04-05 13:30:49 +09007510 updateRoutes(newLp, oldLp, netId);
7511 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007512 // Make sure LinkProperties represents the latest private DNS status.
7513 // This does not need to be done before updateDnses because the
7514 // LinkProperties are not the source of the private DNS configuration.
7515 // updateDnses will fetch the private DNS configuration from DnsManager.
7516 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007517
Chalard Jean5b409c72021-02-04 13:12:59 +09007518 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007519 handleApplyDefaultProxy(newLp.getHttpProxy());
7520 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007521 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007522 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007523
7524 updateWakeOnLan(newLp);
7525
Hai Shalome58bdc62021-01-11 18:45:34 -08007526 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7527 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7528 // does, it needs to be merged here.
7529 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7530 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007531
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007532 // TODO - move this check to cover the whole function
7533 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007534 synchronized (networkAgent) {
7535 networkAgent.linkProperties = newLp;
7536 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007537 // Start or stop DNS64 detection and 464xlat according to network state.
7538 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007539 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007540 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7541 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007542 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007543 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007544
7545 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007546 }
7547
Hai Shalome58bdc62021-01-11 18:45:34 -08007548 /**
7549 * @param naData captive portal data from NetworkAgent
7550 * @param apiData captive portal data from capport API
7551 */
7552 @Nullable
7553 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7554 CaptivePortalData apiData) {
7555 if (naData == null || apiData == null) {
7556 return naData == null ? apiData : naData;
7557 }
7558 final CaptivePortalData.Builder captivePortalBuilder =
7559 new CaptivePortalData.Builder(naData);
7560
7561 if (apiData.isCaptive()) {
7562 captivePortalBuilder.setCaptive(true);
7563 }
7564 if (apiData.isSessionExtendable()) {
7565 captivePortalBuilder.setSessionExtendable(true);
7566 }
7567 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7568 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7569 // otherwise data would be inconsistent. Prefer the capport API info if present,
7570 // as it can generally be refreshed more often.
7571 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7572 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7573 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7574 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7575 // No source has time / bytes remaining information: surface the newest refresh time
7576 // for other fields
7577 captivePortalBuilder.setRefreshTime(
7578 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7579 }
7580
Hai Shalom7c6ab402021-02-04 19:34:06 -08007581 // Prioritize the user portal URL from the network agent if the source is authenticated.
7582 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7583 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7584 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7585 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007586 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007587 // Prioritize the venue information URL from the network agent if the source is
7588 // authenticated.
7589 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7590 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7591 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7592 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007593 }
7594 return captivePortalBuilder.build();
7595 }
7596
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007597 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007598 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007599 // marks on unsupported interfaces is harmless.
7600 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7601 return;
7602 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007603
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007604 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7605 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7606
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007607 // Mask/mark of zero will not detect anything interesting.
7608 // Don't install rules unless both values are nonzero.
7609 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007610 return;
7611 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007612
7613 final String prefix = "iface:" + iface;
7614 try {
7615 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007616 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007617 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007618 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007619 }
7620 } catch (Exception e) {
7621 loge("Exception modifying wakeup packet monitoring: " + e);
7622 }
7623
Joel Scherpelza235a812017-05-22 13:47:41 +09007624 }
7625
Chalard Jean9589e722019-11-19 19:03:53 +09007626 private void updateInterfaces(final @Nullable LinkProperties newLp,
7627 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007628 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007629 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007630 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7631 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007632 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007633 for (final String iface : interfaceDiff.added) {
7634 try {
7635 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007636 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007637 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007638 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7639 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007640 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007641 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007642 }
Paul Jensenbff73492014-04-28 10:33:11 -04007643 }
7644 }
Chalard Jean9589e722019-11-19 19:03:53 +09007645 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007646 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007647 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007648 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007649 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007650 } catch (Exception e) {
7651 loge("Exception removing interface: " + e);
7652 }
7653 }
7654 }
7655
Tyler Weare4314862019-12-05 14:55:30 -08007656 // TODO: move to frameworks/libs/net.
7657 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7658 final String nextHop;
7659
7660 switch (route.getType()) {
7661 case RouteInfo.RTN_UNICAST:
7662 if (route.hasGateway()) {
7663 nextHop = route.getGateway().getHostAddress();
7664 } else {
7665 nextHop = INetd.NEXTHOP_NONE;
7666 }
7667 break;
7668 case RouteInfo.RTN_UNREACHABLE:
7669 nextHop = INetd.NEXTHOP_UNREACHABLE;
7670 break;
7671 case RouteInfo.RTN_THROW:
7672 nextHop = INetd.NEXTHOP_THROW;
7673 break;
7674 default:
7675 nextHop = INetd.NEXTHOP_NONE;
7676 break;
7677 }
7678
7679 final RouteInfoParcel rip = new RouteInfoParcel();
7680 rip.ifName = route.getInterface();
7681 rip.destination = route.getDestination().toString();
7682 rip.nextHop = nextHop;
7683 rip.mtu = route.getMtu();
7684
7685 return rip;
7686 }
7687
Paul Jensene0fd4a82014-08-06 15:51:33 -04007688 /**
7689 * Have netd update routes from oldLp to newLp.
7690 * @return true if routes changed between oldLp and newLp
7691 */
7692 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007693 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007694 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7695 new CompareOrUpdateResult<>(
7696 oldLp != null ? oldLp.getAllRoutes() : null,
7697 newLp != null ? newLp.getAllRoutes() : null,
7698 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007699
7700 // add routes before removing old in case it helps with continuous connectivity
7701
Chalard Jean9dd11612018-06-04 16:52:49 +09007702 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007703 for (RouteInfo route : routeDiff.added) {
7704 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007705 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007706 try {
Tyler Weare4314862019-12-05 14:55:30 -08007707 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007708 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007709 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007710 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007711 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007712 }
7713 }
7714 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007715 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007716 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007717 try {
Tyler Weare4314862019-12-05 14:55:30 -08007718 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007719 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007720 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007721 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007722 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007723 }
7724 }
7725
7726 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007727 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007728 try {
Tyler Weare4314862019-12-05 14:55:30 -08007729 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007730 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007731 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007732 }
7733 }
Tyler Weare4314862019-12-05 14:55:30 -08007734
7735 for (RouteInfo route : routeDiff.updated) {
7736 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7737 try {
7738 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7739 } catch (Exception e) {
7740 loge("Exception in networkUpdateRouteParcel: " + e);
7741 }
7742 }
7743 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7744 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007745 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007746
Erik Klineb9888902016-04-05 13:30:49 +09007747 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7748 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7749 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007750 }
Erik Klineb9888902016-04-05 13:30:49 +09007751
Erik Kline31b4a9e2018-01-11 21:07:29 +09007752 if (DBG) {
7753 final Collection<InetAddress> dnses = newLp.getDnsServers();
7754 log("Setting DNS servers for network " + netId + " to " + dnses);
7755 }
Erik Klineb9888902016-04-05 13:30:49 +09007756 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007757 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007758 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007759 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007760 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007761 }
Erik Kline54e35c02017-04-07 15:29:29 +09007762 }
7763
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007764 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7765 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007766 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7767 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007768 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7769 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007770
7771 if (!wasFiltering && !needsFiltering) {
7772 // Nothing to do.
7773 return;
7774 }
7775
7776 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7777 // Nothing changed.
7778 return;
7779 }
7780
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007781 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007782 if (ranges == null || ranges.isEmpty()) {
7783 return;
7784 }
7785
Qingxi Libb8da982020-01-17 17:54:27 -08007786 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007787 // TODO: this create a window of opportunity for apps to receive traffic between the time
7788 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007789 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007790 // old rules are being removed.
7791 if (wasFiltering) {
7792 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7793 }
7794 if (needsFiltering) {
7795 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7796 }
7797 }
7798
Valentin Iftime9fa35092019-09-24 13:32:13 +02007799 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007800 if (mWolSupportedInterfaces == null) {
7801 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007802 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007803 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007804 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7805 }
7806
Luke Huangb913c812018-08-24 20:33:16 +08007807 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007808 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007809 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007810 }
7811 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007812 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007813 }
Luke Huangb913c812018-08-24 20:33:16 +08007814 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007815 }
7816
Chalard Jean62edfd82019-12-02 18:39:29 +09007817 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7818 @NonNull final NetworkCapabilities newNc) {
7819 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7820 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007821 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007822 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007823 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007824 } catch (RemoteException | ServiceSpecificException e) {
7825 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007826 }
7827 }
7828 }
7829
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007830 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007831 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007832 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007833 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007834 underlyingNetworks = underlyingNetworksOrDefault(
7835 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007836 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007837 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7838 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007839 // metered if any underlying is metered, or originally declared metered by the agent.
7840 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007841 boolean roaming = false; // roaming if any underlying is roaming
7842 boolean congested = false; // congested if any underlying is congested
7843 boolean suspended = true; // suspended if all underlying are suspended
7844
7845 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007846 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007847 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007848 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007849 for (Network underlyingNetwork : underlyingNetworks) {
7850 final NetworkAgentInfo underlying =
7851 getNetworkAgentInfoForNetwork(underlyingNetwork);
7852 if (underlying == null) continue;
7853
7854 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7855 hadUnderlyingNetworks = true;
7856 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007857 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007858 }
7859
7860 // Merge capabilities of this underlying network. For bandwidth, assume the
7861 // worst case.
7862 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7863 underlyingCaps.getLinkDownstreamBandwidthKbps());
7864 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7865 underlyingCaps.getLinkUpstreamBandwidthKbps());
7866 // If this underlying network is metered, the VPN is metered (it may cost money
7867 // to send packets on this network).
7868 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7869 // If this underlying network is roaming, the VPN is roaming (the billing structure
7870 // is different than the usual, local one).
7871 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7872 // If this underlying network is congested, the VPN is congested (the current
7873 // condition of the network affects the performance of this network).
7874 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7875 // If this network is not suspended, the VPN is not suspended (the VPN
7876 // is able to transfer some data).
7877 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007878 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007879 }
7880 }
7881 if (!hadUnderlyingNetworks) {
7882 // No idea what the underlying networks are; assume reasonable defaults
7883 metered = true;
7884 roaming = false;
7885 congested = false;
7886 suspended = false;
7887 }
7888
lifrade6c2a2021-03-04 14:08:08 +08007889 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007890 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7891 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7892 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7893 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7894 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7895 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007896 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007897 }
7898
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007899 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007900 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7901 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7902 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007903 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007904 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007905 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007906 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007907 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7908 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007909 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007910 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007911 if (nai.everConnected()
7912 && !nai.isVPN()
7913 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007914 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007915 // does not cause any request (that is not a listen) currently matching that agent to
7916 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007917 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007918 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007919 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007920 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007921 }
7922
Paul Jensen53f08952015-06-16 14:27:36 -04007923 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007924 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007925 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007926 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007927 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007928 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007929 }
Chalard Jean254bd162022-08-25 13:04:51 +09007930 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007931 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007932 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007933 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007934 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007935 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007936 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007937 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007938 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007939 }
Chalard Jean254bd162022-08-25 13:04:51 +09007940 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007941 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7942 } else {
7943 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7944 }
lucasline117e2e2019-10-22 18:27:33 +08007945 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007946
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007947 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007948 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7949 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007950 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007951 }
7952
Lorenzo Colittibd079452021-07-02 11:47:57 +09007953 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007954 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007955 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007956 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007957 }
7958
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007959 return newNc;
7960 }
7961
Lorenzo Colitti44840702021-01-11 22:27:57 +09007962 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7963 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7964 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7965 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7966 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7967 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7968 if (prevSuspended != suspended) {
7969 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7970 // onResumed have been removed.
7971 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7972 : ConnectivityManager.CALLBACK_RESUMED);
7973 }
7974 if (prevSuspended != suspended || prevRoaming != roaming) {
7975 // updateNetworkInfo will mix in the suspended info from the capabilities and
7976 // take appropriate action for the network having possibly changed state.
7977 updateNetworkInfo(nai, nai.networkInfo);
7978 }
7979 }
7980
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007981 /**
7982 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7983 *
7984 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7985 * capabilities we manage and store in {@code nai}, such as validated status and captive
7986 * portal status)
7987 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7988 * potentially triggers rematches.
7989 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7990 * change.)
7991 *
7992 * @param oldScore score of the network before any of the changes that prompted us
7993 * to call this function.
7994 * @param nai the network having its capabilities updated.
7995 * @param nc the new network capabilities.
7996 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007997 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007998 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007999 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008000 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09008001 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008002 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008003
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008004 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008005 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008006 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008007
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008008 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008009 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8010 // the change we're processing can't affect any requests, it can only affect the listens
8011 // on this network. We might have been called by rematchNetworkAndRequests when a
8012 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008013 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008014 } else {
8015 // If the requestable capabilities have changed or the score changed, we can't have been
8016 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008017 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008018 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008019 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008020 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008021
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008022 final boolean oldMetered = prevNc.isMetered();
8023 final boolean newMetered = newNc.isMetered();
8024 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008025
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008026 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008027 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8028 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008029 }
junyulaif2c67e42018-08-07 19:50:45 +08008030
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008031 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8032 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008033
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008034 // Report changes that are interesting for network statistics tracking.
8035 if (meteredChanged || roamingChanged) {
8036 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008037 }
8038
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008039 // This network might have been underlying another network. Propagate its capabilities.
8040 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008041
8042 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008043 mDnsManager.updateTransportsForNetwork(
8044 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008045 }
lucaslin53e8a262021-06-08 01:43:59 +08008046
8047 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008048 }
8049
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008050 /** Convenience method to update the capabilities for a given network. */
8051 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008052 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008053 }
8054
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008055 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008056 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008057 *
8058 * Ingress interface filtering enforces that all apps under the given network can only receive
8059 * packets from the network's interface (and loopback). This is important for VPNs because
8060 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8061 * non-VPN interfaces.
8062 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008063 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008064 * 1. the network is an app VPN (not legacy VPN)
8065 * 2. the VPN does not allow bypass
8066 * 3. the VPN is fully-routed
8067 * 4. the VPN interface is non-null
8068 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008069 * @see INetd#firewallAddUidInterfaceRules
8070 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008071 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008072 @Nullable
8073 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008074 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008075 if (nc == null || lp == null) return null;
8076 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008077 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008078 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008079 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008080 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008081 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008082 && !lp.hasExcludeRoute()) {
8083 return lp.getInterfaceName();
8084 }
8085 return null;
8086 }
8087
8088 /**
8089 * Returns whether we need to set interface filtering rule or not
8090 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008091 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008092 String isolationIface) {
8093 // Allow rules are always needed if VPN isolation is enabled.
8094 if (isolationIface != null) return true;
8095
8096 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8097 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8098 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8099 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008100 }
8101
Chiachang Wang28afaff2020-12-10 22:24:47 +08008102 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8103 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8104 int index = 0;
8105 for (UidRange range : ranges) {
8106 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8107 index++;
8108 }
8109 return stableRanges;
8110 }
8111
Chalard Jeane6c95272022-01-25 21:04:21 +09008112 private static UidRangeParcel[] intsToUidRangeStableParcels(
8113 final @NonNull ArraySet<Integer> uids) {
8114 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8115 int index = 0;
8116 for (int uid : uids) {
8117 stableRanges[index] = new UidRangeParcel(uid, uid);
8118 index++;
8119 }
8120 return stableRanges;
8121 }
8122
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008123 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8124 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8125 for (int i = 0; i < ranges.length; i++) {
8126 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8127 }
8128 return stableRanges;
8129 }
8130
Ken Chen5e65a852020-12-24 12:59:10 +08008131 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8132 int[] exemptUids) {
8133 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8134 try {
8135 mNetd.socketDestroy(ranges, exemptUids);
8136 } catch (Exception e) {
8137 loge("Exception in socket destroy: ", e);
8138 }
8139 }
8140 }
8141
paulhuaa0743d2021-05-26 21:56:03 +08008142 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008143 int[] exemptUids = new int[2];
8144 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8145 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8146 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8147 exemptUids[0] = VPN_UID;
8148 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8149 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8150
8151 maybeCloseSockets(nai, ranges, exemptUids);
8152 try {
8153 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008154 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008155 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008156 } else {
paulhu0e79d952021-06-09 16:11:35 +08008157 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008158 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008159 }
8160 } catch (Exception e) {
8161 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8162 " on netId " + nai.network.netId + ". " + e);
8163 }
8164 maybeCloseSockets(nai, ranges, exemptUids);
8165 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008166
lucaslin53e8a262021-06-08 01:43:59 +08008167 private boolean isProxySetOnAnyDefaultNetwork() {
8168 ensureRunningOnConnectivityServiceThread();
8169 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8170 final NetworkAgentInfo nai = nri.getSatisfier();
8171 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8172 return true;
8173 }
8174 }
8175 return false;
8176 }
8177
8178 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8179 NetworkCapabilities newNc) {
8180 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8181 // the proxy might be changed since the default network satisfied by the apps might also
8182 // changed.
8183 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8184 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008185 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8186 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008187 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008188 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8189 mProxyTracker.sendProxyBroadcast();
8190 }
8191 }
8192
Chalard Jeane6c95272022-01-25 21:04:21 +09008193 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8194 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008195 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8196 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008197 if (null == prevRanges) prevRanges = new ArraySet<>();
8198 if (null == newRanges) newRanges = new ArraySet<>();
8199 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8200
8201 prevRanges.removeAll(newRanges);
8202 newRanges.removeAll(prevRangesCopy);
8203
8204 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008205 // When updating the VPN uid routing rules, add the new range first then remove the old
8206 // range. If old range were removed first, there would be a window between the old
8207 // range being removed and the new range being added, during which UIDs contained
8208 // in both ranges are not subject to any VPN routing rules. Adding new range before
8209 // removing old range works because, unlike the filtering rules below, it's possible to
8210 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008211 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8212 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8213 // [1-5] & [1-2],[4-5] == [3]
8214 // Then we can do:
8215 // maybeCloseSockets([3])
8216 // mNetd.networkAddUidRanges([1-2],[4-5])
8217 // mNetd.networkRemoveUidRanges([1-5])
8218 // maybeCloseSockets([3])
8219 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8220 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008221 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008222 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008223 }
8224 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008225 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008226 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008227 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8228 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008229 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8230 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008231 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008232 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008233 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8234 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8235 // were added first and then newRanges got removed later, there would be only one uid
8236 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8237 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8238 // Note that this is in contrast with the (more robust) update of VPN routing rules
8239 // above, where the addition of new ranges happens before the removal of old ranges.
8240 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8241 // to be removed will never overlap with the new range to be added.
8242 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008243 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8244 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008245 }
8246 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008247 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008248 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008249 } catch (Exception e) {
8250 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008251 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008252 }
8253 }
8254
Chalard Jeande665262022-02-25 16:12:12 +09008255 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008256 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8257 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008258 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8259 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008260 if (prevEmpty && newEmpty) return;
8261
8262 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008263 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008264 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008265 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008266
8267 if (prevUids.equals(newUids)) return;
8268
8269 // This implementation is very simple and vastly faster for sets of Integers than
8270 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8271 // a key computed from the value and has storage for that.
8272 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8273 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8274 toRemove.removeAll(newUids);
8275 toAdd.removeAll(prevUids);
8276
8277 try {
8278 if (!toAdd.isEmpty()) {
8279 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8280 nai.network.netId,
8281 intsToUidRangeStableParcels(toAdd),
8282 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8283 }
8284 if (!toRemove.isEmpty()) {
8285 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8286 nai.network.netId,
8287 intsToUidRangeStableParcels(toRemove),
8288 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8289 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008290 } catch (ServiceSpecificException e) {
8291 // Has the interface disappeared since the network was built ?
8292 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008293 } catch (RemoteException e) {
8294 // Netd died. This usually causes a runtime restart anyway.
8295 }
8296 }
8297
Hugo Benichi9d35b752017-09-01 01:23:32 +00008298 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008299 ensureRunningOnConnectivityServiceThread();
8300
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008301 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008302 // Ignore updates for disconnected networks
8303 return;
8304 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008305 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008306 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008307 + "; created=" + nai.getCreatedTime()
8308 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008309 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008310 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8311 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008312 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008313 }
8314
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008315 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8316 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008317 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008318 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008319 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008320 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8321 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8322 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008323 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8324 // need to be sent as a separate extra.
8325 final NetworkRequest req = nri.isMultilayerRequest()
8326 ? nri.getActiveRequest()
8327 // Non-multilayer listen requests do not have an active request
8328 : nri.mRequests.get(0);
8329 if (req == null) {
8330 Log.wtf(TAG, "No request in NRI " + nri);
8331 }
8332 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008333 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008334 sendIntent(nri.mPendingIntent, intent);
8335 }
8336 // else not handled
8337 }
8338
8339 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8340 mPendingIntentWakeLock.acquire();
8341 try {
8342 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008343 final BroadcastOptions options = BroadcastOptions.makeBasic();
8344 if (SdkLevel.isAtLeastT()) {
8345 // Explicitly disallow the receiver from starting activities, to prevent apps from
8346 // utilizing the PendingIntent as a backdoor to do this.
8347 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8348 }
8349 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8350 null /* requiredPermission */,
8351 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008352 } catch (PendingIntent.CanceledException e) {
8353 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8354 mPendingIntentWakeLock.release();
8355 releasePendingNetworkRequest(pendingIntent);
8356 }
8357 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8358 }
8359
8360 @Override
8361 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8362 String resultData, Bundle resultExtras) {
8363 if (DBG) log("Finished sending " + pendingIntent);
8364 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008365 // Release with a delay so the receiving client has an opportunity to put in its
8366 // own request.
8367 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008368 }
8369
Chalard Jean46bfbf02022-02-02 00:56:25 +09008370 // networkAgent is only allowed to be null if notificationType is
8371 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8372 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008373 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008374 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008375 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008376 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008377 // Default request has no msgr. Also prevents callbacks from being invoked for
8378 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8379 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8380 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008381 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008382 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008383 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008384 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008385 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008386 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008387 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008388 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8389 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008390 }
Roshan Pius951c0032020-12-22 15:10:42 -08008391 final boolean includeLocationSensitiveInfo =
8392 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008393 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008394 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008395 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008396 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008397 networkCapabilitiesRestrictedForCallerPermissions(
8398 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8399 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008400 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008401 nri.mCallingAttributionTag);
8402 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008403 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8404 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008405 // For this notification, arg1 contains the blocked status.
8406 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008407 break;
8408 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008409 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008410 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008411 break;
8412 }
8413 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008414 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008415 final NetworkCapabilities netCap =
8416 networkCapabilitiesRestrictedForCallerPermissions(
8417 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8418 putParcelable(
8419 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008420 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008421 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008422 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008423 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008424 break;
8425 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008426 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008427 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8428 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008429 break;
8430 }
junyulaif2c67e42018-08-07 19:50:45 +08008431 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008432 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008433 msg.arg1 = arg1;
8434 break;
8435 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008436 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008437 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008438 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008439 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008440 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008441 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008442 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008443 }
James Mattis45d81842021-01-10 14:24:24 -08008444 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008445 } catch (RemoteException e) {
8446 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008447 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008448 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008449 }
8450
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008451 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8452 bundle.putParcelable(t.getClass().getSimpleName(), t);
8453 }
8454
Chalard Jean0702f982021-09-16 21:50:07 +09008455 /**
8456 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8457 *
8458 * When a request should be assigned to a new network, it is normally lingered to give
8459 * time for apps to gracefully migrate their connections. When both networks are on the same
8460 * radio, but that radio can't do time-sharing efficiently, this may end up being
8461 * counter-productive because any traffic on the old network may drastically reduce the
8462 * performance of the new network.
8463 * The stack supports a configuration to let modem vendors state that their radio can't
8464 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8465 * from one cell network to another can't be done gracefully.
8466 *
8467 * @param oldNai the old network serving the request
8468 * @param newNai the new network serving the request
8469 * @return whether the switch can be graceful
8470 */
8471 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8472 @NonNull final NetworkAgentInfo newSatisfier) {
8473 if (mCellularRadioTimesharingCapable) return true;
8474 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8475 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8476 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8477 }
8478
Paul Jensenaf94b982014-09-30 15:37:41 -04008479 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008480 if (nai.numRequestNetworkRequests() != 0) {
8481 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8482 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008483 // Ignore listening and track default requests.
8484 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008485 loge("Dead network still had at least " + nr);
8486 break;
8487 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008488 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008489 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008490 }
8491
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008492 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8493 if (oldNetwork == null) {
8494 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8495 return;
8496 }
Chalard Jean49707572019-12-10 21:07:02 +09008497 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008498
8499 // If we get here it means that the last linger timeout for this network expired. So there
8500 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008501 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008502
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008503 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008504 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008505 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008506 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008507 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008508 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008509 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008510 }
8511
James Mattise3ef1912020-12-20 11:09:58 -08008512 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8513 boolean isDefaultChanged = false;
8514 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8515 final NetworkReassignment.RequestReassignment reassignment =
8516 changes.getReassignment(defaultRequestInfo);
8517 if (null == reassignment) {
8518 continue;
8519 }
8520 // reassignment only contains those instances where the satisfying network changed.
8521 isDefaultChanged = true;
8522 // Notify system services of the new default.
8523 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8524 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008525
James Mattise3ef1912020-12-20 11:09:58 -08008526 if (isDefaultChanged) {
8527 // Hold a wakelock for a short time to help apps in migrating to a new default.
8528 scheduleReleaseNetworkTransitionWakelock();
8529 }
8530 }
8531
8532 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8533 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8534 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8535 if (DBG) {
8536 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8537 }
Chalard Jean8e382112019-12-03 20:45:30 +09008538
James Mattisd31bdfa2020-12-23 16:37:26 -08008539 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8540 if (newDefaultNetwork != null) {
8541 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008542 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008543
James Mattisd31bdfa2020-12-23 16:37:26 -08008544 // Set an app level managed default and return since further processing only applies to the
8545 // default network.
8546 if (mDefaultRequest != nri) {
8547 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8548 return;
8549 }
8550
8551 makeDefaultNetwork(newDefaultNetwork);
8552
James Mattise3ef1912020-12-20 11:09:58 -08008553 if (oldDefaultNetwork != null) {
8554 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8555 }
8556 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008557 handleApplyDefaultProxy(null != newDefaultNetwork
8558 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8559 updateTcpBufferSizes(null != newDefaultNetwork
8560 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008561 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008562 }
8563
James Mattisd31bdfa2020-12-23 16:37:26 -08008564 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8565 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8566 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8567 try {
8568 if (VDBG) {
8569 log("Setting default network for " + nri
8570 + " using UIDs " + nri.getUids()
8571 + " with old network " + (oldDefaultNetwork != null
8572 ? oldDefaultNetwork.network().getNetId() : "null")
8573 + " and new network " + (newDefaultNetwork != null
8574 ? newDefaultNetwork.network().getNetId() : "null"));
8575 }
8576 if (nri.getUids().isEmpty()) {
8577 throw new IllegalStateException("makeDefaultForApps called without specifying"
8578 + " any applications to set as the default." + nri);
8579 }
8580 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008581 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008582 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008583 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008584 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008585 }
8586 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008587 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008588 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008589 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008590 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008591 }
8592 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008593 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008594 }
8595 }
8596
8597 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8598 try {
8599 if (null != newDefaultNetwork) {
8600 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8601 } else {
8602 mNetd.networkClearDefault();
8603 }
8604 } catch (RemoteException | ServiceSpecificException e) {
8605 loge("Exception setting default network :" + e);
8606 }
8607 }
8608
Chalard Jean05cbe972019-12-09 11:50:38 +09008609 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008610 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008611 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008612 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008613 processNewlySatisfiedListenRequests(nai);
8614 }
8615
8616 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008617 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8618 if (nri.isMultilayerRequest()) {
8619 continue;
8620 }
8621 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008622 if (!nr.isListen()) continue;
8623 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008624 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008625 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8626 }
8627 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008628 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008629
Chalard Jeancd397a22019-11-22 22:33:33 +09008630 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008631 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8632 if (nri.isMultilayerRequest()) {
8633 continue;
8634 }
8635 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008636 if (!nr.isListen()) continue;
8637 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8638 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008639 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008640 }
8641 }
8642 }
8643
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008644 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008645 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008646 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008647 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008648 @Nullable public final NetworkRequest mOldNetworkRequest;
8649 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008650 @Nullable public final NetworkAgentInfo mOldNetwork;
8651 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008652 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008653 @Nullable final NetworkRequest oldNetworkRequest,
8654 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008655 @Nullable final NetworkAgentInfo oldNetwork,
8656 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008657 mNetworkRequestInfo = networkRequestInfo;
8658 mOldNetworkRequest = oldNetworkRequest;
8659 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008660 mOldNetwork = oldNetwork;
8661 mNewNetwork = newNetwork;
8662 }
Chalard Jean49707572019-12-10 21:07:02 +09008663
8664 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008665 final NetworkRequest requestToShow = null != mNewNetworkRequest
8666 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8667 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008668 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8669 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008670 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008671 }
8672
Chalard Jean46a62372019-12-10 21:25:24 +09008673 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008674
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008675 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008676 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008677 }
8678
8679 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008680 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008681 // The code is never supposed to add two reassignments of the same request. Make
8682 // sure this stays true, but without imposing this expensive check on all
8683 // reassignments on all user devices.
8684 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008685 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008686 throw new IllegalStateException("Trying to reassign ["
8687 + reassignment + "] but already have ["
8688 + existing + "]");
8689 }
8690 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008691 }
Chalard Jean46a62372019-12-10 21:25:24 +09008692 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008693 }
8694
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008695 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008696 // the passed request.
8697 @Nullable
8698 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008699 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008700 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008701 }
8702 return null;
8703 }
Chalard Jean49707572019-12-10 21:07:02 +09008704
8705 public String toString() {
8706 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8707 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008708 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008709 for (final RequestReassignment rr : getRequestReassignments()) {
8710 sj.add(rr.toString());
8711 }
8712 return sj.toString();
8713 }
8714
8715 public String debugString() {
8716 final StringBuilder sb = new StringBuilder();
8717 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008718 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008719 for (final RequestReassignment rr : getRequestReassignments()) {
8720 sb.append("\n ").append(rr);
8721 }
8722 return sb.append("\n").toString();
8723 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008724 }
8725
Chalard Jean24344d72019-12-04 13:32:31 +09008726 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008727 @Nullable final NetworkRequest previousRequest,
8728 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008729 @Nullable final NetworkAgentInfo previousSatisfier,
8730 @Nullable final NetworkAgentInfo newSatisfier,
8731 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008732 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008733 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008734 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008735 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008736 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008737 }
James Mattisa076c532020-12-02 14:12:41 -08008738 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008739 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008740 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008741 // If this network switch can't be supported gracefully, the request is not
8742 // lingered. This allows letting go of the network sooner to reclaim some
8743 // performance on the new network, since the radio can't do both at the same
8744 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008745 //
8746 // Also don't linger the request if the old network has been destroyed.
8747 // A destroyed network does not provide actual network connectivity, so
8748 // lingering it is not useful. In particular this ensures that a destroyed
8749 // network is outscored by its replacement,
8750 // then it is torn down immediately instead of being lingered, and any apps that
8751 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008752 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8753 }
Chalard Jean24344d72019-12-04 13:32:31 +09008754 } else {
8755 if (VDBG || DDBG) log(" accepting network in place of null");
8756 }
junyulai0ac374f2020-12-14 18:41:52 +08008757
8758 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8759 // and immediately satisfies a request then remove the timer. This will happen for
8760 // all networks except in the case of an underlying network for a VCN.
8761 if (newSatisfier.isNascent()) {
8762 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008763 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008764 }
8765
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008766 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008767 newSatisfier.unlingerRequest(newRequest.requestId);
8768 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008769 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008770 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008771 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008772 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008773 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008774 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008775 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008776 }
James Mattisa076c532020-12-02 14:12:41 -08008777 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008778 }
James Mattisa076c532020-12-02 14:12:41 -08008779 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008780 }
8781
James Mattisa076c532020-12-02 14:12:41 -08008782 /**
8783 * This function is triggered when something can affect what network should satisfy what
8784 * request, and it computes the network reassignment from the passed collection of requests to
8785 * network match to the one that the system should now have. That data is encoded in an
8786 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8787 * satisfier.
8788 *
8789 * After the reassignment is computed, it is applied to the state objects.
8790 *
8791 * @param networkRequests the nri objects to evaluate for possible network reassignment
8792 * @return NetworkReassignment listing of proposed network assignment changes
8793 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008794 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008795 private NetworkReassignment computeNetworkReassignment(
8796 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008797 final NetworkReassignment changes = new NetworkReassignment();
8798
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008799 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008800 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008801 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008802 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008803 }
Chalard Jean857a1712019-12-10 21:08:07 +09008804
James Mattisa076c532020-12-02 14:12:41 -08008805 for (final NetworkRequestInfo nri : networkRequests) {
8806 // Non-multilayer listen requests can be ignored.
8807 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8808 continue;
8809 }
8810 NetworkAgentInfo bestNetwork = null;
8811 NetworkRequest bestRequest = null;
8812 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008813 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008814 // Stop evaluating as the highest possible priority request is satisfied.
8815 if (null != bestNetwork) {
8816 bestRequest = req;
8817 break;
8818 }
8819 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008820 if (null == bestNetwork && isDefaultBlocked(nri)) {
8821 // Remove default networking if disallowed for managed default requests.
8822 bestNetwork = mNoServiceNetwork;
8823 }
8824 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008825 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008826 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008827 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008828 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008829 }
8830 return changes;
8831 }
8832
James Mattisa076c532020-12-02 14:12:41 -08008833 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8834 return new HashSet<>(mNetworkRequests.values());
8835 }
8836
Paul Jensenc88b39b2015-06-16 14:27:36 -04008837 /**
James Mattisa076c532020-12-02 14:12:41 -08008838 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008839 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008840 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008841 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008842 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8843 }
8844
8845 /**
8846 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8847 * being disconnected.
8848 */
8849 private void rematchNetworksAndRequests(
8850 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8851 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008852 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008853 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008854 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008855 final long computed = SystemClock.elapsedRealtime();
8856 applyNetworkReassignment(changes, start);
8857 final long applied = SystemClock.elapsedRealtime();
8858 issueNetworkNeeds();
8859 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008860 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008861 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8862 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008863 log(changes.debugString());
8864 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008865 // Shorter form, only one line of log
8866 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8867 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008868 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008869 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008870
Chalard Jeand7f762d2019-12-10 19:01:29 +09008871 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008872 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008873 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008874
8875 // Since most of the time there are only 0 or 1 background networks, it would probably
8876 // be more efficient to just use an ArrayList here. TODO : measure performance
8877 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8878 for (final NetworkAgentInfo nai : nais) {
8879 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8880 }
8881
Chalard Jeand7f762d2019-12-10 19:01:29 +09008882 // First, update the lists of satisfied requests in the network agents. This is necessary
8883 // because some code later depends on this state to be correct, most prominently computing
8884 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008885 for (final NetworkReassignment.RequestReassignment event :
8886 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008887 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8888 event.mOldNetworkRequest, event.mNewNetworkRequest,
8889 event.mOldNetwork, event.mNewNetwork,
8890 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008891 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008892
James Mattise3ef1912020-12-20 11:09:58 -08008893 // Process default network changes if applicable.
8894 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008895
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008896 // Notify requested networks are available after the default net is switched, but
8897 // before LegacyTypeTracker sends legacy broadcasts
8898 for (final NetworkReassignment.RequestReassignment event :
8899 changes.getRequestReassignments()) {
8900 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008901 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008902 } else {
James Mattisa076c532020-12-02 14:12:41 -08008903 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008904 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008905 }
8906 }
8907
junyulai0ac374f2020-12-14 18:41:52 +08008908 // Update the inactivity state before processing listen callbacks, because the background
8909 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008910 // just yet though, because they have to be sent after the listens are processed to keep
8911 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008912 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008913 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008914 // Rematching may have altered the inactivity state of some networks, so update all
8915 // inactivity timers. updateInactivityState reads the state from the network agent
8916 // and does nothing if the state has not changed : the source of truth is controlled
8917 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8918 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008919 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008920 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008921 }
8922 }
8923
Chalard Jeanb10ab412019-12-11 14:12:30 +09008924 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008925 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008926 // Process listen requests and update capabilities if the background state has
8927 // changed for this network. For consistency with previous behavior, send onLost
8928 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008929 processNewlyLostListenRequests(nai);
8930 if (oldBackground != nai.isBackgroundNetwork()) {
8931 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008932 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008933 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008934 }
8935
junyulai0ac374f2020-12-14 18:41:52 +08008936 for (final NetworkAgentInfo nai : inactiveNetworks) {
8937 // For nascent networks, if connecting with no foreground request, skip broadcasting
8938 // LOSING for backward compatibility. This is typical when mobile data connected while
8939 // wifi connected with mobile data always-on enabled.
8940 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008941 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008942 }
8943
James Mattise3ef1912020-12-20 11:09:58 -08008944 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008945
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008946 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008947 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008948 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008949 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008950 // This network has active linger timers and no requests, but is not
8951 // lingering. Linger it.
8952 //
8953 // One way (the only way?) this can happen if this network is unvalidated
8954 // and became unneeded due to another network improving its score to the
8955 // point where this network will no longer be able to satisfy any requests
8956 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008957 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008958 notifyNetworkLosing(nai, now);
8959 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008960 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008961 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008962 teardownUnneededNetwork(nai);
8963 }
8964 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008965 }
8966 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008967
Chalard Jean62edfd82019-12-02 18:39:29 +09008968 /**
8969 * Apply a change in background state resulting from rematching networks with requests.
8970 *
8971 * During rematch, a network may change background states by starting to satisfy or stopping
8972 * to satisfy a foreground request. Listens don't count for this. When a network changes
8973 * background states, its capabilities need to be updated and callbacks fired for the
8974 * capability change.
8975 *
8976 * @param nai The network that changed background states
8977 */
8978 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8979 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8980 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8981 updateNetworkPermissions(nai, newNc);
8982 nai.getAndSetNetworkCapabilities(newNc);
8983 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8984 }
8985
Chalard Jeanf0344532019-11-19 19:23:38 +09008986 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008987 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008988 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008989 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8990 changes.getReassignment(mDefaultRequest);
8991 final NetworkAgentInfo oldDefaultNetwork =
8992 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8993 final NetworkAgentInfo newDefaultNetwork =
8994 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008995
Chalard Jean5b409c72021-02-04 13:12:59 +09008996 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008997 // Maintain the illusion : since the legacy API only understands one network at a time,
8998 // if the default network changed, apps should see a disconnected broadcast for the
8999 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009000 if (oldDefaultNetwork != null) {
9001 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9002 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009003 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009004 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009005 // The new default network can be newly null if and only if the old default
9006 // network doesn't satisfy the default request any more because it lost a
9007 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009008 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009009 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009010 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009011 }
9012 }
9013
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009014 // Now that all the callbacks have been sent, send the legacy network broadcasts
9015 // as needed. This is necessary so that legacy requests correctly bind dns
9016 // requests to this network. The legacy users are listening for this broadcast
9017 // and will generally do a dns request so they can ensureRouteToHost and if
9018 // they do that before the callbacks happen they'll use the default network.
9019 //
9020 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9021 // callbacks, but if apps can receive the broadcast before the callback, they still might
9022 // have an inconsistent view of networking.
9023 //
9024 // This *does* introduce a race where if the user uses the new api
9025 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9026 // they may get old info. Reverse this after the old startUsing api is removed.
9027 // This is on top of the multiple intent sequencing referenced in the todo above.
9028 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009029 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009030 addNetworkToLegacyTypeTracker(nai);
9031 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009032 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009033 }
9034
Chalard Jean0354d8c2021-01-12 10:58:56 +09009035 private void issueNetworkNeeds() {
9036 ensureRunningOnConnectivityServiceThread();
9037 for (final NetworkOfferInfo noi : mNetworkOffers) {
9038 issueNetworkNeeds(noi);
9039 }
9040 }
9041
9042 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9043 ensureRunningOnConnectivityServiceThread();
9044 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9045 informOffer(nri, noi.offer, mNetworkRanker);
9046 }
9047 }
9048
9049 /**
9050 * Inform a NetworkOffer about any new situation of a request.
9051 *
9052 * This function handles updates to offers. A number of events may happen that require
9053 * updating the registrant for this offer about the situation :
9054 * • The offer itself was updated. This may lead the offer to no longer being able
9055 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9056 * or conversely being strengthened enough to beat the satisfier (and therefore
9057 * start being needed)
9058 * • The network satisfying a request changed (including cases where the request
9059 * starts or stops being satisfied). The new network may be a stronger or weaker
9060 * match than the old one, possibly affecting whether the offer is needed.
9061 * • The network satisfying a request updated their score. This may lead the offer
9062 * to no longer be able to beat it if the current satisfier got better, or
9063 * conversely start being a good choice if the current satisfier got weaker.
9064 *
9065 * @param nri The request
9066 * @param offer The offer. This may be an updated offer.
9067 */
9068 private static void informOffer(@NonNull NetworkRequestInfo nri,
9069 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9070 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9071 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009072
9073 // Multi-layer requests have a currently active request, the one being satisfied.
9074 // Since the system will try to bring up a better network than is currently satisfying
9075 // the request, NetworkProviders need to be told the offers matching the requests *above*
9076 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9077 // not needed, and the offer is needed for the active request iff the offer can beat
9078 // the satisfier.
9079 // For non-multilayer requests, the logic above gracefully degenerates to only the
9080 // last case.
9081 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9082 // providers that the offer is needed for this request, until the active request is found.
9083 // In a second phase, deal with the currently active request. In a third phase, inform
9084 // the providers that offer is unneeded for the remaining requests.
9085
9086 // First phase : inform providers of all requests above the active request.
9087 int i;
9088 for (i = 0; nri.mRequests.size() > i; ++i) {
9089 final NetworkRequest request = nri.mRequests.get(i);
9090 if (activeRequest == request) break; // Found the active request : go to phase 2
9091 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9092 // Since this request is higher-priority than the one currently satisfied, if the
9093 // offer can satisfy it, the provider should try and bring up the network for sure ;
9094 // no need to even ask the ranker – an offer that can satisfy is always better than
9095 // no network. Hence tell the provider so unless it already knew.
9096 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9097 offer.onNetworkNeeded(request);
9098 }
9099 }
9100
9101 // Second phase : deal with the active request (if any)
9102 if (null != activeRequest && activeRequest.isRequest()) {
9103 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009104 // If an offer can satisfy the request, it is considered needed if it is currently
9105 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009106 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009107 && satisfier.factorySerialNumber == offer.providerId
9108 && activeRequest.canBeSatisfiedBy(offer.caps);
9109 final boolean newNeeded = currentlyServing
9110 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009111 if (newNeeded != oldNeeded) {
9112 if (newNeeded) {
9113 offer.onNetworkNeeded(activeRequest);
9114 } else {
9115 // The offer used to be able to beat the satisfier. Now it can't.
9116 offer.onNetworkUnneeded(activeRequest);
9117 }
9118 }
9119 }
9120
9121 // Third phase : inform the providers that the offer isn't needed for any request
9122 // below the active one.
9123 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9124 final NetworkRequest request = nri.mRequests.get(i);
9125 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9126 // Since this request is lower-priority than the one currently satisfied, if the
9127 // offer can satisfy it, the provider should not try and bring up the network.
9128 // Hence tell the provider so unless it already knew.
9129 if (offer.neededFor(request)) {
9130 offer.onNetworkUnneeded(request);
9131 }
9132 }
9133 }
9134
Chalard Jean61c79252019-11-07 23:07:32 +09009135 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9136 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9137 NetworkRequest nr = nai.requestAt(i);
9138 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9139 // legacy type tracker filters out repeat adds
9140 mLegacyTypeTracker.add(nr.legacyType, nai);
9141 }
9142 }
9143
9144 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009145 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009146 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9147 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9148 if (nai.isVPN()) {
9149 mLegacyTypeTracker.add(TYPE_VPN, nai);
9150 }
9151 }
9152
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009153 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009154 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009155 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009156 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009157 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009158 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009159
Chalard Jean254bd162022-08-25 13:04:51 +09009160 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009161 // Don't repeat publish.
9162 if (newInetCondition == mDefaultInetConditionPublished) return;
9163
9164 mDefaultInetConditionPublished = newInetCondition;
9165 sendInetConditionBroadcast(nai.networkInfo);
9166 }
9167
Chalard Jeand61375d2020-01-14 22:46:36 +09009168 @NonNull
9169 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9170 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009171 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009172 final boolean suspended =
9173 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9174 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9175 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9176 // state. This is because the network could have been suspended before connecting,
9177 // or it could be disconnecting while being suspended, and in both these cases
9178 // the state should not be overridden. Note that the only detailed state that
9179 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9180 // worry about multiple different substates of CONNECTED.
9181 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9182 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009183 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9184 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9185 // network agent is created, then goes to suspended, then goes out of suspended without
9186 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009187 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009188 ? NetworkInfo.DetailedState.CONNECTED
9189 : NetworkInfo.DetailedState.CONNECTING,
9190 info.getReason(),
9191 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009192 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009193 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009194 return newInfo;
9195 }
9196
9197 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9198 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9199
Erik Kline99f301b2017-02-15 19:59:17 +09009200 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009201 NetworkInfo oldInfo = null;
9202 synchronized (networkAgent) {
9203 oldInfo = networkAgent.networkInfo;
9204 networkAgent.networkInfo = newInfo;
9205 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009206
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009207 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009208 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9209 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009210 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009211
Chalard Jean254bd162022-08-25 13:04:51 +09009212 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009213 && (state == NetworkInfo.State.CONNECTED
9214 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009215
9216 // A network that has just connected has zero requests and is thus a foreground network.
9217 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9218
Luke Huangfdd11f82019-04-09 18:41:49 +08009219 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009220 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009221 // Initialize the network's capabilities to their starting values according to the
9222 // underlying networks. This ensures that the capabilities are correct before
9223 // anything happens to the network.
9224 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009225 }
Chalard Jean254bd162022-08-25 13:04:51 +09009226 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009227 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009228 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009229 }
9230
Chalard Jean254bd162022-08-25 13:04:51 +09009231 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9232 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009233
lucaslin45e639b2019-04-03 17:09:28 +08009234 // NetworkCapabilities need to be set before sending the private DNS config to
9235 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009236 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9237
Erik Kline9a62f012018-03-21 07:18:33 -07009238 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009239 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9240 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009241
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009242 // If a rate limit has been configured and is applicable to this network (network
9243 // provides internet connectivity), apply it. The tc police filter cannot be attached
9244 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9245 // updateInterfaces -> INetd#networkAddInterface.
9246 // Note: in case of a system server crash, the NetworkController constructor in netd
9247 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9248 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9249 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9250 mIngressRateLimit);
9251 }
9252
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009253 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9254 // command must be sent after updating LinkProperties to maximize chances of
9255 // NetworkMonitor seeing the correct LinkProperties when starting.
9256 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009257 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009258 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009259 }
Chalard Jeand4900722022-02-06 12:25:38 +09009260 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9261 params.networkAgentConfig = networkAgent.networkAgentConfig;
9262 params.networkCapabilities = networkAgent.networkCapabilities;
9263 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9264 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009265 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9266 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9267 // call that would cause a Log.wtf to be emitted from the system_server process, and
9268 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9269 // process to check the interface version, just use an SDK check. NetworkStack will
9270 // always be new enough when running on T+.
9271 if (SdkLevel.isAtLeastT()) {
9272 networkAgent.networkMonitor().notifyNetworkConnected(params);
9273 } else {
9274 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9275 params.networkCapabilities);
9276 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009277 final long delay = activelyPreferBadWifi()
9278 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9279 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9280 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009281
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009282 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9283 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9284 // capabilities, so it only needs to be done once on initial connect, not every time the
9285 // network's capabilities change. Note that we do this before rematching the network,
9286 // so we could decide to tear it down immediately afterwards. That's fine though - on
9287 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9288 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009289 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009290
junyulai0ac374f2020-12-14 18:41:52 +08009291 // Before first rematching networks, put an inactivity timer without any request, this
9292 // allows {@code updateInactivityState} to update the state accordingly and prevent
9293 // tearing down for any {@code unneeded} evaluation in this period.
9294 // Note that the timer will not be rescheduled since the expiry time is
9295 // fixed after connection regardless of the network satisfying other requests or not.
9296 // But it will be removed as soon as the network satisfies a request for the first time.
9297 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9298 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009299 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009300
Paul Jensen05e85ee2014-09-11 11:00:39 -04009301 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009302 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009303
9304 // This has to happen after matching the requests, because callbacks are just requests.
9305 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009306 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009307 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009308 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009309 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009310 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009311 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009312 if (networkAgent.isVPN()) {
9313 // As the active or bound network changes for apps, broadcast the default proxy, as
9314 // apps may need to update their proxy data. This is called after disconnecting from
9315 // VPN to make sure we do not broadcast the old proxy data.
9316 // TODO(b/122649188): send the broadcast only to VPN users.
9317 mProxyTracker.sendProxyBroadcast();
9318 }
Chalard Jean254bd162022-08-25 13:04:51 +09009319 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9320 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009321 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009322 }
9323 }
9324
Chalard Jean28018572020-12-21 18:36:52 +09009325 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009326 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9327 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009328 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009329 }
9330
Erik Kline99f301b2017-02-15 19:59:17 +09009331 // Notify only this one new request of the current state. Transfer all the
9332 // current state by calling NetworkCapabilities and LinkProperties callbacks
9333 // so that callers can be guaranteed to have as close to atomicity in state
9334 // transfer as can be supported by this current API.
9335 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009336 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009337 if (nri.mPendingIntent != null) {
9338 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9339 // Attempt no subsequent state pushes where intents are involved.
9340 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009341 }
Erik Kline99f301b2017-02-15 19:59:17 +09009342
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009343 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009344 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009345 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9346 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9347 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009348 }
9349
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009350 // Notify the requests on this NAI that the network is now lingered.
9351 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009352 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009353 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9354 }
9355
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009356 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9357 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9358 return vpnBlocked
9359 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9360 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9361 }
9362
9363 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9364 if (blockedReasons == BLOCKED_REASON_NONE) {
9365 mUidBlockedReasons.delete(uid);
9366 } else {
9367 mUidBlockedReasons.put(uid, blockedReasons);
9368 }
9369 }
9370
junyulaif2c67e42018-08-07 19:50:45 +08009371 /**
9372 * Notify of the blocked state apps with a registered callback matching a given NAI.
9373 *
9374 * Unlike other callbacks, blocked status is different between each individual uid. So for
9375 * any given nai, all requests need to be considered according to the uid who filed it.
9376 *
9377 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009378 * @param oldMetered True if the previous network capabilities were metered.
9379 * @param newMetered True if the current network capabilities are metered.
9380 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9381 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009382 */
9383 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009384 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9385 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009386
9387 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9388 NetworkRequest nr = nai.requestAt(i);
9389 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009390
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009391 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9392 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9393 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009394 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009395 : oldVpnBlocked;
9396
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009397 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9398 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9399 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009400 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009401 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009402 }
9403 }
9404 }
9405
9406 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009407 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009408 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009409 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009410 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009411 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009412 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009413 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009414 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009415
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009416 final int oldBlockedState = getBlockedState(
9417 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9418 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9419 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009420 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009421 }
junyulaif2c67e42018-08-07 19:50:45 +08009422 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9423 NetworkRequest nr = nai.requestAt(i);
9424 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009425 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009426 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9427 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009428 }
9429 }
9430 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009431 }
9432
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009433 @VisibleForTesting
9434 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009435 // The NetworkInfo we actually send out has no bearing on the real
9436 // state of affairs. For example, if the default connection is mobile,
9437 // and a request for HIPRI has just gone away, we need to pretend that
9438 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9439 // the state to DISCONNECTED, even though the network is of type MOBILE
9440 // and is still connected.
9441 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9442 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009443 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009444 if (state != DetailedState.DISCONNECTED) {
9445 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009446 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009447 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009448 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009449 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9450 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9451 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9452 if (info.isFailover()) {
9453 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9454 nai.networkInfo.setFailover(false);
9455 }
9456 if (info.getReason() != null) {
9457 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9458 }
9459 if (info.getExtraInfo() != null) {
9460 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9461 }
9462 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009463 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009464 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009465 if (newDefaultAgent != null) {
9466 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9467 newDefaultAgent.networkInfo);
9468 } else {
9469 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9470 }
9471 }
9472 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9473 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009474 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009475 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009476 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009477 }
9478 }
9479 }
9480
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009481 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009482 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009483 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009484 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009485 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009486 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9487 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009488 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9489 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009490 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009491 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009492 } else {
9493 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9494 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009495 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009496 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009497
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009498 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9499 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9500 }
9501
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009502 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009503 * Returns the list of all interfaces that could be used by network traffic that does not
9504 * explicitly specify a network. This includes the default network, but also all VPNs that are
9505 * currently connected.
9506 *
9507 * Must be called on the handler thread.
9508 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009509 @NonNull
9510 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009511 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009512 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009513 final Set<Integer> activeNetIds = new ArraySet<>();
9514 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9515 if (nri.isBeingSatisfied()) {
9516 activeNetIds.add(nri.getSatisfier().network().netId);
9517 }
9518 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009519 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009520 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009521 defaultNetworks.add(nai.network);
9522 }
9523 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009524 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009525 }
9526
9527 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009528 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9529 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009530 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009531 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009532 ensureRunningOnConnectivityServiceThread();
9533 String activeIface = null;
9534 LinkProperties activeLinkProperties = getActiveLinkProperties();
9535 if (activeLinkProperties != null) {
9536 activeIface = activeLinkProperties.getInterfaceName();
9537 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009538
junyulai2050bed2021-01-23 09:46:34 +08009539 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009540 try {
junyulaide41fc22021-01-22 22:46:01 +08009541 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009542 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009543 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9544 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009545 } catch (Exception ignored) {
9546 }
9547 }
9548
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009549 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009550 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009551 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009552 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009553 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009554
9555 if (!TextUtils.isEmpty(settingUrl)) {
9556 return settingUrl;
9557 }
9558
9559 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009560 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009561 if (!TextUtils.isEmpty(settingUrl)) {
9562 return settingUrl;
9563 }
9564
9565 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009566 }
9567
9568 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009569 public void startNattKeepalive(Network network, int intervalSeconds,
9570 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009571 enforceKeepalivePermission();
9572 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009573 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009574 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009575 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009576 }
9577
9578 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009579 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009580 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009581 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009582 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009583 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009584 mKeepaliveTracker.startNattKeepalive(
9585 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9586 intervalSeconds, cb,
9587 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9588 } finally {
9589 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9590 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009591 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9592 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009593 }
9594 }
junyulaid05a1922019-01-15 11:32:44 +08009595 }
9596
9597 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009598 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009599 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009600 try {
9601 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009602 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009603 mKeepaliveTracker.startTcpKeepalive(
9604 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9605 } finally {
9606 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9607 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009608 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9609 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009610 }
9611 }
junyulai0835a1e2019-01-08 20:04:33 +08009612 }
9613
9614 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009615 public void stopKeepalive(Network network, int slot) {
9616 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009617 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009618 }
9619
9620 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009621 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009622 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009623
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009624 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009625 final long token = Binder.clearCallingIdentity();
9626 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009627 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9628 UserHandle.getUserHandleForUid(uid))) {
9629 return;
9630 }
9631
Heemin Seogdb8489d2019-06-12 09:21:44 -07009632 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9633 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009634
9635 // Turn airplane mode off
9636 setAirplaneMode(false);
9637
9638 // restore private DNS settings to default mode (opportunistic)
9639 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9640 UserHandle.getUserHandleForUid(uid))) {
9641 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9642 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9643 }
9644
9645 Settings.Global.putString(mContext.getContentResolver(),
9646 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009647 } finally {
9648 Binder.restoreCallingIdentity(token);
9649 }
Stuart Scottd5463642015-04-02 18:00:02 -07009650 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009651
Ricky Wai7097cc92018-01-23 04:09:45 +00009652 @Override
9653 public byte[] getNetworkWatchlistConfigHash() {
9654 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9655 if (nwm == null) {
9656 loge("Unable to get NetworkWatchlistManager");
9657 return null;
9658 }
9659 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9660 return nwm.getWatchlistConfigHash();
9661 }
9662
Hugo Benichibe0c7652016-05-31 16:28:06 +09009663 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009664 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009665 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009666 }
Hugo Benichif4210292017-04-21 15:07:12 +09009667
9668 private static boolean toBool(int encodedBoolean) {
9669 return encodedBoolean != 0; // Only 0 means false.
9670 }
9671
9672 private static int encodeBool(boolean b) {
9673 return b ? 1 : 0;
9674 }
mswest4632928412018-03-12 10:34:34 -07009675
9676 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009677 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9678 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9679 @NonNull String[] args) {
9680 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9681 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009682 }
9683
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009684 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009685 @Override
9686 public int onCommand(String cmd) {
9687 if (cmd == null) {
9688 return handleDefaultCommands(cmd);
9689 }
9690 final PrintWriter pw = getOutPrintWriter();
9691 try {
9692 switch (cmd) {
9693 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009694 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9695 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009696 final String action = getNextArg();
9697 if ("enable".equals(action)) {
9698 setAirplaneMode(true);
9699 return 0;
9700 } else if ("disable".equals(action)) {
9701 setAirplaneMode(false);
9702 return 0;
9703 } else if (action == null) {
9704 final ContentResolver cr = mContext.getContentResolver();
9705 final int enabled = Settings.Global.getInt(cr,
9706 Settings.Global.AIRPLANE_MODE_ON);
9707 pw.println(enabled == 0 ? "disabled" : "enabled");
9708 return 0;
9709 } else {
9710 onHelp();
9711 return -1;
9712 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009713 case "reevaluate":
9714 // Usage : adb shell cmd connectivity reevaluate <netId>
9715 // If netId is omitted, then reevaluate the default network
9716 final String netId = getNextArg();
9717 final NetworkAgentInfo nai;
9718 if (null == netId) {
9719 // Note that the command is running on the wrong thread to call this,
9720 // so this could in principle return stale data. But it can't crash.
9721 nai = getDefaultNetwork();
9722 } else {
9723 // If netId can't be parsed, this throws NumberFormatException, which
9724 // is passed back to adb who prints it.
9725 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
9726 }
9727 if (null == nai) {
9728 pw.println("Unknown network (net ID not found or no default network)");
9729 return 0;
9730 }
9731 Log.d(TAG, "Reevaluating network " + nai.network);
9732 reportNetworkConnectivity(nai.network, !nai.isValidated());
9733 return 0;
mswest4632928412018-03-12 10:34:34 -07009734 default:
9735 return handleDefaultCommands(cmd);
9736 }
9737 } catch (Exception e) {
9738 pw.println(e);
9739 }
9740 return -1;
9741 }
9742
9743 @Override
9744 public void onHelp() {
9745 PrintWriter pw = getOutPrintWriter();
9746 pw.println("Connectivity service commands:");
9747 pw.println(" help");
9748 pw.println(" Print this help text.");
9749 pw.println(" airplane-mode [enable|disable]");
9750 pw.println(" Turn airplane mode on or off.");
9751 pw.println(" airplane-mode");
9752 pw.println(" Get airplane mode.");
9753 }
9754 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009755
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009756 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009757 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9758 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9759 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009760 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009761 }
9762
he_won.hwang881307a2022-03-15 21:23:52 +09009763 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9764 if (nai == null) return;
9765 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9766 final TransportInfo newInfo = nc.getTransportInfo();
9767 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9768 return;
9769 }
9770 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009771 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009772 }
9773 }
9774
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009775 /**
9776 * @param connectionInfo the connection to resolve.
9777 * @return {@code uid} if the connection is found and the app has permission to observe it
9778 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9779 * connection is not found.
9780 */
9781 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009782 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9783 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9784 }
9785
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009786 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009787 connectionInfo.local, connectionInfo.remote);
9788
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009789 if (uid == INVALID_UID) return uid; // Not found.
9790
9791 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9792 // VPN, if any, that applies to the UID that owns the connection.
9793 if (checkNetworkStackPermission()) return uid;
9794
9795 final NetworkAgentInfo vpn = getVpnForUid(uid);
9796 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009797 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009798 return INVALID_UID;
9799 }
9800
9801 return uid;
9802 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009803
Benedict Wong493e04b2018-11-09 14:45:34 -08009804 /**
9805 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9806 *
9807 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9808 */
9809 @Override
9810 public IBinder startOrGetTestNetworkService() {
9811 synchronized (mTNSLock) {
9812 TestNetworkService.enforceTestNetworkPermissions(mContext);
9813
9814 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009815 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009816 }
9817
9818 return mTNS;
9819 }
9820 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009821
Cody Kesting73708bf2019-12-18 10:57:50 -08009822 /**
9823 * Handler used for managing all Connectivity Diagnostics related functions.
9824 *
9825 * @see android.net.ConnectivityDiagnosticsManager
9826 *
9827 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9828 */
9829 @VisibleForTesting
9830 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009831 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9832
Cody Kesting73708bf2019-12-18 10:57:50 -08009833 /**
9834 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9835 * android.net.ConnectivityDiagnosticsManager}.
9836 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9837 * NetworkRequestInfo to be registered
9838 */
9839 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9840
9841 /**
9842 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9843 * android.net.ConnectivityDiagnosticsManager}.
9844 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9845 * arg1 = the uid of the caller
9846 */
9847 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9848
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009849 /**
9850 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009851 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009852 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9853 * NetworkMonitor.
9854 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009855 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009856 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009857
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009858 /**
9859 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9860 * been detected on the network.
9861 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9862 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9863 * arg2 = NetID.
9864 * data = PersistableBundle of extras passed from NetworkMonitor.
9865 */
9866 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9867
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009868 /**
9869 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9870 * the platform. This event will invoke {@link
9871 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9872 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009873 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009874 */
9875 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9876
Cody Kesting73708bf2019-12-18 10:57:50 -08009877 private ConnectivityDiagnosticsHandler(Looper looper) {
9878 super(looper);
9879 }
9880
9881 @Override
9882 public void handleMessage(Message msg) {
9883 switch (msg.what) {
9884 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9885 handleRegisterConnectivityDiagnosticsCallback(
9886 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9887 break;
9888 }
9889 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9890 handleUnregisterConnectivityDiagnosticsCallback(
9891 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9892 break;
9893 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009894 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009895 final ConnectivityReportEvent reportEvent =
9896 (ConnectivityReportEvent) msg.obj;
9897
Aaron Huang959d3642021-01-21 15:47:41 +08009898 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009899 break;
9900 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009901 case EVENT_DATA_STALL_SUSPECTED: {
9902 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009903 final Pair<Long, PersistableBundle> arg =
9904 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009905 if (nai == null) break;
9906
Aaron Huang959d3642021-01-21 15:47:41 +08009907 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009908 break;
9909 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009910 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009911 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009912 break;
9913 }
9914 default: {
9915 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9916 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009917 }
9918 }
9919 }
9920
9921 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9922 @VisibleForTesting
9923 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9924 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9925 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009926 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009927
9928 @VisibleForTesting
9929 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009930 @NonNull IConnectivityDiagnosticsCallback cb,
9931 @NonNull NetworkRequestInfo nri,
9932 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009933 mCb = cb;
9934 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009935 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009936 }
9937
9938 @Override
9939 public void binderDied() {
9940 log("ConnectivityDiagnosticsCallback IBinder died.");
9941 unregisterConnectivityDiagnosticsCallback(mCb);
9942 }
9943 }
9944
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009945 /**
9946 * Class used for sending information from {@link
9947 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9948 */
9949 private static class NetworkTestedResults {
9950 private final int mNetId;
9951 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009952 @Nullable private final String mRedirectUrl;
9953
9954 private NetworkTestedResults(
9955 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9956 mNetId = netId;
9957 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009958 mRedirectUrl = redirectUrl;
9959 }
9960 }
9961
9962 /**
9963 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9964 * ConnectivityDiagnosticsHandler}.
9965 */
9966 private static class ConnectivityReportEvent {
9967 private final long mTimestampMillis;
9968 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009969 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009970
Aaron Huang959d3642021-01-21 15:47:41 +08009971 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9972 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009973 mTimestampMillis = timestampMillis;
9974 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009975 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009976 }
9977 }
9978
Cody Kestingf1120be2020-08-03 18:01:40 -07009979 /**
9980 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9981 * ConnectivityDiagnosticsHandler}.
9982 */
9983 private static class ReportedNetworkConnectivityInfo {
9984 public final boolean hasConnectivity;
9985 public final boolean isNetworkRevalidating;
9986 public final int reporterUid;
9987 @NonNull public final NetworkAgentInfo nai;
9988
9989 private ReportedNetworkConnectivityInfo(
9990 boolean hasConnectivity,
9991 boolean isNetworkRevalidating,
9992 int reporterUid,
9993 @NonNull NetworkAgentInfo nai) {
9994 this.hasConnectivity = hasConnectivity;
9995 this.isNetworkRevalidating = isNetworkRevalidating;
9996 this.reporterUid = reporterUid;
9997 this.nai = nai;
9998 }
9999 }
10000
Cody Kesting73708bf2019-12-18 10:57:50 -080010001 private void handleRegisterConnectivityDiagnosticsCallback(
10002 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10003 ensureRunningOnConnectivityServiceThread();
10004
10005 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010006 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010007 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10008
James Mattis64b8b0f2020-11-24 17:40:49 -080010009 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10010 // confusing for these networks to change when an NRI is satisfied in another layer.
10011 if (nri.isMultilayerRequest()) {
10012 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10013 + "network requests.");
10014 }
10015
Cody Kesting73708bf2019-12-18 10:57:50 -080010016 // This means that the client registered the same callback multiple times. Do
10017 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010018 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010019 if (VDBG) log("Diagnostics callback is already registered");
10020
10021 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10022 // incremented when the NetworkRequestInfo is created as part of
10023 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010024 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010025 return;
10026 }
10027
Cody Kesting31f1ff62020-03-05 10:46:02 -080010028 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010029
10030 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010031 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010032 } catch (RemoteException e) {
10033 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010034 return;
10035 }
10036
10037 // Once registered, provide ConnectivityReports for matching Networks
10038 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10039 synchronized (mNetworkForNetId) {
10040 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10041 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010042 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10043 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010044 matchingNetworks.add(nai);
10045 }
10046 }
10047 }
10048 for (final NetworkAgentInfo nai : matchingNetworks) {
10049 final ConnectivityReport report = nai.getConnectivityReport();
10050 if (report == null) {
10051 continue;
10052 }
10053 if (!checkConnectivityDiagnosticsPermissions(
10054 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10055 continue;
10056 }
10057
10058 try {
10059 cb.onConnectivityReportAvailable(report);
10060 } catch (RemoteException e) {
10061 // Exception while sending the ConnectivityReport. Move on to the next network.
10062 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010063 }
10064 }
10065
10066 private void handleUnregisterConnectivityDiagnosticsCallback(
10067 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10068 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010069 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010070
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010071 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10072 mConnectivityDiagnosticsCallbacks.remove(iCb);
10073 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010074 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10075 return;
10076 }
10077
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010078 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010079
Cody Kesting70fa2b22020-12-02 12:16:56 -080010080 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10081 // (if the Binder died)
10082 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10083 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010084 return;
10085 }
10086
Cody Kesting46cb1672020-03-04 13:35:20 -080010087 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10088 // incremented when the NetworkRequestInfo is created as part of
10089 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010090 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010091
Cody Kesting31f1ff62020-03-05 10:46:02 -080010092 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010093 }
10094
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010095 private void handleNetworkTestedWithExtras(
10096 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10097 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010098 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010099 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010100 final ConnectivityReport report =
10101 new ConnectivityReport(
10102 reportEvent.mNai.network,
10103 reportEvent.mTimestampMillis,
10104 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010105 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010106 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010107 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010108
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010109 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010110 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010111 for (final IConnectivityDiagnosticsCallback cb : results) {
10112 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010113 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010114 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010115 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010116 }
10117 }
10118 }
10119
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010120 private void handleDataStallSuspected(
10121 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10122 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010123 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010124 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010125 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010126 new DataStallReport(
10127 nai.network,
10128 timestampMillis,
10129 detectionMethod,
10130 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010131 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010132 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010133 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010134 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010135 for (final IConnectivityDiagnosticsCallback cb : results) {
10136 try {
10137 cb.onDataStallSuspected(report);
10138 } catch (RemoteException ex) {
10139 loge("Error invoking onDataStallSuspected", ex);
10140 }
10141 }
10142 }
10143
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010144 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010145 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10146 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10147 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10148
10149 // If the Network is being re-validated as a result of this call to
10150 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10151 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010152 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010153 getMatchingPermissionedCallbacks(
10154 nai,
10155 reportedNetworkConnectivityInfo.isNetworkRevalidating
10156 ? Process.INVALID_UID
10157 : reportedNetworkConnectivityInfo.reporterUid);
10158
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010159 for (final IConnectivityDiagnosticsCallback cb : results) {
10160 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010161 cb.onNetworkConnectivityReported(
10162 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010163 } catch (RemoteException ex) {
10164 loge("Error invoking onNetworkConnectivityReported", ex);
10165 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010166
10167 // If the Network isn't re-validating, also provide the cached report. If there is no
10168 // cached report, the Network is still being validated and a report will be sent once
10169 // validation is complete. Note that networks which never undergo validation will still
10170 // have a cached ConnectivityReport with RESULT_SKIPPED.
10171 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10172 try {
10173 cb.onConnectivityReportAvailable(cachedReport);
10174 } catch (RemoteException ex) {
10175 loge("Error invoking onConnectivityReportAvailable", ex);
10176 }
10177 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010178 }
10179 }
10180
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010181 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010182 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10183 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010184 sanitized.setUids(null);
10185 sanitized.setAdministratorUids(new int[0]);
10186 sanitized.setOwnerUid(Process.INVALID_UID);
10187 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010188 }
10189
Cody Kestingf1120be2020-08-03 18:01:40 -070010190 /**
10191 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10192 *
10193 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10194 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010195 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010196 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010197 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010198 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010199 mConnectivityDiagnosticsCallbacks.entrySet()) {
10200 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10201 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010202
James Mattis64b8b0f2020-11-24 17:40:49 -080010203 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010204 if (!nai.satisfies(nri.mRequests.get(0))) {
10205 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010206 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010207
10208 // UID for this callback must either be:
10209 // - INVALID_UID (which sends callbacks to all UIDs), or
10210 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10211 // notified as a result)
10212 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10213 continue;
10214 }
10215
10216 if (!checkConnectivityDiagnosticsPermissions(
10217 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10218 continue;
10219 }
10220
10221 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010222 }
10223 return results;
10224 }
10225
Cody Kesting7474f672021-05-11 14:22:40 -070010226 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10227 @NonNull NetworkAgentInfo nai) {
10228 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10229 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10230 }
10231
Cody Kesting160ef392021-05-05 13:17:22 -070010232 private boolean hasLocationPermission(String packageName, int uid) {
10233 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10234 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10235 // call in a try-catch.
10236 try {
10237 if (!mLocationPermissionChecker.checkLocationPermission(
10238 packageName, null /* featureId */, uid, null /* message */)) {
10239 return false;
10240 }
10241 } catch (SecurityException e) {
10242 return false;
10243 }
10244
10245 return true;
10246 }
10247
10248 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10249 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010250 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010251 && virtual.networkCapabilities.getOwnerUid() == uid
10252 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10253 return true;
10254 }
10255 }
10256
10257 return false;
10258 }
10259
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010260 @VisibleForTesting
10261 boolean checkConnectivityDiagnosticsPermissions(
10262 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10263 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10264 return true;
10265 }
10266
Cody Kesting160ef392021-05-05 13:17:22 -070010267 // Administrator UIDs also contains the Owner UID
10268 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10269 if (!CollectionUtils.contains(administratorUids, callbackUid)
10270 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010271 return false;
10272 }
10273
Cody Kesting7474f672021-05-11 14:22:40 -070010274 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10275 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010276 }
10277
Cody Kestingd199a9d2019-12-17 12:55:28 -080010278 @Override
10279 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010280 @NonNull IConnectivityDiagnosticsCallback callback,
10281 @NonNull NetworkRequest request,
10282 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010283 Objects.requireNonNull(callback, "callback must not be null");
10284 Objects.requireNonNull(request, "request must not be null");
10285 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10286
Cody Kesting73708bf2019-12-18 10:57:50 -080010287 if (request.legacyType != TYPE_NONE) {
10288 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10289 + " Please use NetworkCapabilities instead.");
10290 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010291 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010292 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010293
10294 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10295 // and administrator uids to be safe.
10296 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010297 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010298
10299 final NetworkRequest requestWithId =
10300 new NetworkRequest(
10301 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10302
10303 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10304 //
10305 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10306 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10307 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010308 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010309 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010310 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010311
10312 mConnectivityDiagnosticsHandler.sendMessage(
10313 mConnectivityDiagnosticsHandler.obtainMessage(
10314 ConnectivityDiagnosticsHandler
10315 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10316 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010317 }
10318
10319 @Override
10320 public void unregisterConnectivityDiagnosticsCallback(
10321 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010322 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010323 mConnectivityDiagnosticsHandler.sendMessage(
10324 mConnectivityDiagnosticsHandler.obtainMessage(
10325 ConnectivityDiagnosticsHandler
10326 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010327 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010328 0,
10329 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010330 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010331
10332 @Override
10333 public void simulateDataStall(int detectionMethod, long timestampMillis,
10334 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010335 Objects.requireNonNull(network, "network must not be null");
10336 Objects.requireNonNull(extras, "extras must not be null");
10337
paulhu3ffffe72021-09-16 10:15:22 +080010338 enforceAnyPermissionOf(mContext,
10339 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010340 android.Manifest.permission.NETWORK_STACK);
10341 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10342 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010343 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010344 }
10345
10346 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010347 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010348 throw new SecurityException("Data Stall simulation is only possible for network "
10349 + "creators");
10350 }
10351
Cody Kesting652e3ec2020-05-21 12:08:21 -070010352 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10353 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10354 // Data Stall information as a DataStallReportParcelable and passing to
10355 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10356 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010357 final DataStallReportParcelable p = new DataStallReportParcelable();
10358 p.timestampMillis = timestampMillis;
10359 p.detectionMethod = detectionMethod;
10360
10361 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10362 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10363 }
10364 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10365 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10366 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10367 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10368 }
10369
Serik Beketayevec8ad212020-12-07 22:43:07 -080010370 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010371 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010372
lucaslin66f44212021-02-23 01:12:55 +080010373 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10374 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010375 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010376 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010377 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010378 }
lucaslin37a16d92021-01-21 19:48:09 +080010379
10380 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010381 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010382 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010383 nai.clatd.interfaceLinkStateChanged(iface, up);
10384 }
10385 }
10386
10387 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010388 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010389 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010390 nai.clatd.interfaceRemoved(iface);
10391 }
lucaslin66f44212021-02-23 01:12:55 +080010392 }
10393 }
10394
lucaslin1a8b4c62021-01-21 02:02:55 +080010395 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10396
10397 /**
10398 * Class used for updating network activity tracking with netd and notify network activity
10399 * changes.
10400 */
10401 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010402 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010403 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010404 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010405 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10406 new RemoteCallbackList<>();
10407 // Indicate the current system default network activity is active or not.
10408 @GuardedBy("mActiveIdleTimers")
10409 private boolean mNetworkActive;
10410 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010411 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010412 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010413
Chalard Jean46bfbf02022-02-02 00:56:25 +090010414 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010415 public final int timeout;
10416 public final int transportType;
10417
10418 IdleTimerParams(int timeout, int transport) {
10419 this.timeout = timeout;
10420 this.transportType = transport;
10421 }
10422 }
10423
10424 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010425 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010426 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010427 mNetd = netd;
10428 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010429 }
10430
lucaslin66f44212021-02-23 01:12:55 +080010431 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10432 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10433 synchronized (mActiveIdleTimers) {
10434 mNetworkActive = active;
10435 // If there are no idle timers, it means that system is not monitoring
10436 // activity, so the system default network for those default network
10437 // unspecified apps is always considered active.
10438 //
10439 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10440 // any network activity change event. Whenever this event is received,
10441 // the mActiveIdleTimers should be always not empty. The legacy behavior
10442 // is no-op. Remove to refer to mNetworkActive only.
10443 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10444 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10445 }
10446 }
10447 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010448
lucaslin1193a5d2021-01-21 02:04:15 +080010449 // The network activity should only be updated from ConnectivityService handler thread
10450 // when mActiveIdleTimers lock is held.
10451 @GuardedBy("mActiveIdleTimers")
10452 private void reportNetworkActive() {
10453 final int length = mNetworkActivityListeners.beginBroadcast();
10454 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10455 try {
10456 for (int i = 0; i < length; i++) {
10457 try {
10458 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10459 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010460 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010461 }
10462 }
10463 } finally {
10464 mNetworkActivityListeners.finishBroadcast();
10465 }
10466 }
10467
10468 @GuardedBy("mActiveIdleTimers")
10469 public void handleReportNetworkActivity() {
10470 synchronized (mActiveIdleTimers) {
10471 reportNetworkActive();
10472 }
10473 }
10474
lucaslin1a8b4c62021-01-21 02:02:55 +080010475 // This is deprecated and only to support legacy use cases.
10476 private int transportTypeToLegacyType(int type) {
10477 switch (type) {
10478 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010479 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010480 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010481 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010482 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010483 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010484 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010485 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010486 default:
10487 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10488 }
10489 return ConnectivityManager.TYPE_NONE;
10490 }
10491
10492 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10493 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10494 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10495 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10496 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10497 final long ident = Binder.clearCallingIdentity();
10498 try {
10499 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10500 RECEIVE_DATA_ACTIVITY_CHANGE,
10501 null /* resultReceiver */,
10502 null /* scheduler */,
10503 0 /* initialCode */,
10504 null /* initialData */,
10505 null /* initialExtra */);
10506 } finally {
10507 Binder.restoreCallingIdentity(ident);
10508 }
10509 }
10510
10511 /**
10512 * Setup data activity tracking for the given network.
10513 *
10514 * Every {@code setupDataActivityTracking} should be paired with a
10515 * {@link #removeDataActivityTracking} for cleanup.
10516 */
10517 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10518 final String iface = networkAgent.linkProperties.getInterfaceName();
10519
10520 final int timeout;
10521 final int type;
10522
10523 if (networkAgent.networkCapabilities.hasTransport(
10524 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10525 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010526 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010527 10);
10528 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10529 } else if (networkAgent.networkCapabilities.hasTransport(
10530 NetworkCapabilities.TRANSPORT_WIFI)) {
10531 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010532 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010533 15);
10534 type = NetworkCapabilities.TRANSPORT_WIFI;
10535 } else {
10536 return; // do not track any other networks
10537 }
10538
lucaslinb961efc2021-01-21 02:03:17 +080010539 updateRadioPowerState(true /* isActive */, type);
10540
lucaslin1a8b4c62021-01-21 02:02:55 +080010541 if (timeout > 0 && iface != null) {
10542 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010543 synchronized (mActiveIdleTimers) {
10544 // Networks start up.
10545 mNetworkActive = true;
10546 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10547 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10548 reportNetworkActive();
10549 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010550 } catch (Exception e) {
10551 // You shall not crash!
10552 loge("Exception in setupDataActivityTracking " + e);
10553 }
10554 }
10555 }
10556
10557 /**
10558 * Remove data activity tracking when network disconnects.
10559 */
10560 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10561 final String iface = networkAgent.linkProperties.getInterfaceName();
10562 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10563
lucaslinb961efc2021-01-21 02:03:17 +080010564 if (iface == null) return;
10565
10566 final int type;
10567 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10568 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10569 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10570 type = NetworkCapabilities.TRANSPORT_WIFI;
10571 } else {
10572 return; // do not track any other networks
10573 }
10574
10575 try {
10576 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010577 synchronized (mActiveIdleTimers) {
10578 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10579 // The call fails silently if no idle timer setup for this interface
10580 mNetd.idletimerRemoveInterface(iface, params.timeout,
10581 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010582 }
lucaslinb961efc2021-01-21 02:03:17 +080010583 } catch (Exception e) {
10584 // You shall not crash!
10585 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010586 }
10587 }
10588
10589 /**
10590 * Update data activity tracking when network state is updated.
10591 */
10592 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10593 NetworkAgentInfo oldNetwork) {
10594 if (newNetwork != null) {
10595 setupDataActivityTracking(newNetwork);
10596 }
10597 if (oldNetwork != null) {
10598 removeDataActivityTracking(oldNetwork);
10599 }
10600 }
lucaslinb961efc2021-01-21 02:03:17 +080010601
10602 private void updateRadioPowerState(boolean isActive, int transportType) {
10603 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10604 switch (transportType) {
10605 case NetworkCapabilities.TRANSPORT_CELLULAR:
10606 bs.reportMobileRadioPowerState(isActive, NO_UID);
10607 break;
10608 case NetworkCapabilities.TRANSPORT_WIFI:
10609 bs.reportWifiRadioPowerState(isActive, NO_UID);
10610 break;
10611 default:
10612 logw("Untracked transport type:" + transportType);
10613 }
10614 }
lucaslin1193a5d2021-01-21 02:04:15 +080010615
10616 public boolean isDefaultNetworkActive() {
10617 synchronized (mActiveIdleTimers) {
10618 // If there are no idle timers, it means that system is not monitoring activity,
10619 // so the default network is always considered active.
10620 //
10621 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10622 // tracking is disabled (negative idle timer value configured), or no active default
10623 // network. In the latter case, this reports active but it should report inactive.
10624 return mNetworkActive || mActiveIdleTimers.isEmpty();
10625 }
10626 }
10627
10628 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10629 mNetworkActivityListeners.register(l);
10630 }
10631
10632 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10633 mNetworkActivityListeners.unregister(l);
10634 }
lucaslin012f7a12021-01-21 02:04:35 +080010635
10636 public void dump(IndentingPrintWriter pw) {
10637 synchronized (mActiveIdleTimers) {
10638 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10639 pw.println("Idle timers:");
10640 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10641 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10642 final IdleTimerParams params = ent.getValue();
10643 pw.print(" timeout="); pw.print(params.timeout);
10644 pw.print(" type="); pw.println(params.transportType);
10645 }
10646 }
10647 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010648 }
James Mattis47db0582021-01-01 14:13:35 -080010649
Daniel Brightf9e945b2020-06-15 16:10:01 -070010650 /**
10651 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10652 *
10653 * @param socketInfo the socket information
10654 * @param callback the callback to register
10655 */
10656 @Override
10657 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10658 @NonNull final IQosCallback callback) {
10659 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10660 if (nai == null || nai.networkCapabilities == null) {
10661 try {
10662 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10663 } catch (final RemoteException ex) {
10664 loge("registerQosCallbackInternal: RemoteException", ex);
10665 }
10666 return;
10667 }
10668 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10669 }
10670
10671 /**
10672 * Register a {@link IQosCallback} with base {@link QosFilter}.
10673 *
10674 * @param filter the filter to register
10675 * @param callback the callback to register
10676 * @param nai the agent information related to the filter's network
10677 */
10678 @VisibleForTesting
10679 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10680 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010681 Objects.requireNonNull(filter, "filter must be non-null");
10682 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010683
10684 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010685 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10686 // on this network is unregistered when the app loses permission or b) no QoS
10687 // callbacks are sent for restricted networks unless the app currently has permission
10688 // to access restricted networks.
10689 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010690 }
10691 mQosCallbackTracker.registerCallback(callback, filter, nai);
10692 }
10693
10694 /**
10695 * Unregisters the given callback.
10696 *
10697 * @param callback the callback to unregister
10698 */
10699 @Override
10700 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010701 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010702 mQosCallbackTracker.unregisterCallback(callback);
10703 }
James Mattis47db0582021-01-01 14:13:35 -080010704
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010705 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10706 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10707 // Enterprise device can be fully managed like device owner and such use case
10708 // also should be supported. Calling app check for work profile and fully managed device
10709 // is already done in DevicePolicyManager.
10710 // This check is an extra caution to be sure device is fully managed or not.
10711 final UserManager um = mContext.getSystemService(UserManager.class);
10712 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10713 if (um.isManagedProfile(profile.getIdentifier())) {
10714 return true;
10715 }
10716 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10717 return false;
10718 }
10719
James Mattis45d81842021-01-10 14:24:24 -080010720 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010721 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010722 *
10723 * See the documentation for the individual preferences for a description of the supported
10724 * behaviors.
10725 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010726 * @param profile If the device owner is set, any profile is allowed.
10727 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010728 * @param preferences the list of profile network preferences for the
10729 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010730 * @param listener an optional listener to listen for completion of the operation.
10731 */
10732 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010733 public void setProfileNetworkPreferences(
10734 @NonNull final UserHandle profile,
10735 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010736 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010737 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010738 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010739
10740 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010741 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10742 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10743 .build();
10744 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010745 }
10746
paulhu3ffffe72021-09-16 10:15:22 +080010747 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010748 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010749 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010750 }
10751 if (profile.getIdentifier() < 0) {
10752 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10753 + "UserHandle.CURRENT not supported)");
10754 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010755 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10756 throw new IllegalArgumentException("Profile must be a managed profile "
10757 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010758 }
paulhuaa0743d2021-05-26 21:56:03 +080010759
Chalard Jean46bfbf02022-02-02 00:56:25 +090010760 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010761 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010762 for (final ProfileNetworkPreference preference : preferences) {
10763 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010764 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010765 switch (preference.getPreference()) {
10766 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10767 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010768 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010769 if (preference.getPreferenceEnterpriseId() != 0) {
10770 throw new IllegalArgumentException(
10771 "Invalid enterprise identifier in setProfileNetworkPreferences");
10772 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010773 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010774 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10775 allowFallback = false;
10776 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010777 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010778 // This code is needed even though there is a check later on,
10779 // because isRangeAlreadyInPreferenceList assumes that every preference
10780 // has a UID list.
10781 if (hasDefaultPreference) {
10782 throw new IllegalArgumentException(
10783 "Default profile preference should not be set along with other "
10784 + "preference");
10785 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010786 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10787 throw new IllegalArgumentException(
10788 "Invalid enterprise identifier in setProfileNetworkPreferences");
10789 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010790 final Set<UidRange> uidRangeSet =
10791 getUidListToBeAppliedForNetworkPreference(profile, preference);
10792 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10793 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10794 } else {
10795 throw new IllegalArgumentException(
10796 "Overlapping uid range in setProfileNetworkPreferences");
10797 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010798 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010799 nc.addEnterpriseId(
10800 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010801 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10802 break;
10803 default:
10804 throw new IllegalArgumentException(
10805 "Invalid preference in setProfileNetworkPreferences");
10806 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010807 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10808 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010809 if (hasDefaultPreference && preferenceList.size() > 1) {
10810 throw new IllegalArgumentException(
10811 "Default profile preference should not be set along with other preference");
10812 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010813 }
10814 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010815 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010816 }
10817
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010818 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10819 @NonNull final UserHandle profile,
10820 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10821 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010822 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10823 profileNetworkPreference.getIncludedUids());
10824
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010825 if (uidRangeSet.size() > 0) {
10826 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10827 throw new IllegalArgumentException(
10828 "Allow uid range is outside the uid range of profile.");
10829 }
10830 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010831 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010832 profileNetworkPreference.getExcludedUids());
10833 if (disallowUidRangeSet.size() > 0) {
10834 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10835 throw new IllegalArgumentException(
10836 "disallow uid range is outside the uid range of profile.");
10837 }
10838 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10839 disallowUidRangeSet);
10840 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010841 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010842 uidRangeSet.add(profileUids);
10843 }
10844 }
10845 return uidRangeSet;
10846 }
10847
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010848 private boolean isEnterpriseIdentifierValid(
10849 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010850 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010851 return true;
10852 }
10853 return false;
10854 }
10855
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010856 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010857 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010858 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010859 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010860 // The NRI for a user should contain the request for capabilities.
10861 // If fallback to default network is needed then NRI should include
10862 // the request for the default network. Create an image of it to
10863 // have the correct UIDs in it (also a request can only be part of one NRI, because
10864 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010865 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10866 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010867 if (pref.allowFallback) {
10868 nrs.add(createDefaultInternetRequestForTransport(
10869 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10870 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010871 if (VDBG) {
10872 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10873 pref.capabilities.getUids()));
10874 }
10875
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010876 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010877 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010878 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010879 result.add(nri);
10880 }
10881 return result;
10882 }
10883
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010884 /**
10885 * Compare if the given UID range sets have the same UIDs.
10886 *
10887 */
10888 private boolean isRangeAlreadyInPreferenceList(
10889 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10890 @NonNull Set<UidRange> uidRangeSet) {
10891 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10892 return false;
10893 }
10894 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10895 if (UidRangeUtils.doesRangeSetOverlap(
10896 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10897 return true;
10898 }
10899 }
10900 return false;
10901 }
10902
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010903 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010904 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010905 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010906 /*
10907 * handleSetProfileNetworkPreference is always called for single user.
10908 * preferenceList only contains preferences for different uids within the same user
10909 * (enforced by getUidListToBeAppliedForNetworkPreference).
10910 * Clear all the existing preferences for the user before applying new preferences.
10911 *
10912 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010913 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010914 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010915 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010916 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10917 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010918
paulhu74128522021-09-28 02:29:03 +000010919 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10920 addPerAppDefaultNetworkRequests(
10921 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010922
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010923 // Finally, rematch.
10924 rematchAllNetworksAndRequests();
10925
10926 if (null != listener) {
10927 try {
10928 listener.onComplete();
10929 } catch (RemoteException e) {
10930 loge("Listener for setProfileNetworkPreference has died");
10931 }
10932 }
10933 }
10934
paulhu51f77dc2021-06-07 02:34:20 +000010935 @VisibleForTesting
10936 @NonNull
10937 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10938 @NonNull final Set<Integer> uids) {
10939 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10940 if (uids.size() == 0) {
10941 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10942 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10943 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10944 return nris;
10945 }
10946
10947 final List<NetworkRequest> requests = new ArrayList<>();
10948 // The NRI should be comprised of two layers:
10949 // - The request for the mobile network preferred.
10950 // - The request for the default network, for fallback.
10951 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010952 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010953 requests.add(createDefaultInternetRequestForTransport(
10954 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10955 final Set<UidRange> ranges = new ArraySet<>();
10956 for (final int uid : uids) {
10957 ranges.add(new UidRange(uid, uid));
10958 }
10959 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010960 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010961 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010962 return nris;
10963 }
10964
10965 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010966 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010967 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10968 addPerAppDefaultNetworkRequests(
10969 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010970 // Finally, rematch.
10971 rematchAllNetworksAndRequests();
10972 }
10973
Patrick Rohr2857ac42022-01-21 14:58:16 +010010974 private void handleIngressRateLimitChanged() {
10975 final long oldIngressRateLimit = mIngressRateLimit;
10976 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10977 mContext);
10978 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10979 if (canNetworkBeRateLimited(networkAgent)) {
10980 // If rate limit has previously been enabled, remove the old limit first.
10981 if (oldIngressRateLimit >= 0) {
10982 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10983 }
10984 if (mIngressRateLimit >= 0) {
10985 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10986 mIngressRateLimit);
10987 }
10988 }
10989 }
10990 }
10991
10992 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010993 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10994 if (!SdkLevel.isAtLeastT()) return false;
10995
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010996 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10997 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10998 // internet connectivity can be rate limited.
10999 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11000 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011001 return false;
11002 }
11003
11004 final String iface = networkAgent.linkProperties.getInterfaceName();
11005 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011006 // This may happen in tests, but if there is no interface then there is nothing that
11007 // can be rate limited.
11008 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011009 return false;
11010 }
11011 return true;
11012 }
11013
James Mattis45d81842021-01-10 14:24:24 -080011014 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011015 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11016 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011017 }
11018
11019 /**
11020 * Used by automotive devices to set the network preferences used to direct traffic at an
11021 * application level as per the given OemNetworkPreferences. An example use-case would be an
11022 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11023 * vehicle via a particular network.
11024 *
11025 * Calling this will overwrite the existing preference.
11026 *
James Mattisda32cfe2021-01-26 16:23:52 -080011027 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011028 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011029 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011030 */
James Mattis47db0582021-01-01 14:13:35 -080011031 @Override
James Mattis45d81842021-01-10 14:24:24 -080011032 public void setOemNetworkPreference(
11033 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011034 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011035
James Mattisfa270db2021-05-31 17:11:10 -070011036 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11037 // Only bypass the permission/device checks if this is a valid test request.
11038 if (isValidTestOemNetworkPreference(preference)) {
11039 enforceManageTestNetworksPermission();
11040 } else {
11041 enforceAutomotiveDevice();
11042 enforceOemNetworkPreferencesPermission();
11043 validateOemNetworkPreferences(preference);
11044 }
James Mattis45d81842021-01-10 14:24:24 -080011045
James Mattis45d81842021-01-10 14:24:24 -080011046 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11047 new Pair<>(preference, listener)));
11048 }
11049
James Mattisfa270db2021-05-31 17:11:10 -070011050 /**
11051 * Check the validity of an OEM network preference to be used for testing purposes.
11052 * @param preference the preference to validate
11053 * @return true if this is a valid OEM network preference test request.
11054 */
11055 private boolean isValidTestOemNetworkPreference(
11056 @NonNull final OemNetworkPreferences preference) {
11057 // Allow for clearing of an existing OemNetworkPreference used for testing.
11058 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11059 // changes after this check is complete. This is an unlikely scenario as calling of this API
11060 // is controlled by the OEM therefore the added complexity is not worth adding given those
11061 // circumstances. That said, it is an edge case to be aware of hence this comment.
11062 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11063 && isTestOemNetworkPreference(mOemNetworkPreferences);
11064 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11065 }
11066
11067 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11068 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11069 return prefMap.size() == 1
11070 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11071 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11072 }
11073
James Mattis45d81842021-01-10 14:24:24 -080011074 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11075 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11076 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011077 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11078 throw new IllegalArgumentException(
11079 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11080 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011081 }
11082 }
11083 }
11084
11085 private void handleSetOemNetworkPreference(
11086 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011087 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011088 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11089 if (DBG) {
11090 log("set OEM network preferences :" + preference.toString());
11091 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011092
James Mattiscb1e0362021-04-06 17:07:42 -070011093 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011094 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11095 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11096 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011097 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011098
11099 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011100 try {
11101 listener.onComplete();
11102 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011103 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011104 }
James Mattis45d81842021-01-10 14:24:24 -080011105 }
11106 }
11107
paulhu74128522021-09-28 02:29:03 +000011108 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011109 // Skip the requests which are set by other network preference. Because the uid range rules
11110 // should stay in netd.
11111 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011112 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011113 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011114 }
11115
James Mattis3ce3d3c2021-02-09 18:18:28 -080011116 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11117 ensureRunningOnConnectivityServiceThread();
11118 mDefaultNetworkRequests.addAll(nris);
11119 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11120 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011121 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011122 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11123 nrisToRegister.addAll(
11124 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11125 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011126 }
11127
11128 /**
11129 * All current requests that are tracking the default network need to be assessed as to whether
11130 * or not the current set of per-application default requests will be changing their default
11131 * network. If so, those requests will need to be updated so that they will send callbacks for
11132 * default network changes at the appropriate time. Additionally, those requests tracking the
11133 * default that were previously updated by this flow will need to be reassessed.
11134 * @return the nris which will need to be updated.
11135 */
11136 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11137 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11138 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11139 // same nri in the map's values for each of its NetworkRequest objects.
11140 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011141 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011142 // Include this nri if it is currently being tracked.
11143 if (isPerAppTrackedNri(nri)) {
11144 defaultCallbackRequests.add(nri);
11145 continue;
11146 }
11147 // We only track callbacks for requests tracking the default.
11148 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11149 continue;
11150 }
11151 // Include this nri if it will be tracked by the new per-app default requests.
11152 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011153 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011154 if (isNriGoingToBeTracked) {
11155 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011156 }
11157 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011158 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011159 }
11160
James Mattis3ce3d3c2021-02-09 18:18:28 -080011161 /**
11162 * Create nris for those network requests that are currently tracking the default network that
11163 * are being controlled by a per-application default.
11164 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11165 * foundation when creating the nri. Important items include the calling uid's original
11166 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11167 * requests are assumed to have already been validated as needing to be updated.
11168 * @return the Set of nris to use when registering network requests.
11169 */
11170 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11171 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11172 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11173 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11174 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011175 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011176
Chalard Jean9473c982021-07-29 20:03:04 +090011177 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011178 if (trackingNri == mDefaultRequest) {
11179 callbackRequestsToRegister.add(new NetworkRequestInfo(
11180 callbackRequest,
11181 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11182 continue;
11183 }
11184
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011185 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011186 callbackRequestsToRegister.add(new NetworkRequestInfo(
11187 callbackRequest,
11188 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011189 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011190 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011191 }
11192 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011193 }
11194
Chalard Jean17215832021-03-01 14:06:28 +090011195 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11196 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011197 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011198 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011199 }
11200 }
11201
James Mattis45d81842021-01-10 14:24:24 -080011202 /**
11203 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11204 */
11205 @VisibleForTesting
11206 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011207 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011208 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011209 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011210 final SparseArray<Set<Integer>> uids =
11211 createUidsFromOemNetworkPreferences(preference);
11212 for (int i = 0; i < uids.size(); i++) {
11213 final int key = uids.keyAt(i);
11214 final Set<Integer> value = uids.valueAt(i);
11215 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11216 // No need to add an nri without any requests.
11217 if (0 == nri.mRequests.size()) {
11218 continue;
11219 }
11220 nris.add(nri);
11221 }
11222
11223 return nris;
11224 }
11225
11226 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11227 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011228 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011229 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011230 final List<UserHandle> users =
11231 mContext.getSystemService(UserManager.class).getUserHandles(true);
11232 if (null == users || users.size() == 0) {
11233 if (VDBG || DDBG) {
11234 log("No users currently available for setting the OEM network preference.");
11235 }
James Mattisb6b6a432021-06-01 22:30:36 -070011236 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011237 }
James Mattis45d81842021-01-10 14:24:24 -080011238 for (final Map.Entry<String, Integer> entry :
11239 preference.getNetworkPreferences().entrySet()) {
11240 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011241 // Add the rules for all users as this policy is device wide.
11242 for (final UserHandle user : users) {
11243 try {
11244 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11245 if (!prefToUids.contains(pref)) {
11246 prefToUids.put(pref, new ArraySet<>());
11247 }
11248 prefToUids.get(pref).add(uid);
11249 } catch (PackageManager.NameNotFoundException e) {
11250 // Although this may seem like an error scenario, it is ok that uninstalled
11251 // packages are sent on a network preference as the system will watch for
11252 // package installations associated with this network preference and update
11253 // accordingly. This is done to minimize race conditions on app install.
11254 continue;
James Mattis45d81842021-01-10 14:24:24 -080011255 }
James Mattis45d81842021-01-10 14:24:24 -080011256 }
11257 }
James Mattisb6b6a432021-06-01 22:30:36 -070011258 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011259 }
11260
11261 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11262 @OemNetworkPreferences.OemNetworkPreference final int preference,
11263 @NonNull final Set<Integer> uids) {
11264 final List<NetworkRequest> requests = new ArrayList<>();
11265 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11266 switch (preference) {
11267 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11268 requests.add(createUnmeteredNetworkRequest());
11269 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011270 requests.add(createDefaultInternetRequestForTransport(
11271 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011272 break;
11273 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11274 requests.add(createUnmeteredNetworkRequest());
11275 requests.add(createOemPaidNetworkRequest());
11276 break;
11277 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11278 requests.add(createOemPaidNetworkRequest());
11279 break;
11280 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11281 requests.add(createOemPrivateNetworkRequest());
11282 break;
James Mattisfa270db2021-05-31 17:11:10 -070011283 case OEM_NETWORK_PREFERENCE_TEST:
11284 requests.add(createUnmeteredNetworkRequest());
11285 requests.add(createTestNetworkRequest());
11286 requests.add(createDefaultRequest());
11287 break;
11288 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11289 requests.add(createTestNetworkRequest());
11290 break;
James Mattis45d81842021-01-10 14:24:24 -080011291 default:
11292 // This should never happen.
11293 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11294 + " called with invalid preference of " + preference);
11295 }
11296
James Mattisfa270db2021-05-31 17:11:10 -070011297 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011298 for (final int uid : uids) {
11299 ranges.add(new UidRange(uid, uid));
11300 }
11301 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011302 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011303 }
11304
11305 private NetworkRequest createUnmeteredNetworkRequest() {
11306 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11307 .addCapability(NET_CAPABILITY_NOT_METERED)
11308 .addCapability(NET_CAPABILITY_VALIDATED);
11309 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11310 }
11311
11312 private NetworkRequest createOemPaidNetworkRequest() {
11313 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11314 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11315 .addCapability(NET_CAPABILITY_OEM_PAID)
11316 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11317 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11318 }
11319
11320 private NetworkRequest createOemPrivateNetworkRequest() {
11321 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11322 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11323 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11324 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11325 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11326 }
11327
11328 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011329 final NetworkCapabilities netcap = new NetworkCapabilities();
11330 netcap.addCapability(NET_CAPABILITY_INTERNET);
11331 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11332 return netcap;
11333 }
11334
11335 private NetworkRequest createTestNetworkRequest() {
11336 final NetworkCapabilities netcap = new NetworkCapabilities();
11337 netcap.clearAll();
11338 netcap.addTransportType(TRANSPORT_TEST);
11339 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011340 }
James Mattis47db0582021-01-01 14:13:35 -080011341 }
markchien738ad912021-12-09 18:15:45 +080011342
11343 @Override
11344 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11345 enforceNetworkStackOrSettingsPermission();
11346
11347 try {
11348 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011349 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011350 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011351 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011352 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011353 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011354 throw new IllegalStateException(e);
11355 }
11356 }
11357
11358 @Override
11359 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11360 enforceNetworkStackOrSettingsPermission();
11361
11362 try {
11363 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011364 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011365 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011366 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011367 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011368 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011369 throw new IllegalStateException(e);
11370 }
11371 }
markchiene1561fa2021-12-09 22:00:56 +080011372
11373 @Override
markchien3c04e662022-03-22 16:29:56 +080011374 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011375 enforceNetworkStackOrSettingsPermission();
11376
markchien3c04e662022-03-22 16:29:56 +080011377 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11378 int firewallRule = getFirewallRuleType(chain, rule);
11379
11380 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11381 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11382 }
11383
markchiene1561fa2021-12-09 22:00:56 +080011384 try {
markchien3c04e662022-03-22 16:29:56 +080011385 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011386 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011387 throw new IllegalStateException(e);
11388 }
11389 }
markchien98a6f952022-01-13 23:43:53 +080011390
markchien3c04e662022-03-22 16:29:56 +080011391 private int getFirewallRuleType(int chain, int rule) {
11392 final int defaultRule;
11393 switch (chain) {
11394 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011395 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11396 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011397 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011398 defaultRule = FIREWALL_RULE_ALLOW;
11399 break;
11400 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11401 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11402 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11403 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11404 defaultRule = FIREWALL_RULE_DENY;
11405 break;
11406 default:
11407 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11408 }
11409 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11410
11411 return rule;
11412 }
11413
markchien98a6f952022-01-13 23:43:53 +080011414 @Override
11415 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11416 enforceNetworkStackOrSettingsPermission();
11417
11418 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011419 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011420 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011421 throw new IllegalStateException(e);
11422 }
11423 }
11424
markchien00a0bed2022-01-13 23:46:13 +080011425 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011426 public boolean getFirewallChainEnabled(final int chain) {
11427 enforceNetworkStackOrSettingsPermission();
11428
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011429 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011430 }
11431
11432 @Override
markchien00a0bed2022-01-13 23:46:13 +080011433 public void replaceFirewallChain(final int chain, final int[] uids) {
11434 enforceNetworkStackOrSettingsPermission();
11435
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011436 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011437 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011438}