blob: 6804bafe4e5cf37ed32c3c9e189beaf737e45fc1 [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();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001985 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001986 if (nai == null) return null;
1987 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001988 }
1989
1990 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001991 public NetworkInfo[] getAllNetworkInfo() {
1992 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001993 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001994 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1995 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001996 NetworkInfo info = getNetworkInfo(networkType);
1997 if (info != null) {
1998 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001999 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002001 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002002 }
2003
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002004 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002005 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002006 public Network getNetworkForType(int networkType) {
2007 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002008 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2009 return null;
2010 }
2011 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2012 if (nai == null) {
2013 return null;
2014 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002015 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002016 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2017 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002018 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002019 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002020 }
2021
2022 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002023 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002024 public Network[] getAllNetworks() {
2025 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002026 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002027 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002028 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002029 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002030 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002031 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002032 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002033 }
2034
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002035 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002036 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002037 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002038 // The basic principle is: if an app's traffic could possibly go over a
2039 // network, without the app doing anything multinetwork-specific,
2040 // (hence, by "default"), then include that network's capabilities in
2041 // the array.
2042 //
2043 // In the normal case, app traffic only goes over the system's default
2044 // network connection, so that's the only network returned.
2045 //
2046 // With a VPN in force, some app traffic may go into the VPN, and thus
2047 // over whatever underlying networks the VPN specifies, while other app
2048 // traffic may go over the system default network (e.g.: a split-tunnel
2049 // VPN, or an app disallowed by the VPN), so the set of networks
2050 // returned includes the VPN's underlying networks and the system
2051 // default.
2052 enforceAccessPermission();
2053
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002054 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002055
James Mattis2516da32021-01-31 17:06:19 -08002056 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2057 if (!nri.isBeingSatisfied()) {
2058 continue;
2059 }
2060 final NetworkAgentInfo nai = nri.getSatisfier();
2061 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2062 if (null != nc
2063 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2064 && !result.containsKey(nai.network)) {
2065 result.put(
2066 nai.network,
2067 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002068 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002069 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2070 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002071 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002072 }
2073
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002074 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002075 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002076 if (null != networks) {
2077 for (final Network network : networks) {
2078 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2079 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002080 result.put(
2081 network,
2082 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002083 nc,
2084 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002085 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002086 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002087 }
2088 }
2089 }
2090
2091 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2092 out = result.values().toArray(out);
2093 return out;
2094 }
2095
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002096 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002097 public boolean isNetworkSupported(int networkType) {
2098 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002099 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002100 }
2101
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002102 /**
2103 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002104 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002105 * @return the ip properties for the active network, or {@code null} if
2106 * none is active
2107 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002108 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002109 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002110 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002111 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002112 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2113 if (nai == null) return null;
2114 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002115 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002116 }
2117
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002118 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002119 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002120 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002121 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002122 final LinkProperties lp = getLinkProperties(nai);
2123 if (lp == null) return null;
2124 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002125 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002126 }
2127
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002128 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002129 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002130 public LinkProperties getLinkProperties(Network network) {
2131 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002132 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2133 if (lp == null) return null;
2134 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002135 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002136 }
2137
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002138 @Nullable
2139 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002140 if (nai == null) {
2141 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002142 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002143 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002144 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002145 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002146 }
2147
lucaslinc582d502022-01-27 09:07:00 +08002148 @Override
2149 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002150 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002151 @NonNull String packageName, @Nullable String callingAttributionTag) {
2152 Objects.requireNonNull(packageName);
2153 Objects.requireNonNull(lp);
2154 enforceNetworkStackOrSettingsPermission();
2155 if (!checkAccessPermission(-1 /* pid */, uid)) {
2156 return null;
2157 }
2158 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2159 }
2160
Qingxi Lib2748102020-01-08 12:51:49 -08002161 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2162 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2163 }
2164
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002165 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002166 if (nai == null) return null;
2167 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002168 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002169 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002170 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002171 }
2172
2173 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002174 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2175 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002176 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002177 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002178 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002179 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002180 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002181 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002182 }
2183
lucaslinc582d502022-01-27 09:07:00 +08002184 @Override
lucaslind2b06132022-03-02 10:56:57 +08002185 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2186 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2187 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002188 Objects.requireNonNull(nc);
2189 Objects.requireNonNull(packageName);
2190 enforceNetworkStackOrSettingsPermission();
2191 if (!checkAccessPermission(-1 /* pid */, uid)) {
2192 return null;
2193 }
2194 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2195 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2196 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2197 callingAttributionTag);
2198 }
2199
lucaslin69e1aa92022-03-22 18:15:09 +08002200 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2201 if (nc.getUnderlyingNetworks() != null
2202 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2203 nc.setUnderlyingNetworks(null);
2204 }
2205 }
2206
Qingxi Libb8da982020-01-17 17:54:27 -08002207 @VisibleForTesting
2208 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002209 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002210 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2211 // this would be expensive (one more permission check every time any NC callback is
2212 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2213 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2214 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002215 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002216 if (!checkSettingsPermission(callerPid, callerUid)) {
2217 newNc.setUids(null);
2218 newNc.setSSID(null);
2219 }
Etan Cohen107ae952018-12-30 17:59:59 -08002220 if (newNc.getNetworkSpecifier() != null) {
2221 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2222 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002223 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2224 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2225 newNc.setAdministratorUids(new int[0]);
2226 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002227 if (!checkAnyPermissionOf(
2228 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002229 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002230 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002231 }
lucaslin69e1aa92022-03-22 18:15:09 +08002232 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002233
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002234 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002235 }
2236
Roshan Pius98f59ec2021-02-23 08:47:39 -08002237 /**
2238 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002239 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002240 * NetworkCapabilities.
2241 * Note: This wrapper does not support any sort of invalidation and thus must not be
2242 * persistent or long-lived. It may only be used for the time necessary to
2243 * compute the redactions required by one particular NetworkCallback or
2244 * synchronous call.
2245 */
2246 private class RedactionPermissionChecker {
2247 private final int mCallingPid;
2248 private final int mCallingUid;
2249 @NonNull private final String mCallingPackageName;
2250 @Nullable private final String mCallingAttributionTag;
2251
2252 private Boolean mHasLocationPermission = null;
2253 private Boolean mHasLocalMacAddressPermission = null;
2254 private Boolean mHasSettingsPermission = null;
2255
2256 RedactionPermissionChecker(int callingPid, int callingUid,
2257 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2258 mCallingPid = callingPid;
2259 mCallingUid = callingUid;
2260 mCallingPackageName = callingPackageName;
2261 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002262 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002263
2264 private boolean hasLocationPermissionInternal() {
2265 final long token = Binder.clearCallingIdentity();
2266 try {
2267 return mLocationPermissionChecker.checkLocationPermission(
2268 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2269 null /* message */);
2270 } finally {
2271 Binder.restoreCallingIdentity(token);
2272 }
2273 }
2274
2275 /**
2276 * Returns whether the app holds location permission or not (might return cached result
2277 * if the permission was already checked before).
2278 */
2279 public boolean hasLocationPermission() {
2280 if (mHasLocationPermission == null) {
2281 // If there is no cached result, perform the check now.
2282 mHasLocationPermission = hasLocationPermissionInternal();
2283 }
2284 return mHasLocationPermission;
2285 }
2286
2287 /**
2288 * Returns whether the app holds local mac address permission or not (might return cached
2289 * result if the permission was already checked before).
2290 */
2291 public boolean hasLocalMacAddressPermission() {
2292 if (mHasLocalMacAddressPermission == null) {
2293 // If there is no cached result, perform the check now.
2294 mHasLocalMacAddressPermission =
2295 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2296 }
2297 return mHasLocalMacAddressPermission;
2298 }
2299
2300 /**
2301 * Returns whether the app holds settings permission or not (might return cached
2302 * result if the permission was already checked before).
2303 */
2304 public boolean hasSettingsPermission() {
2305 if (mHasSettingsPermission == null) {
2306 // If there is no cached result, perform the check now.
2307 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2308 }
2309 return mHasSettingsPermission;
2310 }
2311 }
2312
2313 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2314 @NetworkCapabilities.NetCapability long redaction) {
2315 return (redactions & redaction) != 0;
2316 }
2317
2318 /**
2319 * Use the provided |applicableRedactions| to check the receiving app's
2320 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2321 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2322 * before being sent to the corresponding app.
2323 */
2324 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2325 @NetworkCapabilities.RedactionType long applicableRedactions,
2326 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2327 boolean includeLocationSensitiveInfo) {
2328 long redactions = applicableRedactions;
2329 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2330 if (includeLocationSensitiveInfo
2331 && redactionPermissionChecker.hasLocationPermission()) {
2332 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2333 }
2334 }
2335 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2336 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2337 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2338 }
2339 }
2340 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2341 if (redactionPermissionChecker.hasSettingsPermission()) {
2342 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2343 }
2344 }
2345 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002346 }
2347
Qingxi Lib2748102020-01-08 12:51:49 -08002348 @VisibleForTesting
2349 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002350 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002351 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002352 int callingPid, int callingUid, @NonNull String callingPkgName,
2353 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002354 if (nc == null) {
2355 return null;
2356 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002357 // Avoid doing location permission check if the transport info has no location sensitive
2358 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002359 final RedactionPermissionChecker redactionPermissionChecker =
2360 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2361 callingAttributionTag);
2362 final long redactions = retrieveRequiredRedactions(
2363 nc.getApplicableRedactions(), redactionPermissionChecker,
2364 includeLocationSensitiveInfo);
2365 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002366 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002367 // TODO : calling UID is redacted because apps should generally not know what UID is
2368 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002369 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002370 newNc.setOwnerUid(INVALID_UID);
2371 return newNc;
2372 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002373 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2374 if (nc.hasTransport(TRANSPORT_VPN)) {
2375 // Owner UIDs already checked above. No need to re-check.
2376 return newNc;
2377 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002378 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2379 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002380 // compatibility for older apps.
2381 if (!includeLocationSensitiveInfo
2382 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002383 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002384 newNc.setOwnerUid(INVALID_UID);
2385 return newNc;
2386 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002387 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002388 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002389 newNc.setOwnerUid(INVALID_UID);
2390 }
Qingxi Lib2748102020-01-08 12:51:49 -08002391 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002392 }
2393
lucaslinc582d502022-01-27 09:07:00 +08002394 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002395 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2396 LinkProperties lp, int callerPid, int callerUid) {
2397 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002398 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2399 // this would be expensive (one more permission check every time any LP callback is
2400 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2401 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2402 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002403
2404 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2405 final boolean needsSanitization =
2406 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2407 if (!needsSanitization) {
2408 return new LinkProperties(lp);
2409 }
2410
2411 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002412 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002413 }
2414
2415 final LinkProperties newLp = new LinkProperties(lp);
2416 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2417 // object gets parceled.
2418 newLp.setCaptivePortalApiUrl(null);
2419 newLp.setCaptivePortalData(null);
2420 return newLp;
2421 }
2422
Roshan Pius08c94fb2020-01-16 12:17:17 -08002423 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2424 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002425 // There is no need to track the effective UID of the request here. If the caller
2426 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002427 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002428 // Unprivileged apps can only pass in null or their own UID.
2429 if (nc.getUids() == null) {
2430 // If the caller passes in null, the callback will also match networks that do not
2431 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2432 // In this case, redact everything in the request immediately. This ensures that the
2433 // app is not able to get any redacted information by filing an unredacted request
2434 // and observing whether the request matches something.
2435 if (nc.getNetworkSpecifier() != null) {
2436 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2437 }
2438 } else {
2439 nc.setSingleUid(callerUid);
2440 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002441 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002442 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002443 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002444
2445 // Clear owner UID; this can never come from an app.
2446 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002447 }
2448
Chalard Jean38354d12018-03-20 19:13:57 +09002449 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002450 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002451 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2452 }
2453 }
2454
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002455 @Override
2456 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2457 enforceAccessPermission();
2458 final int callerUid = Binder.getCallingUid();
2459 final long token = Binder.clearCallingIdentity();
2460 try {
2461 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2462 } finally {
2463 Binder.restoreCallingIdentity(token);
2464 }
2465 }
2466
junyulaiebd15162021-03-03 12:09:05 +08002467 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002468 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002469 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002470 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002471 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002472
Serik Beketayev05130302021-01-15 16:47:25 -08002473 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002474 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002475 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2476 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002477 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002478 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002479 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002480 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2481 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002482 }
2483 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002484 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002485 }
2486
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002487 @Override
junyulaiebd15162021-03-03 12:09:05 +08002488 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002489 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002490 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002491 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002492
2493 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2494 for (Network network : getAllNetworks()) {
2495 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002496 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002497 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2498 // NetworkCapabilities, which may contain UIDs of apps to which the
2499 // network applies. Should the UIDs be cleared so as not to leak or
2500 // interfere ?
2501 result.add(nai.getNetworkStateSnapshot());
2502 }
2503 }
2504 return result;
2505 }
2506
2507 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002508 public boolean isActiveNetworkMetered() {
2509 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002510
Qingxi Lib2748102020-01-08 12:51:49 -08002511 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002512 if (caps != null) {
2513 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2514 } else {
2515 // Always return the most conservative value
2516 return true;
2517 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002518 }
2519
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002520 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002521 * Ensures that the system cannot call a particular method.
2522 */
2523 private boolean disallowedBecauseSystemCaller() {
2524 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002525 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2526 // for devices launched with Q and above. However, existing devices upgrading to Q and
2527 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002528 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002529 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002530 log("This method exists only for app backwards compatibility"
2531 + " and must not be called by system services.");
2532 return true;
2533 }
2534 return false;
2535 }
2536
paulhub2c28682021-08-18 18:35:54 +08002537 private int getAppUid(final String app, final UserHandle user) {
2538 final PackageManager pm =
2539 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2540 final long token = Binder.clearCallingIdentity();
2541 try {
2542 return pm.getPackageUid(app, 0 /* flags */);
2543 } catch (PackageManager.NameNotFoundException e) {
2544 return -1;
2545 } finally {
2546 Binder.restoreCallingIdentity(token);
2547 }
2548 }
2549
2550 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2551 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2552 if (getAppUid(packageName, user) != callingUid) {
2553 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2554 }
2555 }
2556
Lorenzo Colitti23862912018-09-28 11:31:55 +09002557 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002558 * Ensure that a network route exists to deliver traffic to the specified
2559 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002560 * @param networkType the type of the network over which traffic to the
2561 * specified host is to be routed
2562 * @param hostAddress the IP address of the host to which the route is
2563 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002564 * @return {@code true} on success, {@code false} on failure
2565 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002566 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002567 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2568 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002569 if (disallowedBecauseSystemCaller()) {
2570 return false;
2571 }
paulhub2c28682021-08-18 18:35:54 +08002572 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002573 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002574 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002575 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002576 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002577
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002578 InetAddress addr;
2579 try {
2580 addr = InetAddress.getByAddress(hostAddress);
2581 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002582 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002583 return false;
2584 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002585
The Android Open Source Project28527d22009-03-03 19:31:44 -08002586 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002587 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002588 return false;
2589 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002590
2591 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2592 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002593 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002594 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2595 } else {
2596 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2597 }
2598 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002599 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002600
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002601 DetailedState netState;
2602 synchronized (nai) {
2603 netState = nai.networkInfo.getDetailedState();
2604 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002605
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002606 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002607 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002608 log("requestRouteToHostAddress on down network "
2609 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002610 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002611 }
2612 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002613 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002614
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002615 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002616 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002617 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002618 LinkProperties lp;
2619 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002620 synchronized (nai) {
2621 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002622 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002623 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002624 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002625 if (DBG) {
2626 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2627 }
Wink Saville32506bc2013-06-29 21:10:57 -07002628 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002629 } finally {
2630 Binder.restoreCallingIdentity(token);
2631 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002632 }
2633
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002634 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002635 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002636 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002637 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002638 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002639 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002640 if (bestRoute.getGateway().equals(addr)) {
2641 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002642 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002643 } else {
2644 // if we will connect to this through another route, add a direct route
2645 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002646 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002647 }
2648 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002649 if (DBG) log("Adding legacy route " + bestRoute +
2650 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002651
2652 final String dst = bestRoute.getDestinationLinkAddress().toString();
2653 final String nextHop = bestRoute.hasGateway()
2654 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002655 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002656 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2657 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002658 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002659 return false;
2660 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002661 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002662 }
2663
paulhu7c0a2e62021-01-08 00:51:49 +08002664 class DnsResolverUnsolicitedEventCallback extends
2665 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002666 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002667 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002668 try {
2669 mHandler.sendMessage(mHandler.obtainMessage(
2670 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002671 new PrivateDnsValidationUpdate(event.netId,
2672 InetAddresses.parseNumericAddress(event.ipAddress),
2673 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002674 } catch (IllegalArgumentException e) {
2675 loge("Error parsing ip address in validation event");
2676 }
2677 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002678
2679 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002680 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2681 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002682 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2683 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2684 // event callback for certain nai. e.g. cellular. Register here to pass to
2685 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002686 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002687 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2688 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002689 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002690 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002691 }
2692 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002693
2694 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002695 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2696 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2697 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002698 }
dalyk1720e542018-03-05 12:42:22 -05002699
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002700 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002701 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002702 return this.VERSION;
2703 }
2704
2705 @Override
2706 public String getInterfaceHash() {
2707 return this.HASH;
2708 }
paulhu7c0a2e62021-01-08 00:51:49 +08002709 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002710
2711 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002712 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2713 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002714
paulhu7c0a2e62021-01-08 00:51:49 +08002715 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002716 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002717 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002718 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002719 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002720 }
2721 }
2722
Sudheer Shanka9967d462021-03-18 19:09:25 +00002723 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002724 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002725 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2727 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002728 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002729 };
2730
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002731 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002732 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002733 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002734 }
2735
paulhu1a407652019-03-22 16:35:06 +08002736 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2737 for (String permission : permissions) {
2738 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2739 return true;
2740 }
2741 }
2742 return false;
2743 }
2744
Paul Jensen83f5d572014-08-29 09:54:01 -04002745 private void enforceInternetPermission() {
2746 mContext.enforceCallingOrSelfPermission(
2747 android.Manifest.permission.INTERNET,
2748 "ConnectivityService");
2749 }
2750
The Android Open Source Project28527d22009-03-03 19:31:44 -08002751 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002752 mContext.enforceCallingOrSelfPermission(
2753 android.Manifest.permission.ACCESS_NETWORK_STATE,
2754 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002755 }
2756
lucaslinc582d502022-01-27 09:07:00 +08002757 private boolean checkAccessPermission(int pid, int uid) {
2758 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2759 == PERMISSION_GRANTED;
2760 }
2761
paulhua6ee2122021-02-22 15:40:43 +08002762 /**
2763 * Performs a strict and comprehensive check of whether a calling package is allowed to
2764 * change the state of network, as the condition differs for pre-M, M+, and
2765 * privileged/preinstalled apps. The caller is expected to have either the
2766 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2767 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2768 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2769 * permission and cannot be revoked. See http://b/23597341
2770 *
2771 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2772 * of this app will be updated to the current time.
2773 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002774 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002775 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2776 == PackageManager.PERMISSION_GRANTED) {
2777 return;
2778 }
2779
2780 if (callingPkg == null) {
2781 throw new SecurityException("Calling package name is null.");
2782 }
2783
2784 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2785 final int uid = mDeps.getCallingUid();
2786 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2787 callingPkg, callingAttributionTag, null /* message */);
2788
2789 if (mode == AppOpsManager.MODE_ALLOWED) {
2790 return;
2791 }
2792
2793 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2794 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2795 return;
2796 }
2797
2798 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2799 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2800 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002801 }
2802
Charles He9369e612017-05-15 17:07:18 +01002803 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002804 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002805 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002806 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002807 }
2808
paulhu8e96a752019-08-12 16:25:11 +08002809 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002810 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002811 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002812 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002813 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002814 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002815 }
2816
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002817 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002818 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002819 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002820 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002821 android.Manifest.permission.NETWORK_SETTINGS,
2822 android.Manifest.permission.NETWORK_FACTORY,
2823 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2824 }
2825
2826 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002827 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002828 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002829 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002830 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2831 android.Manifest.permission.NETWORK_FACTORY,
2832 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2833 }
2834
lucaslin69e1aa92022-03-22 18:15:09 +08002835 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2836 return PERMISSION_GRANTED == mContext.checkPermission(
2837 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2838 || PERMISSION_GRANTED == mContext.checkPermission(
2839 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2840 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002841 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002842 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002843 }
2844
Chalard Jean9a396cc2018-02-21 18:43:54 +09002845 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002846 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002847 android.Manifest.permission.NETWORK_SETTINGS,
2848 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002849 }
2850
2851 private boolean checkSettingsPermission(int pid, int uid) {
2852 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002853 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2854 || PERMISSION_GRANTED == mContext.checkPermission(
2855 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002856 }
2857
paulhu8e96a752019-08-12 16:25:11 +08002858 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002859 enforceNetworkStackPermissionOr(mContext,
2860 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002861 }
2862
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002863 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002864 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002865 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002866 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002867 }
2868
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002869 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002870 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002871 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2872 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002873 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002874 }
2875
James Mattis8378aec2021-01-26 14:05:36 -08002876 private void enforceOemNetworkPreferencesPermission() {
2877 mContext.enforceCallingOrSelfPermission(
2878 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2879 "ConnectivityService");
2880 }
2881
James Mattisfa270db2021-05-31 17:11:10 -07002882 private void enforceManageTestNetworksPermission() {
2883 mContext.enforceCallingOrSelfPermission(
2884 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2885 "ConnectivityService");
2886 }
2887
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002888 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002889 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002890 android.Manifest.permission.NETWORK_STACK,
2891 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002892 }
2893
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002894 private boolean checkNetworkStackPermission(int pid, int uid) {
2895 return checkAnyPermissionOf(pid, uid,
2896 android.Manifest.permission.NETWORK_STACK,
2897 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2898 }
2899
paulhu1a407652019-03-22 16:35:06 +08002900 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2901 return checkAnyPermissionOf(pid, uid,
2902 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002903 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2904 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002905 }
2906
Paul Hu8fc2a552022-05-04 18:44:42 +08002907 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2908 boolean checkUidsAllowedList) {
2909 if (PermissionUtils.checkAnyPermissionOf(mContext,
2910 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2911 return true;
2912 }
2913
2914 // fallback to ConnectivityInternalPermission
2915 // TODO: Remove this fallback check after all apps have declared
2916 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2917 if (PermissionUtils.checkAnyPermissionOf(mContext,
2918 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2919 return true;
2920 }
2921
2922 // Check whether uid is in allowed on restricted networks list.
2923 if (checkUidsAllowedList
2924 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2925 return true;
2926 }
2927 return false;
2928 }
2929
2930 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2931 final int callingUid = mDeps.getCallingUid();
2932 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2933 throw new SecurityException("ConnectivityService: user " + callingUid
2934 + " has no permission to access restricted network.");
2935 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002936 }
2937
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002938 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002939 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002940 }
2941
Roshan Pius98f59ec2021-02-23 08:47:39 -08002942 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2943 return PERMISSION_GRANTED == mContext.checkPermission(
2944 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2945 }
2946
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002947 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002948 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002949 }
2950
2951 private void sendInetConditionBroadcast(NetworkInfo info) {
2952 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2953 }
2954
Wink Saville4f0de1e2011-08-04 15:01:58 -07002955 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002956 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002957 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002958 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002959 if (info.isFailover()) {
2960 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2961 info.setFailover(false);
2962 }
2963 if (info.getReason() != null) {
2964 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2965 }
2966 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002967 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2968 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002969 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002970 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002971 return intent;
2972 }
2973
2974 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2975 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2976 }
2977
Chiachang Wang3bc52762021-11-25 14:17:57 +08002978 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2979 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002980 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002981 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002982 if (!mSystemReady
2983 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002984 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002985 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002986 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002987 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002988 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002989 }
2990
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002991 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002992 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002993 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002994 final NetworkInfo ni = intent.getParcelableExtra(
2995 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002996 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2997 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2998 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002999 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003000 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003001 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003002 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003003 } finally {
3004 Binder.restoreCallingIdentity(ident);
3005 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003006 }
3007 }
3008
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003009 /**
Aaron Huang96011892020-06-27 07:18:23 +08003010 * Called by SystemServer through ConnectivityManager when the system is ready.
3011 */
3012 @Override
3013 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003014 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003015 throw new SecurityException("Calling Uid is not system uid.");
3016 }
3017 systemReadyInternal();
3018 }
3019
3020 /**
3021 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003022 */
3023 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003024 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003025 // Load flags after PackageManager is ready to query module version
3026 mFlags.loadFlags(mDeps, mContext);
3027
Aaron Huang9a57acf2020-12-08 10:03:29 +08003028 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3029 // listening network request which is sent by MultipathPolicyTracker won't be added
3030 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3031 // be called after PermissionMonitor#startMonitoring().
3032 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3033 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3034 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003035 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003036 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003037 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003038
Hugo Benichie5220992017-04-26 14:53:28 +09003039 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003040 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003041 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003042 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003043 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003044 }
3045 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003046
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003047 // Create network requests for always-on networks.
3048 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003049
3050 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003051 // Note that updating can be skipped here if the list is empty only because no uid
3052 // rules are applied before system ready. Normally, the empty uid list means to clear
3053 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003054 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3055 updateMobileDataPreferredUids();
3056 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003057
3058 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3059 if (SdkLevel.isAtLeastT()) {
3060 mBpfNetMaps.setPullAtomCallback(mContext);
3061 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003062 }
3063
The Android Open Source Project28527d22009-03-03 19:31:44 -08003064 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003065 * Start listening for default data network activity state changes.
3066 */
3067 @Override
3068 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003069 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003070 }
3071
3072 /**
3073 * Stop listening for default data network activity state changes.
3074 */
3075 @Override
3076 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003077 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003078 }
3079
3080 /**
3081 * Check whether the default network radio is currently active.
3082 */
3083 @Override
3084 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003085 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003086 }
3087
3088 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003089 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003090 * and set it on it's iface.
3091 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003092 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3093 final String iface = newLp.getInterfaceName();
3094 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003095 if (oldLp == null && mtu == 0) {
3096 // Silently ignore unset MTU value.
3097 return;
3098 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003099 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3100 if (VDBG) log("identical MTU - not setting");
3101 return;
3102 }
paulhucbbc3db2019-03-08 16:35:20 +08003103 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003104 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003105 return;
3106 }
sy.yun4aa73922013-09-02 05:24:09 +09003107
w19976e714f1d2014-08-05 15:18:11 -07003108 // Cannot set MTU without interface name
3109 if (TextUtils.isEmpty(iface)) {
3110 loge("Setting MTU size with null iface.");
3111 return;
3112 }
3113
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003114 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003115 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003116 mNetd.interfaceSetMtu(iface, mtu);
3117 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003118 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003119 }
3120 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003121
Chenbo Feng15416292018-11-08 17:36:21 -08003122 @VisibleForTesting
3123 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003124
lucaslin821c9782018-11-28 19:27:52 +08003125 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003126 String[] values = null;
3127 if (tcpBufferSizes != null) {
3128 values = tcpBufferSizes.split(",");
3129 }
3130
3131 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003132 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003133 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3134 values = tcpBufferSizes.split(",");
3135 }
3136
3137 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3138
3139 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003140 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003141
Chenbo Feng15416292018-11-08 17:36:21 -08003142 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3143 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3144 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003145 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003146 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003147 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003148 }
3149 }
3150
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003151 @Override
3152 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003153 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003154 NETWORK_RESTORE_DELAY_PROP_NAME);
3155 if(restoreDefaultNetworkDelayStr != null &&
3156 restoreDefaultNetworkDelayStr.length() != 0) {
3157 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003158 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003159 } catch (NumberFormatException e) {
3160 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003161 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003162 // if the system property isn't set, use the value for the apn type
3163 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3164
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003165 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3166 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003167 }
3168 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003169 }
3170
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003171 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003172 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003173 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003174 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003175 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003176 // Start gathering diagnostic information.
3177 netDiags.add(new NetworkDiagnostics(
3178 nai.network,
3179 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003180 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003181 DIAG_TIME_MS));
3182 }
3183
3184 for (NetworkDiagnostics netDiag : netDiags) {
3185 pw.println();
3186 netDiag.waitForMeasurements();
3187 netDiag.dump(pw);
3188 }
3189 }
3190
The Android Open Source Project28527d22009-03-03 19:31:44 -08003191 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003192 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3193 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003194 if (!checkDumpPermission(mContext, TAG, writer)) return;
3195
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003196 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003197 }
3198
lucaslin99473f62020-12-10 15:10:54 +08003199 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3200 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3201 != PackageManager.PERMISSION_GRANTED) {
3202 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003203 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003204 + " due to missing android.permission.DUMP permission");
3205 return false;
3206 } else {
3207 return true;
3208 }
3209 }
3210
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003211 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003212 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003213
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003214 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003215 dumpNetworkDiagnostics(pw);
3216 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003217 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003218 dumpNetworks(pw);
3219 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003220 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003221 dumpNetworkRequests(pw);
3222 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003223 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3224 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3225 dumpTrafficController(pw, fd, verbose);
3226 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003227 }
Erik Kline9647f382015-06-05 17:47:34 +09003228
Junyu Lai0da479b2022-04-20 15:06:29 +08003229 pw.println("NetworkProviders for:");
3230 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003231 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003232 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003233 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003234 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003235 pw.println();
3236
Chalard Jean5b409c72021-02-04 13:12:59 +09003237 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003238 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003239 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003240 pw.println("none");
3241 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003242 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003243 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003244 pw.println();
3245
James Mattis8b298a02021-06-01 22:34:04 -07003246 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003247 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003248 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003249 pw.decreaseIndent();
3250 pw.println();
3251
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003252 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003253 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003254 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003255 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003256 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003257
junyulaif2c67e42018-08-07 19:50:45 +08003258 pw.println("Status for known UIDs:");
3259 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003260 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003261 for (int i = 0; i < size; i++) {
3262 // Don't crash if the array is modified while dumping in bugreports.
3263 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003264 final int uid = mUidBlockedReasons.keyAt(i);
3265 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3266 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003267 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003268 } catch (ArrayIndexOutOfBoundsException e) {
3269 pw.println(" ArrayIndexOutOfBoundsException");
3270 } catch (ConcurrentModificationException e) {
3271 pw.println(" ConcurrentModificationException");
3272 }
3273 }
3274 pw.println();
3275 pw.decreaseIndent();
3276
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003277 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003278 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003279 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003280 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003281 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003282
Junyu Lai0da479b2022-04-20 15:06:29 +08003283 pw.println("Network Offers:");
3284 pw.increaseIndent();
3285 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3286 pw.println(offerInfo.offer);
3287 }
3288 pw.decreaseIndent();
3289 pw.println();
3290
Robert Greenwalt94e22142014-07-30 16:31:24 -07003291 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003292
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003293 pw.println();
markchien5e866652019-09-30 14:40:57 +08003294 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003295
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003296 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003297 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003298
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003299 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003300
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003301 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003302 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003303 pw.println("mNetworkRequestInfoLogs (most recent first):");
3304 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003305 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003306 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003307
3308 pw.println();
3309 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3310 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003311 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003312 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003313
3314 pw.println();
3315 pw.println("NetTransition WakeLock activity (most recent first):");
3316 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003317 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3318 pw.println("total releases: " + mTotalWakelockReleases);
3319 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3320 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3321 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3322 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3323 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3324 }
James Mattiscb1e0362021-04-06 17:07:42 -07003325 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003326
3327 pw.println();
3328 pw.println("bandwidth update requests (by uid):");
3329 pw.increaseIndent();
3330 synchronized (mBandwidthRequests) {
3331 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3332 pw.println("[" + mBandwidthRequests.keyAt(i)
3333 + "]: " + mBandwidthRequests.valueAt(i));
3334 }
3335 }
3336 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003337 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003338
James Mattiscb1e0362021-04-06 17:07:42 -07003339 pw.println();
3340 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3341 pw.increaseIndent();
3342 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003343 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003344 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003345
3346 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003347
3348 pw.println();
3349 pw.println("Permission Monitor:");
3350 pw.increaseIndent();
3351 mPermissionMonitor.dump(pw);
3352 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003353
3354 pw.println();
3355 pw.println("Legacy network activity:");
3356 pw.increaseIndent();
3357 mNetworkActivityTracker.dump(pw);
3358 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003359 }
3360
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003361 private void dumpNetworks(IndentingPrintWriter pw) {
3362 for (NetworkAgentInfo nai : networksSortedById()) {
3363 pw.println(nai.toString());
3364 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003365 pw.println("Nat464Xlat:");
3366 pw.increaseIndent();
3367 nai.dumpNat464Xlat(pw);
3368 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003369 pw.println(String.format(
3370 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3371 nai.numForegroundNetworkRequests(),
3372 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3373 nai.numBackgroundNetworkRequests(),
3374 nai.numNetworkRequests()));
3375 pw.increaseIndent();
3376 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3377 pw.println(nai.requestAt(i).toString());
3378 }
3379 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003380 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003381 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003382 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003383 pw.decreaseIndent();
3384 pw.decreaseIndent();
3385 }
3386 }
3387
James Mattis8b298a02021-06-01 22:34:04 -07003388 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3389 if (!mProfileNetworkPreferences.isEmpty()) {
3390 pw.println("Profile preferences:");
3391 pw.increaseIndent();
3392 pw.println(mProfileNetworkPreferences.preferences);
3393 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003394 }
James Mattis8b298a02021-06-01 22:34:04 -07003395 if (!mOemNetworkPreferences.isEmpty()) {
3396 pw.println("OEM preferences:");
3397 pw.increaseIndent();
3398 pw.println(mOemNetworkPreferences);
3399 pw.decreaseIndent();
3400 }
3401 if (!mMobileDataPreferredUids.isEmpty()) {
3402 pw.println("Mobile data preferred UIDs:");
3403 pw.increaseIndent();
3404 pw.println(mMobileDataPreferredUids);
3405 pw.decreaseIndent();
3406 }
James Mattis45d81842021-01-10 14:24:24 -08003407
James Mattis8b298a02021-06-01 22:34:04 -07003408 pw.println("Default requests:");
3409 pw.increaseIndent();
3410 dumpPerAppDefaultRequests(pw);
3411 pw.decreaseIndent();
3412 }
3413
3414 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003415 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3416 if (mDefaultRequest == defaultRequest) {
3417 continue;
3418 }
3419
James Mattis8b298a02021-06-01 22:34:04 -07003420 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3421 final String networkOutput;
3422 if (null == satisfier) {
3423 networkOutput = "null";
3424 } else if (mNoServiceNetwork.equals(satisfier)) {
3425 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003426 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003427 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003428 }
James Mattis8b298a02021-06-01 22:34:04 -07003429 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3430 ? "" : " asUid: " + defaultRequest.mAsUid;
3431 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3432 + defaultRequest.mPid + asUidString + "]";
3433 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3434 + " Preference order: " + defaultRequest.mPreferenceOrder
3435 + " Tracked UIDs: " + defaultRequest.getUids();
3436 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003437 }
3438 }
3439
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003440 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003441 NetworkRequestInfo[] infos = null;
3442 while (infos == null) {
3443 try {
3444 infos = requestsSortedById();
3445 } catch (ConcurrentModificationException e) {
3446 // mNetworkRequests should only be accessed from handler thread, except dump().
3447 // As dump() is never called in normal usage, it would be needlessly expensive
3448 // to lock the collection only for its benefit. Instead, retry getting the
3449 // requests if ConcurrentModificationException is thrown during dump().
3450 }
3451 }
3452 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003453 pw.println(nri.toString());
3454 }
3455 }
3456
Ken Chene6d511f2022-01-25 11:10:42 +08003457 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3458 boolean verbose) {
3459 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003460 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003461 } catch (ServiceSpecificException e) {
3462 pw.println(e.getMessage());
3463 } catch (IOException e) {
3464 loge("Dump BPF maps failed, " + e);
3465 }
3466 }
3467
Chalard Jean524f0b12021-10-25 21:11:56 +09003468 private void dumpAllRequestInfoLogsToLogcat() {
3469 try (PrintWriter logPw = new PrintWriter(new Writer() {
3470 @Override
3471 public void write(final char[] cbuf, final int off, final int len) {
3472 // This method is called with 0-length and 1-length arrays for empty strings
3473 // or strings containing only the DEL character.
3474 if (len <= 1) return;
3475 Log.e(TAG, new String(cbuf, off, len));
3476 }
3477 @Override public void flush() {}
3478 @Override public void close() {}
3479 })) {
3480 mNetworkRequestInfoLogs.dump(logPw);
3481 }
3482 }
3483
Hugo Benichia480ba52018-09-03 08:19:02 +09003484 /**
3485 * Return an array of all current NetworkAgentInfos sorted by network id.
3486 */
3487 private NetworkAgentInfo[] networksSortedById() {
3488 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003489 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003490 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003491 return networks;
3492 }
3493
3494 /**
3495 * Return an array of all current NetworkRequest sorted by request id.
3496 */
James Mattis258ea3c2020-11-15 15:04:40 -08003497 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003498 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003499 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003500 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003501 // Sort the array based off the NRI containing the min requestId in its requests.
3502 Arrays.sort(requests,
3503 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3504 Comparator.comparingInt(req -> req.requestId)).requestId
3505 )
3506 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003507 return requests;
3508 }
3509
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003510 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003511 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003512 if (officialNai != null && officialNai.equals(nai)) return true;
3513 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003514 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003515 " - " + nai);
3516 }
3517 return false;
3518 }
3519
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003520 private boolean isDisconnectRequest(Message msg) {
3521 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3522 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3523 return info.getState() == NetworkInfo.State.DISCONNECTED;
3524 }
3525
Robert Greenwalt2034b912009-08-12 16:08:25 -07003526 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003527 private class NetworkStateTrackerHandler extends Handler {
3528 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003529 super(looper);
3530 }
3531
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003532 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003533 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3534 final NetworkAgentInfo nai = arg.first;
3535 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003536 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003537 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003538 }
3539 return;
3540 }
3541
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003542 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003543 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003544 return;
3545 }
3546
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003547 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003548 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003549 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3550 final NetworkCapabilities sanitized =
3551 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003552 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003553 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003554 break;
3555 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003556 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003557 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003558 processLinkPropertiesFromAgent(nai, newLp);
3559 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003560 break;
3561 }
3562 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003563 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003564 updateNetworkInfo(nai, info);
3565 break;
3566 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003567 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003568 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003569 break;
3570 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003571 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003572 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003573 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003574 // Note that if the NAI had been connected, this would affect the
3575 // score, and therefore would require re-mixing the score and performing
3576 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003577 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003578 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3579 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003580 // Mark the network as temporarily accepting partial connectivity so that it
3581 // will be validated (and possibly become default) even if it only provides
3582 // partial internet access. Note that if user connects to partial connectivity
3583 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3584 // out of wifi coverage) and if the same wifi is available again, the device
3585 // will auto connect to this wifi even though the wifi has "no internet".
3586 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003587 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003588 break;
3589 }
junyulai011b1f12019-01-03 18:50:15 +08003590 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003591 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003592 break;
3593 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003594 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003595 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003596 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003597
3598 if (isLegacyLockdownNai(nai)
3599 && (underlying == null || underlying.size() != 1)) {
3600 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3601 + " must have exactly one underlying network: " + underlying);
3602 }
3603
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003604 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3605 nai.declaredUnderlyingNetworks = (underlying != null)
3606 ? underlying.toArray(new Network[0]) : null;
3607
3608 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3609 if (DBG) {
3610 log(nai.toShortString() + " changed underlying networks to "
3611 + Arrays.toString(nai.declaredUnderlyingNetworks));
3612 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003613 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003614 notifyIfacesChangedForNetworkStats();
3615 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003616 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003617 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003618 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3619 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3620 nai.teardownDelayMs = msg.arg1;
3621 } else {
3622 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3623 }
Chalard Jean550b5212021-03-05 23:07:53 +09003624 break;
3625 }
3626 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3627 nai.setLingerDuration((int) arg.second);
3628 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003629 }
Tyler Wear72388212021-09-09 14:49:02 -07003630 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3631 DscpPolicy policy = (DscpPolicy) arg.second;
3632 if (mDscpPolicyTracker != null) {
3633 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3634 }
3635 break;
3636 }
3637 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3638 if (mDscpPolicyTracker != null) {
3639 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3640 }
3641 break;
3642 }
3643 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3644 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003645 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003646 }
3647 break;
3648 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003649 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003650 // If nai is not yet created, or is already destroyed, ignore.
3651 if (!shouldDestroyNativeNetwork(nai)) break;
3652
3653 final int timeoutMs = (int) arg.second;
3654 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3655 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3656 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3657 }
3658
3659 // Marking a network awaiting replacement is used to ensure that any requests
3660 // satisfied by the network do not switch to another network until a
3661 // replacement is available or the wait for a replacement times out.
3662 // If the network is inactive (i.e., nascent or lingering), then there are no
3663 // such requests, and there is no point keeping it. Just tear it down.
3664 // Note that setLingerDuration(0) cannot be used to do this because the network
3665 // could be nascent.
3666 nai.clearInactivityState();
3667 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3668 Log.d(TAG, nai.toShortString()
3669 + " marked awaiting replacement is unneeded, tearing down instead");
3670 teardownUnneededNetwork(nai);
3671 break;
3672 }
3673
3674 Log.d(TAG, "Marking " + nai.toShortString()
3675 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3676 destroyNativeNetwork(nai);
3677
3678 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3679 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3680 // consider the fact that the network could already have disconnected or been
3681 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3682 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3683 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3684 mKeepaliveTracker.handleStopAllKeepalives(nai,
3685 SocketKeepalive.ERROR_INVALID_NETWORK);
3686
3687 nai.updateScoreForNetworkAgentUpdate();
3688 // This rematch is almost certainly not going to result in any changes, because
3689 // the destroyed flag is only just above the "current satisfier wins"
3690 // tie-breaker. But technically anything that affects scoring should rematch.
3691 rematchAllNetworksAndRequests();
3692 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3693 break;
3694 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003695 }
3696 }
3697
3698 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003699 final int netId = msg.arg2;
3700 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003701 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003702 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003703 switch (msg.what) {
3704 default:
3705 return false;
lucasline117e2e2019-10-22 18:27:33 +08003706 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003707 if (nai == null) {
3708 break;
3709 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003710 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3711 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003712 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003713 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003714 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003715 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003716 if (probePrivateDnsCompleted) {
3717 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3718 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003719 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003720 }
3721 // Only show the notification when the private DNS is broken and the
3722 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003723 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003724 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3725 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003726 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003727 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3728 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3729 // private DNS is broken, it means this network is being reevaluated.
3730 // Either probing private DNS is not necessary any more or it hasn't been
3731 // done yet. In either case, the networkCapabilities should be updated to
3732 // reflect the new status.
3733 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003734 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003735 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003736 }
3737 break;
3738 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003739 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003740 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3741
Erik Kline31b4a9e2018-01-11 21:07:29 +09003742 if (nai == null) break;
3743
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003744 handleNetworkTested(nai, results.mTestResult,
3745 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003746 break;
3747 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003748 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003749 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003750 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003751 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003752 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003753 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003754 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3755 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003756 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003757 if (nai == null) {
3758 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3759 break;
3760 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003761 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003762 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003763 (PendingIntent) msg.obj,
3764 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003765 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003766 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003767 break;
3768 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003769 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003770 if (nai == null) break;
3771
Erik Kline9a62f012018-03-21 07:18:33 -07003772 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003773 break;
3774 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003775 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003776 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003777 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003778 break;
3779 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003780 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003781 return true;
3782 }
3783
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003784 private void handleNetworkTested(
3785 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003786 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3787 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003788 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003789
3790 // If there is any kind of working networking, then the NAI has been evaluated
3791 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3792 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003793 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003794 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003795 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3796 // any callback that receives onAvailable for that rematch receives an extra caps
3797 // callback. To prevent that, update the score in the agent so the updates below won't
3798 // see an update to both caps and score at the same time.
3799 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003800 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3801
he_won.hwang881307a2022-03-15 21:23:52 +09003802 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3803 // Assume the validation failure is due to a temporary failure after roaming
3804 // and ignore it. NetworkMonitor will continue to retry validation. If it
3805 // continues to fail after the block timeout expires, the network will be
3806 // marked unvalidated. If it succeeds, then validation state will not change.
3807 return;
3808 }
3809
Chalard Jean254bd162022-08-25 13:04:51 +09003810 final boolean wasValidated = nai.isValidated();
3811 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003812 final boolean wasPortal = nai.captivePortalDetected();
3813 nai.setPartialConnectivity(partial);
3814 nai.setCaptivePortalDetected(portal);
3815 nai.updateScoreForNetworkAgentUpdate();
3816 final boolean partialConnectivityChanged = (wasPartial != partial);
3817 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003818
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003819 if (DBG) {
3820 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3821 ? " with redirect to " + redirectUrl
3822 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003823 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003824 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003825 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003826 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003827 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003828 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003829 if (valid) {
3830 handleFreshlyValidatedNetwork(nai);
3831 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3832 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003833 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003834 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003835 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003836 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003837 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003838 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003839 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003840 NotificationType.PRIVATE_DNS_BROKEN);
3841 // If network becomes valid, the hasShownBroken should be reset for
3842 // that network so that the notification will be fired when the private
3843 // DNS is broken again.
3844 nai.networkAgentConfig.hasShownBroken = false;
3845 }
3846 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003847 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09003848 } else if (portalChanged) {
3849 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3850 == getCaptivePortalMode()) {
3851 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3852 nai.onPreventAutomaticReconnect();
3853 teardownUnneededNetwork(nai);
3854 return;
3855 } else {
3856 updateCapabilitiesForNetwork(nai);
3857 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09003858 } else if (becameEvaluated) {
3859 // If valid or partial connectivity changed, updateCapabilities* has
3860 // done the rematch.
3861 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003862 }
3863 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003864
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003865 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003866 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003867 nai.onValidationStatusChanged(
3868 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3869 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003870
3871 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003872 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003873 // immediately. Re-notify partial connectivity silently if no internet
3874 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003875 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003876 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003877 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
3878 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003879 }
3880
Chalard Jean254bd162022-08-25 13:04:51 +09003881 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003882 handleNetworkUnvalidated(nai);
3883 }
3884 }
3885
Calvin Ondada1452016-10-11 15:10:46 -07003886 private int getCaptivePortalMode() {
3887 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003888 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3889 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003890 }
3891
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003892 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3893 switch (msg.what) {
3894 default:
3895 return false;
3896 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3897 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3898 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3899 handleLingerComplete(nai);
3900 }
3901 break;
3902 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003903 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3904 handleNetworkAgentRegistered(msg);
3905 break;
3906 }
3907 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3908 handleNetworkAgentDisconnected(msg);
3909 break;
3910 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003911 }
3912 return true;
3913 }
3914
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003915 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003916 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003917 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003918 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003919 maybeHandleNetworkAgentMessage(msg);
3920 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003921 }
3922 }
3923
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003924 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003925 private final int mNetId;
3926 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003927
3928 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003929 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003930 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003931 }
3932
3933 @Override
3934 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3935 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003936 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003937 }
3938
3939 @Override
3940 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003941 // Legacy version of notifyNetworkTestedWithExtras.
3942 // Would only be called if the system has a NetworkStack module older than the
3943 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003944 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003945 }
3946
3947 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003948 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003949 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3950 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003951 final Message msg = mTrackerHandler.obtainMessage(
3952 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003953 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003954 new NetworkTestedResults(
3955 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003956 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003957
3958 // Invoke ConnectivityReport generation for this Network test event.
3959 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3960 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003961
Cody Kestingf1120be2020-08-03 18:01:40 -07003962 // NetworkMonitor reports the network validation result as a bitmask while
3963 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3964 // logical value for ConnectivityDiagnostics.
3965 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3966 p.result);
3967
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003968 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003969 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003970 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3971 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3972
Aaron Huang959d3642021-01-21 15:47:41 +08003973 ConnectivityReportEvent reportEvent =
3974 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3975 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003976 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003977 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003978 }
3979
3980 @Override
3981 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3982 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3983 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003984 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003985 }
3986
3987 @Override
lucasline117e2e2019-10-22 18:27:33 +08003988 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3989 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3990 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003991 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003992 }
3993
3994 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003995 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3996 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3997 EVENT_CAPPORT_DATA_CHANGED,
3998 0, mNetId, data));
3999 }
4000
4001 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004002 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004003 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004004 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004005
4006 final PendingIntent pendingIntent;
4007 // Only the system server can register notifications with package "android"
4008 final long token = Binder.clearCallingIdentity();
4009 try {
paulhu7746e4e2020-06-09 19:07:03 +08004010 pendingIntent = PendingIntent.getBroadcast(
4011 mContext,
4012 0 /* requestCode */,
4013 intent,
4014 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004015 } finally {
4016 Binder.restoreCallingIdentity(token);
4017 }
4018 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4019 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004020 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004021 }
4022
4023 @Override
4024 public void hideProvisioningNotification() {
4025 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004026 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004027 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004028
4029 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004030 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004031 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004032 }
4033
4034 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004035 public int getInterfaceVersion() {
4036 return this.VERSION;
4037 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004038
4039 @Override
4040 public String getInterfaceHash() {
4041 return this.HASH;
4042 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004043 }
4044
Cody Kestingf1120be2020-08-03 18:01:40 -07004045 /**
4046 * Converts the given NetworkMonitor-specific validation result bitmask to a
4047 * ConnectivityDiagnostics-specific validation result int.
4048 */
4049 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4050 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4051 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4052 }
4053 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4054 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4055 }
4056 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4057 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4058 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4059 }
4060
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004061 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004062 log("Data stall detected with methods: " + p.detectionMethod);
4063
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004064 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004065 int detectionMethod = 0;
4066 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4067 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4068 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4069 }
4070 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4071 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4072 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4073 p.tcpMetricsCollectionPeriodMillis);
4074 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004075 }
4076
Cody Kestingf53a0752020-04-15 12:33:28 -07004077 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004078 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004079 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004080
4081 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4082 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4083 // the cost of going through two handlers.
4084 mConnectivityDiagnosticsHandler.sendMessage(msg);
4085 }
4086
Cody Kestingb37958e2020-05-15 10:36:01 -07004087 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4088 return (p.detectionMethod & detectionMethod) != 0;
4089 }
4090
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004091 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4092 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004093 }
4094
Erik Klinea73af002018-06-26 18:53:43 +09004095 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4096 if (nai == null) return;
4097 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4098 // in order to restart a validation pass from within netd.
4099 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4100 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004101 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004102 }
4103 }
4104
Erik Kline31b4a9e2018-01-11 21:07:29 +09004105 private void handlePrivateDnsSettingsChanged() {
4106 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4107
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004108 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004109 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004110 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004111 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4112 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004113 }
4114 }
4115
Erik Kline9a62f012018-03-21 07:18:33 -07004116 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4117 // Private DNS only ever applies to networks that might provide
4118 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004119 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004120
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004121 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004122 // schedule DNS resolutions. If a DNS resolution is required the
4123 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004124 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004125
4126 // With Private DNS bypass support, we can proceed to update the
4127 // Private DNS config immediately, even if we're in strict mode
4128 // and have not yet resolved the provider name into a set of IPs.
4129 updatePrivateDns(nai, cfg);
4130 }
4131
4132 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4133 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004134 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004135 }
4136
dalyk1720e542018-03-05 12:42:22 -05004137 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4138 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4139 if (nai == null) {
4140 return;
4141 }
4142 mDnsManager.updatePrivateDnsValidation(update);
4143 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4144 }
4145
paulhu7c0a2e62021-01-08 00:51:49 +08004146 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004147 int prefixLength) {
4148 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4149 if (nai == null) return;
4150
paulhu7c0a2e62021-01-08 00:51:49 +08004151 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4152 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004153
4154 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004155 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004156 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004157 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004158 prefixLength);
4159 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004160 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004161 return;
4162 }
4163 }
4164
Lorenzo Colittid523d142020-04-01 20:16:30 +09004165 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004166 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4167 }
4168
Hai Shalome58bdc62021-01-11 18:45:34 -08004169 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004170 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004171 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004172 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4173 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4174 }
4175
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004176 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004177 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004178 * @param nai the agent info to update
4179 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004180 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004181 */
junyulai2b6f0c22021-02-03 20:15:30 +08004182 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4183 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4184 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004185 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004186 // one lingered request, set inactive.
4187 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004188 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004189 if (DBG) log("Unsetting inactive " + nai.toShortString());
4190 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004191 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004192 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004193 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004194 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4195 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004196 }
junyulai2b6f0c22021-02-03 20:15:30 +08004197 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004198 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004199 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004200 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004201 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004202 }
4203
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004204 private void handleNetworkAgentRegistered(Message msg) {
4205 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4206 if (!mNetworkAgentInfos.contains(nai)) {
4207 return;
4208 }
4209
4210 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4211 if (VDBG) log("NetworkAgent registered");
4212 } else {
4213 loge("Error connecting NetworkAgent");
4214 mNetworkAgentInfos.remove(nai);
4215 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004216 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004217 synchronized (mNetworkForNetId) {
4218 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004219 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004220 mNetIdManager.releaseNetId(nai.network.getNetId());
4221 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004222 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004223 }
4224 }
4225 }
Paul Jensend5f53392014-11-25 15:26:53 -05004226
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004227 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004228 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004229 }
4230
he_won.hwang881307a2022-03-15 21:23:52 +09004231 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004232 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004233 if (SdkLevel.isAtLeastT()) return false;
4234 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4235 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4236 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4237 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004238 final long currentTimeMs = SystemClock.elapsedRealtime();
4239 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004240 if (timeSinceLastRoam <= blockTimeOut) {
4241 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4242 return true;
4243 }
4244 }
4245 return false;
4246 }
4247
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004248 private void handleNetworkAgentDisconnected(Message msg) {
4249 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004250 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004251 }
4252
Chalard Jeand9fffc32018-05-11 20:19:20 +09004253 // Destroys a network, remove references to it from the internal state managed by
4254 // ConnectivityService, free its interfaces and clean up.
4255 // Must be called on the Handler thread.
4256 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004257 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004258
4259 if (!mNetworkAgentInfos.contains(nai)) return;
4260
Chalard Jeand9fffc32018-05-11 20:19:20 +09004261 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004262 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004263 }
lucaslinb25c9a62019-02-12 15:30:13 +08004264 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004265 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004266 // A network agent has disconnected.
4267 // TODO - if we move the logic to the network agent (have them disconnect
4268 // because they lost all their requests or because their score isn't good)
4269 // then they would disconnect organically, report their new state and then
4270 // disconnect the channel.
4271 if (nai.networkInfo.isConnected()) {
4272 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4273 null, null);
4274 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004275 final boolean wasDefault = isDefaultNetwork(nai);
4276 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004277 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004278 }
4279 notifyIfacesChangedForNetworkStats();
4280 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4281 // by other networks that are already connected. Perhaps that can be done by
4282 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4283 // of rematchAllNetworksAndRequests
4284 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004285 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004286
4287 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004288 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4289 // Disable wakeup packet monitoring for each interface.
4290 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4291 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004292 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004293 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004294 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004295 synchronized (mNetworkForNetId) {
4296 // Remove the NetworkAgent, but don't mark the netId as
4297 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004298 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004299 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004300 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004301 // Remove all previously satisfied requests.
4302 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004303 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004304 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004305 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004306 if (currentNetwork != null
4307 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004308 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004309 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4310 // rematch not to keep disconnected agents instead of setting it here ; this
4311 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004312 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004313 for (final NetworkOfferInfo noi : mNetworkOffers) {
4314 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004315 }
James Mattise3ef1912020-12-20 11:09:58 -08004316
Chalard Jean5b409c72021-02-04 13:12:59 +09004317 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004318 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004319 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004320 // network, because while incorrect this is the closest to the old (also
4321 // incorrect) behavior.
4322 mNetworkActivityTracker.updateDataActivityTracking(
4323 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004324 ensureNetworkTransitionWakelock(nai.toShortString());
4325 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004326 }
4327 }
junyulai2b6f0c22021-02-03 20:15:30 +08004328 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004329 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004330 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004331 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004332 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004333 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004334 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004335
4336 // Immediate teardown.
4337 if (nai.teardownDelayMs == 0) {
4338 destroyNetwork(nai);
4339 return;
4340 }
4341
4342 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004343 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304344 try {
4345 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4346 } catch (RemoteException e) {
4347 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4348 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004349 }
4350 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4351 }
4352
4353 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004354 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004355 // Tell netd to clean up the configuration for this network
4356 // (routing rules, DNS, etc).
4357 // This may be slow as it requires a lot of netd shelling out to ip and
4358 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004359 // after we've rematched networks with requests (which might change the default
4360 // network or service a new request from an app), so network traffic isn't interrupted
4361 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004362 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004363 }
Chalard Jean254bd162022-08-25 13:04:51 +09004364 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004365 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4366 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4367 // false if the network was never created.
4368 // TODO: delete when S is no longer supported.
4369 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004370 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004371 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004372 }
4373
Ken Chen6df7a902021-04-09 15:08:42 +08004374 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004375 try {
4376 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004377 final NativeNetworkConfig config;
4378 if (nai.isVPN()) {
4379 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004380 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004381 return false;
4382 }
4383 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4384 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004385 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004386 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004387 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004388 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004389 getNetworkPermission(nai.networkCapabilities),
4390 false /* secure */,
4391 VpnManager.TYPE_VPN_NONE,
4392 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004393 }
Ken Chen6df7a902021-04-09 15:08:42 +08004394 mNetd.networkCreate(config);
4395 mDnsResolver.createNetworkCache(nai.network.getNetId());
4396 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4397 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004398 return true;
4399 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004400 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004401 return false;
4402 }
4403 }
4404
Ken Chen6df7a902021-04-09 15:08:42 +08004405 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004406 if (mDscpPolicyTracker != null) {
4407 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4408 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004409 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004410 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004411 } catch (RemoteException | ServiceSpecificException e) {
4412 loge("Exception destroying network(networkDestroy): " + e);
4413 }
4414 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004415 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004416 } catch (RemoteException | ServiceSpecificException e) {
4417 loge("Exception destroying network: " + e);
4418 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004419 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4420 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4421 // gets created, could add data to DnsManager data structures that will never get deleted.
4422 mDnsManager.removeNetwork(nai.network);
4423
4424 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004425 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004426 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4427 }
4428
Chalard Jean254bd162022-08-25 13:04:51 +09004429 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004430 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004431 }
4432
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004433 // If this method proves to be too slow then we can maintain a separate
4434 // pendingIntent => NetworkRequestInfo map.
4435 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4436 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004437 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4438 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4439 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004440 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004441 return entry.getValue();
4442 }
4443 }
4444 return null;
4445 }
4446
Chalard Jean524f0b12021-10-25 21:11:56 +09004447 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4448 if (SdkLevel.isAtLeastT()) {
4449 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4450 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4451 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4452 // bug is fixed.
4453 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004454 throw new IllegalStateException("This NRI is already registered. New : " + nri
4455 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004456 }
4457 }
4458 }
4459 }
4460
Chalard Jeanac9ace02022-01-26 16:54:05 +09004461 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4462 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004463 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004464 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4465 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004466 }
4467 return false;
4468 }
4469
James Mattisf7027322020-12-13 16:28:14 -08004470 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004471 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004472 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4473 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4474 final NetworkRequestInfo existingRequest =
4475 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004476 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004477 if (DBG) {
4478 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4479 + nri.mRequests.get(0) + " because their intents matched.");
4480 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004481 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004482 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004483 }
Erik Kline05f2b402015-04-30 12:58:40 +09004484 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004485 }
4486
James Mattisf7027322020-12-13 16:28:14 -08004487 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004488 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004489 }
4490
James Mattis3ce3d3c2021-02-09 18:18:28 -08004491 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004492 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004493 for (final NetworkRequestInfo nri : nris) {
4494 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004495 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004496 for (final NetworkRequest req : nri.mRequests) {
4497 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004498 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004499 if (req.isListen()) {
4500 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4501 if (req.networkCapabilities.hasSignalStrength()
4502 && network.satisfiesImmutableCapabilitiesOf(req)) {
4503 updateSignalStrengthThresholds(network, "REGISTER", req);
4504 }
James Mattisf7027322020-12-13 16:28:14 -08004505 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004506 }
4507 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004508
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004509 // If this NRI has a satisfier already, it is replacing an older request that
4510 // has been removed. Track it.
4511 final NetworkRequest activeRequest = nri.getActiveRequest();
4512 if (null != activeRequest) {
4513 // If there is an active request, then for sure there is a satisfier.
4514 nri.getSatisfier().addRequest(activeRequest);
4515 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004516 }
James Mattisf7027322020-12-13 16:28:14 -08004517
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004518 if (mFlags.noRematchAllRequestsOnRegister()) {
4519 rematchNetworksAndRequests(nris);
4520 } else {
4521 rematchAllNetworksAndRequests();
4522 }
James Mattis45d81842021-01-10 14:24:24 -08004523
Chalard Jean0354d8c2021-01-12 10:58:56 +09004524 // Requests that have not been matched to a network will not have been sent to the
4525 // providers, because the old satisfier and the new satisfier are the same (null in this
4526 // case). Send these requests to the providers.
4527 for (final NetworkRequestInfo nri : nris) {
4528 for (final NetworkOfferInfo noi : mNetworkOffers) {
4529 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004530 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004531 }
4532 }
4533
James Mattisf7027322020-12-13 16:28:14 -08004534 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4535 final int callingUid) {
4536 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004537 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004538 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4539 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4540 handleReleaseNetworkRequest(
4541 nri.mRequests.get(0),
4542 callingUid,
4543 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004544 }
4545 }
4546
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004547 // Determines whether the network is the best (or could become the best, if it validated), for
4548 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4549 // on the value of reason:
4550 //
4551 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4552 // then it should be torn down.
4553 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4554 // then it should be lingered.
4555 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004556 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004557
Chalard Jean254bd162022-08-25 13:04:51 +09004558 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004559 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4560 return false;
4561 }
4562
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004563 final int numRequests;
4564 switch (reason) {
4565 case TEARDOWN:
4566 numRequests = nai.numRequestNetworkRequests();
4567 break;
4568 case LINGER:
4569 numRequests = nai.numForegroundNetworkRequests();
4570 break;
4571 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004572 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004573 return true;
4574 }
4575
Chalard Jean947acd42021-03-08 22:29:27 +09004576 if (numRequests > 0) return false;
4577
Paul Jensende49eb12015-06-25 15:30:08 -04004578 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004579 if (reason == UnneededFor.LINGER
4580 && !nri.isMultilayerRequest()
4581 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004582 // Background requests don't affect lingering.
4583 continue;
4584 }
4585
James Mattis3d229892020-11-16 16:46:28 -08004586 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004587 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004588 }
4589 }
Paul Jensende49eb12015-06-25 15:30:08 -04004590 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004591 }
4592
James Mattis3d229892020-11-16 16:46:28 -08004593 private boolean isNetworkPotentialSatisfier(
4594 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4595 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004596 // request, return immediately. For multilayer requests, check to see if any of the
4597 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004598 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4599 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004600 return false;
4601 }
4602 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004603 // This multilayer listen request is satisfied therefore no further requests need to be
4604 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004605 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004606 return false;
4607 }
James Mattis3d229892020-11-16 16:46:28 -08004608 // As non-multilayer listen requests have already returned, the below would only happen
4609 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004610 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004611 continue;
4612 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004613 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004614 // there is hope for it to become one if it validated, then it is needed.
4615 if (candidate.satisfies(req)) {
4616 // As soon as a network is found that satisfies a request, return. Specifically for
4617 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4618 // is important so as to not evaluate lower priority requests further in
4619 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004620 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4621 ? nri.getSatisfier() : null;
4622 // Note that this catches two important cases:
4623 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4624 // is currently satisfying the request. This is desirable when
4625 // cellular ends up validating but WiFi does not.
4626 // 2. Unvalidated WiFi will not be reaped when validated cellular
4627 // is currently satisfying the request. This is desirable when
4628 // WiFi ends up validating and out scoring cellular.
4629 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004630 }
4631 }
4632
4633 return false;
4634 }
4635
Erik Kline0c04b742016-07-07 16:50:58 +09004636 private NetworkRequestInfo getNriForAppRequest(
4637 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004638 // Looking up the app passed param request in mRequests isn't possible since it may return
4639 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4640 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004641 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4642 // to avoid potential race conditions when validating a package->uid mapping when sending
4643 // the callback on the very low-chance that an application shuts down prior to the callback
4644 // being sent.
4645 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4646 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004647
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004648 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004649 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004650 log(String.format("UID %d attempted to %s for unowned request %s",
4651 callingUid, requestedOperation, nri));
4652 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004653 }
Erik Kline0c04b742016-07-07 16:50:58 +09004654 }
4655
4656 return nri;
4657 }
4658
James Mattisf7027322020-12-13 16:28:14 -08004659 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4660 final String callingMethod) {
4661 if (nri.isMultilayerRequest()) {
4662 throw new IllegalStateException(
4663 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004664 }
4665 }
4666
James Mattisf7027322020-12-13 16:28:14 -08004667 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004668 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004669 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4670 // single NetworkRequest and thus does not apply to multilayer requests.
4671 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4672 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004673 return;
4674 }
James Mattis2516da32021-01-31 17:06:19 -08004675 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004676 return;
4677 }
James Mattisf7027322020-12-13 16:28:14 -08004678 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4679 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004680 }
4681 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004682 callCallbackForRequest(
4683 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004684 }
4685
James Mattisf7027322020-12-13 16:28:14 -08004686 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4687 final int callingUid,
4688 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004689 final NetworkRequestInfo nri =
4690 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4691 if (nri == null) {
4692 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004693 }
James Mattisf7027322020-12-13 16:28:14 -08004694 if (VDBG || (DBG && request.isRequest())) {
4695 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004696 }
4697 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004698 if (callOnUnavailable) {
4699 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4700 }
Erik Kline155a59a2015-11-25 12:49:38 +09004701 }
Erik Kline0c04b742016-07-07 16:50:58 +09004702
James Mattisa076c532020-12-02 14:12:41 -08004703 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004704 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004705 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004706 if (null == mNetworkRequests.remove(req)) {
4707 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4708 continue;
4709 }
James Mattisa076c532020-12-02 14:12:41 -08004710 if (req.isListen()) {
4711 removeListenRequestFromNetworks(req);
4712 }
4713 }
James Mattis8f036802021-06-20 16:26:01 -07004714 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004715 if (mDefaultNetworkRequests.remove(nri)) {
4716 // If this request was one of the defaults, then the UID rules need to be updated
4717 // WARNING : if the app(s) for which this network request is the default are doing
4718 // traffic, this will kill their connected sockets, even if an equivalent request
4719 // is going to be reinstated right away ; unconnected traffic will go on the default
4720 // until the new default is set, which will happen very soon.
4721 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4722 // remove ranges for those requests that won't have a replacement
4723 final NetworkAgentInfo satisfier = nri.getSatisfier();
4724 if (null != satisfier) {
4725 try {
paulhu0e79d952021-06-09 16:11:35 +08004726 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4727 satisfier.network.getNetId(),
4728 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004729 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004730 } catch (RemoteException e) {
4731 loge("Exception setting network preference default network", e);
4732 }
4733 }
4734 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004735 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004736 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004737 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004738
4739 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004740 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004741 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004742 }
4743 }
4744
Chalard Jean0354d8c2021-01-12 10:58:56 +09004745 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4746 // needed for this offer.
4747 for (final NetworkOfferInfo noi : mNetworkOffers) {
4748 for (final NetworkRequest req : nri.mRequests) {
4749 if (req.isRequest() && noi.offer.neededFor(req)) {
4750 noi.offer.onNetworkUnneeded(req);
4751 }
4752 }
4753 }
James Mattisa076c532020-12-02 14:12:41 -08004754 }
4755
James Mattis3ce3d3c2021-02-09 18:18:28 -08004756 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4757 for (final NetworkRequestInfo nri : nris) {
4758 if (mDefaultRequest == nri) {
4759 // Make sure we never remove the default request.
4760 continue;
4761 }
4762 handleRemoveNetworkRequest(nri);
4763 }
4764 }
4765
James Mattisa076c532020-12-02 14:12:41 -08004766 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4767 // listens don't have a singular affected Network. Check all networks to see
4768 // if this listen request applies and remove it.
4769 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4770 nai.removeRequest(req.requestId);
4771 if (req.networkCapabilities.hasSignalStrength()
4772 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4773 updateSignalStrengthThresholds(nai, "RELEASE", req);
4774 }
4775 }
4776 }
4777
4778 /**
4779 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4780 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4781 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4782 */
4783 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4784 boolean wasKept = false;
4785 final NetworkAgentInfo nai = nri.getSatisfier();
4786 if (nai != null) {
4787 final int requestLegacyType = nri.getActiveRequest().legacyType;
4788 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4789 nai.removeRequest(nri.getActiveRequest().requestId);
4790 if (VDBG || DDBG) {
4791 log(" Removing from current network " + nai.toShortString()
4792 + ", leaving " + nai.numNetworkRequests() + " requests.");
4793 }
4794 // If there are still lingered requests on this network, don't tear it down,
4795 // but resume lingering instead.
4796 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004797 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004798 notifyNetworkLosing(nai, now);
4799 }
4800 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4801 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4802 teardownUnneededNetwork(nai);
4803 } else {
4804 wasKept = true;
4805 }
James Mattisa076c532020-12-02 14:12:41 -08004806 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4807 // Went from foreground to background.
4808 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004809 }
4810
Erik Kline0c04b742016-07-07 16:50:58 +09004811 // Maintain the illusion. When this request arrived, we might have pretended
4812 // that a network connected to serve it, even though the network was already
4813 // connected. Now that this request has gone away, we might have to pretend
4814 // that the network disconnected. LegacyTypeTracker will generate that
4815 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004816 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004817 boolean doRemove = true;
4818 if (wasKept) {
4819 // check if any of the remaining requests for this network are for the
4820 // same legacy type - if so, don't remove the nai
4821 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4822 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004823 if (otherRequest.legacyType == requestLegacyType
4824 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004825 if (DBG) log(" still have other legacy request - leaving");
4826 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004827 }
4828 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004829 }
4830
Erik Kline0c04b742016-07-07 16:50:58 +09004831 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004832 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004833 }
4834 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004835 }
4836 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004837
Junyu Lai00d92df2022-07-05 11:01:52 +08004838 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004839 return checkAnyPermissionOf(
4840 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4841 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4842 }
4843
Lorenzo Colittid6459092016-07-04 12:55:44 +09004844 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004845 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004846 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004847 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004848 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004849 }
4850
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004851 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004852 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4853 enforceNetworkStackSettingsOrSetup();
4854 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4855 encodeBool(accept), encodeBool(always), network));
4856 }
4857
4858 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004859 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004860 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004861 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4862 }
4863
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004864 @Override
4865 public void setTestAllowBadWifiUntil(long timeMs) {
4866 enforceSettingsPermission();
4867 if (!Build.isDebuggable()) {
4868 throw new IllegalStateException("Does not support in non-debuggable build");
4869 }
4870
4871 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4872 throw new IllegalArgumentException("It should not exceed "
4873 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4874 }
4875
4876 mHandler.sendMessage(
4877 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4878 }
4879
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004880 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4881 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4882 " accept=" + accept + " always=" + always);
4883
4884 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4885 if (nai == null) {
4886 // Nothing to do.
4887 return;
4888 }
4889
Chalard Jean254bd162022-08-25 13:04:51 +09004890 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004891 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004892 return;
4893 }
4894
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004895 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004896 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004897 }
4898
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004899 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4900 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004901 // If network becomes partial connectivity and user already accepted to use this
4902 // network, we should respect the user's option and don't need to popup the
4903 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004904 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004905 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004906 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004907 }
4908
4909 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004910 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004911 }
4912
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004913 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004914 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004915 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004916 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004917 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004918 }
4919
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004920 }
4921
lucaslin2240ef62019-03-12 13:08:03 +08004922 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4923 boolean always) {
4924 if (DBG) {
4925 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4926 + " always=" + always);
4927 }
4928
4929 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4930 if (nai == null) {
4931 // Nothing to do.
4932 return;
4933 }
4934
Chalard Jean254bd162022-08-25 13:04:51 +09004935 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004936 // The network validated while the dialog box was up. Take no action.
4937 return;
4938 }
4939
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004940 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4941 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004942 }
4943
4944 // TODO: Use the current design or save the user choice into IpMemoryStore.
4945 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004946 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004947 }
4948
4949 if (!accept) {
4950 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004951 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004952 // Tear down the network.
4953 teardownUnneededNetwork(nai);
4954 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004955 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4956 // result in a partial connectivity result which will be processed by
4957 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004958 //
4959 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4960 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004961 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004962 }
4963 }
4964
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004965 private void handleSetAvoidUnvalidated(Network network) {
4966 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09004967 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004968 // Nothing to do. The network either disconnected or revalidated.
4969 return;
4970 }
Chalard Jean254bd162022-08-25 13:04:51 +09004971 if (0L == nai.getAvoidUnvalidated()) {
4972 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09004973 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004974 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004975 }
4976 }
4977
Chalard Jean5fb43c72022-09-08 19:03:14 +09004978 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09004979 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09004980 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004981 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09004982 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004983 }
4984
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004985 @Override
4986 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004987 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004988 mHandler.post(() -> {
4989 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4990 if (nai == null) return;
4991 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004992 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004993 });
4994 }
4995
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004996 /**
4997 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4998 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004999 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005000 * @param appExtras Bundle to use as intent extras for the captive portal application.
5001 * Must be treated as opaque to avoid preventing the captive portal app to
5002 * update its arguments.
5003 */
5004 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005005 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005006 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5007 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005008
5009 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5010 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005011 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5012 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005013 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5014
lucaslin75ff7022020-12-17 04:14:35 +08005015 final long token = Binder.clearCallingIdentity();
5016 try {
5017 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5018 } finally {
5019 Binder.restoreCallingIdentity(token);
5020 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005021 }
5022
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005023 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5024 private final Network mNetwork;
5025
5026 private CaptivePortalImpl(Network network) {
5027 mNetwork = network;
5028 }
5029
5030 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005031 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005032 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5033 enforceSettingsPermission();
5034 }
5035
Chiachang Wang938bfba2020-01-09 13:50:55 +08005036 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005037 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005038 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005039 }
5040
5041 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005042 public void appRequest(final int request) {
5043 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5044 if (nm == null) return;
5045
5046 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005047 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005048 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005049 }
5050 }
5051
5052 @Nullable
5053 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5054 // getNetworkAgentInfoForNetwork is thread-safe
5055 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5056 if (nai == null) return null;
5057
5058 // nai.networkMonitor() is thread-safe
5059 return nai.networkMonitor();
5060 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005061 }
5062
Hugo Benichic9048bc2016-09-14 23:23:08 +00005063 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005064 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005065 }
5066
Chalard Jean020b93a2022-09-01 13:20:14 +09005067 private boolean activelyPreferBadWifi() {
5068 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5069 }
5070
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005071 /**
5072 * Return whether the device should maintain continuous, working connectivity by switching away
5073 * from WiFi networks having no connectivity.
5074 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5075 */
5076 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005077 if (!checkNetworkStackPermission()) {
5078 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5079 }
5080 return avoidBadWifi();
5081 }
5082
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005083 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005084 ensureRunningOnConnectivityServiceThread();
5085 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005086 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005087 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005088 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005089 if (avoidBadWifi) {
5090 // If the device is now avoiding bad wifi, remove notifications that might have
5091 // been put up when the device didn't.
5092 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5093 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005094 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005095 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5096 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5097 for (final NetworkOfferInfo noi : offersToUpdate) {
5098 updateOfferScore(noi.offer);
5099 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005100 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005101 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005102 }
5103
Erik Kline95ecfee2016-10-02 18:02:14 +09005104 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005105 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005106 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005107 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005108 if (!configRestrict) {
5109 pw.println("Bad Wi-Fi avoidance: unrestricted");
5110 return;
5111 }
5112
5113 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5114 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005115 pw.println("Config restrict: " + configRestrict);
5116 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005117
Chalard Jeane0fdea32022-09-14 21:44:22 +09005118 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005119 String description;
5120 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005121 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005122 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005123 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005124 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005125 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005126 description = "avoid";
5127 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005128 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005129 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005130 pw.println("Avoid bad wifi setting: " + description);
5131 final Boolean configValue = mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi();
5132 if (null == configValue) {
5133 description = "unset";
5134 } else if (configValue) {
5135 description = "force true";
5136 } else {
5137 description = "force false";
5138 }
5139 pw.println("Actively prefer bad wifi conf: " + description);
5140 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005141 pw.println("Network overrides:");
5142 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005143 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005144 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005145 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005146 }
5147 }
5148 pw.decreaseIndent();
5149 pw.decreaseIndent();
5150 }
5151
paulhu7746e4e2020-06-09 19:07:03 +08005152 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5153 // unify the method.
5154 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5155 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5156 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5157 return settingsComponent != null
5158 ? settingsComponent.getPackageName() : "com.android.settings";
5159 }
5160
lucaslinb1e8e382019-01-24 15:55:30 +08005161 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005162 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005163 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005164 switch (type) {
5165 case NO_INTERNET:
5166 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005167 // High priority because it is only displayed for explicitly selected networks.
5168 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005169 break;
lucasline117e2e2019-10-22 18:27:33 +08005170 case PRIVATE_DNS_BROKEN:
5171 action = Settings.ACTION_WIRELESS_SETTINGS;
5172 // High priority because we should let user know why there is no internet.
5173 highPriority = true;
5174 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005175 case LOST_INTERNET:
5176 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005177 // High priority because it could help the user avoid unexpected data usage.
5178 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005179 break;
lucaslin2240ef62019-03-12 13:08:03 +08005180 case PARTIAL_CONNECTIVITY:
5181 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005182 // Don't bother the user with a high-priority notification if the network was not
5183 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005184 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005185 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005186 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005187 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005188 return;
5189 }
5190
5191 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005192 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005193 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005194 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005195 // Some OEMs have their own Settings package. Thus, need to get the current using
5196 // Settings package name instead of just use default name "com.android.settings".
5197 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5198 intent.setClassName(settingsPkgName,
5199 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005200 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005201
paulhu2af50222020-10-11 22:52:27 +08005202 PendingIntent pendingIntent = PendingIntent.getActivity(
5203 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005204 0 /* requestCode */,
5205 intent,
paulhu2af50222020-10-11 22:52:27 +08005206 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005207
Serik Beketayevec8ad212020-12-07 22:43:07 -08005208 mNotifier.showNotification(
5209 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005210 }
5211
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005212 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5213 // Don't prompt if the network is validated, and don't prompt on captive portals
5214 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005215 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005216 return false;
5217 }
5218
5219 // If a network has partial connectivity, always prompt unless the user has already accepted
5220 // partial connectivity and selected don't ask again. This ensures that if the device
5221 // automatically connects to a network that has partial Internet access, the user will
5222 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005223 // because we have prompted them.
5224 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005225 return true;
5226 }
5227
5228 // If a network has no Internet access, only prompt if the network was explicitly selected
5229 // and if the user has not already told us to use the network regardless of whether it
5230 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005231 if (nai.networkAgentConfig.explicitlySelected
5232 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005233 return true;
5234 }
5235
5236 return false;
5237 }
5238
Chalard Jean5fb43c72022-09-08 19:03:14 +09005239 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5240 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005241
Chalard Jean5fb43c72022-09-08 19:03:14 +09005242 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5243 if (null == nai) return;
5244
5245 if (nai.setEvaluated()) {
5246 // If setEvaluated() returned true, the network never had any form of connectivity.
5247 // This may have an impact on request matching if bad WiFi avoidance is off and the
5248 // network was found not to have Internet access.
5249 nai.updateScoreForNetworkAgentUpdate();
5250 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005251
5252 // Also, if this is WiFi and it should be preferred actively, now is the time to
5253 // prompt the user that they walked past and connected to a bad WiFi.
5254 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5255 && !avoidBadWifi()
5256 && activelyPreferBadWifi()) {
5257 // The notification will be removed if the network validates or disconnects.
5258 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5259 return;
5260 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005261 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005262
Chalard Jean5fb43c72022-09-08 19:03:14 +09005263 if (!shouldPromptUnvalidated(nai)) return;
5264
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005265 // Stop automatically reconnecting to this network in the future. Automatically connecting
5266 // to a network that provides no or limited connectivity is not useful, because the user
5267 // cannot use that network except through the notification shown by this method, and the
5268 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005269 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005270
Chalard Jean254bd162022-08-25 13:04:51 +09005271 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005272 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005273 } else {
5274 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5275 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005276 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005277
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005278 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5279 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005280 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005281
lucaslin2240ef62019-03-12 13:08:03 +08005282 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5283 return;
5284 }
5285
5286 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005287 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005288 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005289 }
5290
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005291 @Override
5292 public int getMultipathPreference(Network network) {
5293 enforceAccessPermission();
5294
5295 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005296 if (nai != null && nai.networkCapabilities
5297 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005298 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5299 }
5300
Aaron Huang9a57acf2020-12-08 10:03:29 +08005301 final NetworkPolicyManager netPolicyManager =
5302 mContext.getSystemService(NetworkPolicyManager.class);
5303
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005304 final long token = Binder.clearCallingIdentity();
5305 final int networkPreference;
5306 try {
5307 networkPreference = netPolicyManager.getMultipathPreference(network);
5308 } finally {
5309 Binder.restoreCallingIdentity(token);
5310 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005311 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005312 return networkPreference;
5313 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005314 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5315 }
5316
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005317 @Override
5318 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005319 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005320 }
5321
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005322 private class InternalHandler extends Handler {
5323 public InternalHandler(Looper looper) {
5324 super(looper);
5325 }
5326
5327 @Override
5328 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005329 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005330 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005331 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005332 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005333 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005334 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005335 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005336 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005337 break;
5338 }
Jason Monka69f1b02013-10-10 14:02:51 -04005339 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005340 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5341 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005342 break;
5343 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005344 case EVENT_REGISTER_NETWORK_PROVIDER: {
5345 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005346 break;
5347 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005348 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5349 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005350 break;
5351 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005352 case EVENT_REGISTER_NETWORK_OFFER: {
5353 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5354 break;
5355 }
5356 case EVENT_UNREGISTER_NETWORK_OFFER: {
5357 final NetworkOfferInfo offer =
5358 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5359 if (null != offer) {
5360 handleUnregisterNetworkOffer(offer);
5361 }
5362 break;
5363 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005364 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005365 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5366 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5367 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005368 break;
5369 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005370 case EVENT_REGISTER_NETWORK_REQUEST:
5371 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005372 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005373 break;
5374 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005375 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5376 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005377 handleRegisterNetworkRequestWithIntent(msg);
5378 break;
5379 }
Erik Kline155a59a2015-11-25 12:49:38 +09005380 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5381 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5382 handleTimedOutNetworkRequest(nri);
5383 break;
5384 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005385 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5386 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5387 break;
5388 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005389 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005390 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5391 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005392 break;
5393 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005394 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005395 Network network = (Network) msg.obj;
5396 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005397 break;
5398 }
lucaslin2240ef62019-03-12 13:08:03 +08005399 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5400 Network network = (Network) msg.obj;
5401 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5402 toBool(msg.arg2));
5403 break;
5404 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005405 case EVENT_SET_AVOID_UNVALIDATED: {
5406 handleSetAvoidUnvalidated((Network) msg.obj);
5407 break;
5408 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005409 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5410 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005411 break;
5412 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005413 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5414 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005415 break;
5416 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005417 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005418 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005419 mKeepaliveTracker.handleStartKeepalive(msg);
5420 break;
5421 }
5422 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005423 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005424 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5425 int slot = msg.arg1;
5426 int reason = msg.arg2;
5427 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5428 break;
5429 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005430 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5431 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5432 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005433 break;
5434 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005435 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5436 handlePrivateDnsSettingsChanged();
5437 break;
dalyk1720e542018-03-05 12:42:22 -05005438 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5439 handlePrivateDnsValidationUpdate(
5440 (PrivateDnsValidationUpdate) msg.obj);
5441 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005442 case EVENT_UID_BLOCKED_REASON_CHANGED:
5443 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005444 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005445 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5446 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5447 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005448 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005449 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5450 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005451 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005452 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005453 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005454 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005455 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5456 IOnCompleteListener> arg =
5457 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5458 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005459 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005460 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005461 }
lucaslin1193a5d2021-01-21 02:04:15 +08005462 case EVENT_REPORT_NETWORK_ACTIVITY:
5463 mNetworkActivityTracker.handleReportNetworkActivity();
5464 break;
paulhu51f77dc2021-06-07 02:34:20 +00005465 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5466 handleMobileDataPreferredUidsChanged();
5467 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005468 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5469 final long timeMs = ((Long) msg.obj).longValue();
5470 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5471 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005472 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5473 handleIngressRateLimitChanged();
5474 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005475 }
5476 }
5477 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005478
Lorenzo Colittid6459092016-07-04 12:55:44 +09005479 @Override
markchien5776f962019-12-16 20:15:20 +08005480 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005481 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005482 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005483 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5484 Context.TETHERING_SERVICE);
5485 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005486 }
5487
Lorenzo Colittid6459092016-07-04 12:55:44 +09005488 @Override
markchien5776f962019-12-16 20:15:20 +08005489 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005490 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005491 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005492 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5493 Context.TETHERING_SERVICE);
5494 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005495 }
5496
Lorenzo Colittid6459092016-07-04 12:55:44 +09005497 @Override
markchien5776f962019-12-16 20:15:20 +08005498 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005499 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005500 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005501 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5502 Context.TETHERING_SERVICE);
5503 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005504 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005505
markchien5776f962019-12-16 20:15:20 +08005506
Lorenzo Colittid6459092016-07-04 12:55:44 +09005507 @Override
markchien5776f962019-12-16 20:15:20 +08005508 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005509 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005510 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005511 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5512 Context.TETHERING_SERVICE);
5513
5514 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005515 }
5516
Lorenzo Colittid6459092016-07-04 12:55:44 +09005517 @Override
markchien5776f962019-12-16 20:15:20 +08005518 @Deprecated
5519 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005520 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005521 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5522 Context.TETHERING_SERVICE);
5523
5524 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005525 }
5526
Udam Saini8f7d6a72017-06-07 12:06:28 -07005527 @Override
markchien5776f962019-12-16 20:15:20 +08005528 @Deprecated
5529 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005530 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005531 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5532 Context.TETHERING_SERVICE);
5533 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005534 }
5535
Robert Greenwalte0b00512014-07-02 09:59:16 -07005536 // Called when we lose the default network and have no replacement yet.
5537 // This will automatically be cleared after X seconds or a new default network
5538 // becomes CONNECTED, whichever happens first. The timer is started by the
5539 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005540 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005541 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005542 if (mNetTransitionWakeLock.isHeld()) {
5543 return;
5544 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005545 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005546 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5547 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005548 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005549 mWakelockLogs.log("ACQUIRE for " + forWhom);
5550 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005551 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005552 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005553 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005554 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005555
Hugo Benichi471b62a2017-03-30 23:18:10 +09005556 // Called when we gain a new default network to release the network transition wakelock in a
5557 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5558 // message is cancelled.
5559 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005560 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005561 if (!mNetTransitionWakeLock.isHeld()) {
5562 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005563 }
5564 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005565 // Cancel self timeout on wakelock hold.
5566 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5567 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5568 mHandler.sendMessageDelayed(msg, 1000);
5569 }
5570
5571 // Called when either message of ensureNetworkTransitionWakelock or
5572 // scheduleReleaseNetworkTransitionWakelock is processed.
5573 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5574 String event = eventName(eventId);
5575 synchronized (this) {
5576 if (!mNetTransitionWakeLock.isHeld()) {
5577 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005578 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005579 return;
5580 }
5581 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005582 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5583 mTotalWakelockDurationMs += lockDuration;
5584 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5585 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005586 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005587 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005588 }
5589
Robert Greenwalt986c7412010-09-08 15:24:47 -07005590 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005591 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005592 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005593 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005594 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005595 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005596 }
5597
Lorenzo Colittid6459092016-07-04 12:55:44 +09005598 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005599 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005600 enforceAccessPermission();
5601 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005602 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005603 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005604
5605 final NetworkAgentInfo nai;
5606 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005607 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005608 } else {
5609 nai = getNetworkAgentInfoForNetwork(network);
5610 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005611
5612 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005613 mHandler.obtainMessage(
5614 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005615 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005616
Hugo Benichid6b510a2017-04-06 17:22:18 +09005617 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005618 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005619 if (nai == null
5620 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005621 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005622 return;
5623 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005624 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005625 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005626 mConnectivityDiagnosticsHandler.sendMessage(
5627 mConnectivityDiagnosticsHandler.obtainMessage(
5628 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5629 new ReportedNetworkConnectivityInfo(
5630 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005631 return;
5632 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005633 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005634 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005635 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005636 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005637 // Validating a network that has not yet connected could result in a call to
5638 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005639 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005640 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005641 }
paulhu7aeba372020-12-30 00:42:19 +08005642 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5643 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005644 return;
5645 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005646
5647 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5648 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5649 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5650 // completed.
5651 mConnectivityDiagnosticsHandler.sendMessage(
5652 mConnectivityDiagnosticsHandler.obtainMessage(
5653 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5654 new ReportedNetworkConnectivityInfo(
5655 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005656 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005657 }
5658
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005659 // TODO: call into netd.
5660 private boolean queryUserAccess(int uid, Network network) {
5661 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5662 if (nai == null) return false;
5663
5664 // Any UID can use its default network.
5665 if (nai == getDefaultNetworkForUid(uid)) return true;
5666
5667 // Privileged apps can use any network.
5668 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5669 return true;
5670 }
5671
5672 // An unprivileged UID can use a VPN iff the VPN applies to it.
5673 if (nai.isVPN()) {
5674 return nai.networkCapabilities.appliesToUid(uid);
5675 }
5676
5677 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5678 // sockets, i.e., if it is the owner.
5679 final NetworkAgentInfo vpn = getVpnForUid(uid);
5680 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5681 && uid != vpn.networkCapabilities.getOwnerUid()) {
5682 return false;
5683 }
5684
5685 // The UID's permission must be at least sufficient for the network. Since the restricted
5686 // permission was already checked above, that just leaves background networks.
5687 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5688 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5689 }
5690
5691 // Unrestricted network. Anyone gets to use it.
5692 return true;
5693 }
5694
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005695 /**
5696 * Returns information about the proxy a certain network is using. If given a null network, it
5697 * it will return the proxy for the bound network for the caller app or the default proxy if
5698 * none.
5699 *
5700 * @param network the network we want to get the proxy information for.
5701 * @return Proxy information if a network has a proxy configured, or otherwise null.
5702 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005703 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005704 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005705 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005706 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005707 if (network == null) {
5708 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005709 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005710 true);
5711 if (activeNetwork == null) {
5712 return null;
5713 }
5714 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005715 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005716 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5717 // caller may not have.
5718 return getLinkPropertiesProxyInfo(network);
5719 }
5720 // No proxy info available if the calling UID does not have network access.
5721 return null;
5722 }
5723
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005724
5725 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005726 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5727 if (nai == null) return null;
5728 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005729 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5730 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005731 }
5732 }
5733
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005734 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005735 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005736 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005737 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005738 }
5739
Chalard Jean777e2e52018-06-07 18:02:37 +09005740 @Override
5741 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005742 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005743 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005744 }
5745
Jason Monk4d5e20f2014-04-25 15:00:09 -04005746 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005747 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005748 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005749 proxy = null;
5750 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005751 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005752 }
5753
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005754 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5755 // when any network changes proxy.
5756 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5757 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005758 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005759 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5760 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5761
Chalard Jean7d97afc2018-06-07 17:41:29 +09005762 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005763 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005764 }
5765 }
5766
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005767 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005768 final private HashMap<Uri, Integer> mUriEventMap;
5769 final private Context mContext;
5770 final private Handler mHandler;
5771
5772 SettingsObserver(Context context, Handler handler) {
5773 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005774 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005775 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005776 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005777 }
5778
Erik Kline05f2b402015-04-30 12:58:40 +09005779 void observe(Uri uri, int what) {
5780 mUriEventMap.put(uri, what);
5781 final ContentResolver resolver = mContext.getContentResolver();
5782 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005783 }
5784
5785 @Override
5786 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005787 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005788 }
5789
5790 @Override
5791 public void onChange(boolean selfChange, Uri uri) {
5792 final Integer what = mUriEventMap.get(uri);
5793 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005794 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005795 } else {
5796 loge("No matching event to send for URI=" + uri);
5797 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005798 }
5799 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005800
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005801 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005802 Log.d(TAG, s);
5803 }
5804
5805 private static void logw(String s) {
5806 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005807 }
5808
Daniel Brightf9e945b2020-06-15 16:10:01 -07005809 private static void logwtf(String s) {
5810 Log.wtf(TAG, s);
5811 }
5812
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005813 private static void logwtf(String s, Throwable t) {
5814 Log.wtf(TAG, s, t);
5815 }
5816
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005817 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005818 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005819 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005820
Hugo Benichi39621362017-02-11 17:04:43 +09005821 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005822 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005823 }
5824
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005825 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005826 * Return the information of all ongoing VPNs.
5827 *
5828 * <p>This method is used to update NetworkStatsService.
5829 *
5830 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005831 */
junyulai2050bed2021-01-23 09:46:34 +08005832 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005833 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005834 if (mLockdownEnabled) {
5835 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005836 }
junyulai2050bed2021-01-23 09:46:34 +08005837 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005838 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005839 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005840 if (info != null) {
5841 infoList.add(info);
5842 }
5843 }
junyulai2050bed2021-01-23 09:46:34 +08005844 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005845 }
5846
5847 /**
5848 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005849 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005850 */
junyulai2050bed2021-01-23 09:46:34 +08005851 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005852 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005853 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5854 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005855 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5856 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5857 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005858 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5859 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005860 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005861 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005862 }
5863 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005864
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005865 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005866
5867 List<String> interfaces = new ArrayList<>();
5868 for (Network network : underlyingNetworks) {
5869 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5870 if (underlyingNai == null) continue;
5871 LinkProperties lp = underlyingNai.linkProperties;
5872 for (String iface : lp.getAllInterfaceNames()) {
5873 if (!TextUtils.isEmpty(iface)) {
5874 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005875 }
5876 }
Benedict Wong34857f82019-06-12 17:46:15 +00005877 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005878
5879 if (interfaces.isEmpty()) return null;
5880
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005881 // Must be non-null or NetworkStatsService will crash.
5882 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5883 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005884 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005885 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005886
junyulai2050bed2021-01-23 09:46:34 +08005887 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5888 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005889 }
5890
James Mattisd31bdfa2020-12-23 16:37:26 -08005891 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005892 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5893 Network[] underlyingNetworks) {
5894 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005895 if (underlyingNetworks == null && defaultNetwork != null) {
5896 // null underlying networks means to track the default.
5897 underlyingNetworks = new Network[] { defaultNetwork };
5898 }
5899 return underlyingNetworks;
5900 }
5901
5902 // Returns true iff |network| is an underlying network of |nai|.
5903 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5904 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5905 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005906 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005907 final Network[] underlying = underlyingNetworksOrDefault(
5908 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005909 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005910 }
5911
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005912 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005913 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005914 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005915 * When underlying networks change, such networks may have to update capabilities to reflect
5916 * things like the metered bit, their transports, and so on. The capabilities are calculated
5917 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005918 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005919 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005920 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005921 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005922 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005923 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005924 }
5925 }
5926 }
5927
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005928 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5929 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5930 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5931 // a VPN is not up.
5932 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5933 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5934 for (UidRange range : blockedUidRanges) {
5935 if (range.contains(uid)) return true;
5936 }
5937 return false;
5938 }
5939
5940 @Override
5941 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005942 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005943 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5944 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5945 }
5946
5947 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5948 if (DBG) {
5949 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5950 + Arrays.toString(ranges));
5951 }
5952 // Cannot use a Set since the list of UID ranges might contain duplicates.
5953 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5954 for (int i = 0; i < ranges.length; i++) {
5955 if (requireVpn) {
5956 newVpnBlockedUidRanges.add(ranges[i]);
5957 } else {
5958 newVpnBlockedUidRanges.remove(ranges[i]);
5959 }
5960 }
5961
5962 try {
5963 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5964 } catch (RemoteException | ServiceSpecificException e) {
5965 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5966 + Arrays.toString(ranges) + "): netd command failed: " + e);
5967 }
5968
Motomu Utsumib08654c2022-05-11 05:56:26 +00005969 if (SdkLevel.isAtLeastT()) {
5970 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5971 }
5972
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005973 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5974 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005975 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5976 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005977 }
5978
5979 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5980 }
5981
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005982 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005983 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005984 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005985 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005986 }
5987
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005988 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5989 return mLockdownEnabled
5990 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5991 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005992 }
5993
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005994 private NetworkAgentInfo getLegacyLockdownNai() {
5995 if (!mLockdownEnabled) {
5996 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005997 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005998 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005999 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6000 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006001
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006002 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006003 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6004 // a local variable. There is no need to make a copy because its contents cannot change.
6005 final Network[] underlying = nai.declaredUnderlyingNetworks;
6006 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006007 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006008 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006009
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006010 // The legacy lockdown VPN always uses the default network.
6011 // If the VPN's underlying network is no longer the current default network, it means that
6012 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006013 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6014 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006015 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006016 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006017 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006018 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006019
6020 return nai;
6021 };
6022
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006023 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6024 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6025 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006026 private DetailedState getLegacyLockdownState(DetailedState origState) {
6027 if (origState != DetailedState.CONNECTED) {
6028 return origState;
6029 }
6030 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6031 ? DetailedState.CONNECTING
6032 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006033 }
6034
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006035 private void filterForLegacyLockdown(NetworkInfo ni) {
6036 if (!mLockdownEnabled || !ni.isConnected()) return;
6037 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6038 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6039 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6040 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6041 // network, this time with a state of CONNECTED.
6042 //
6043 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6044 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6045 // is not too far off the truth, since an always-on VPN, when not connected, is always
6046 // trying to reconnect.
6047 if (getLegacyLockdownNai() == null) {
6048 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6049 }
6050 }
6051
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006052 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006053 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006054 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006055 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006056 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6057 return;
6058 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006059 final long ident = Binder.clearCallingIdentity();
6060 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006061 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006062 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006063 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006064 } finally {
6065 Binder.restoreCallingIdentity(ident);
6066 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006067 }
Wink Savillecb117d32013-08-29 14:57:08 -07006068
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006069 @Override
6070 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006071 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006072 final long ident = Binder.clearCallingIdentity();
6073 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006074 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006075 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006076 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6077 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006078 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006079 } finally {
6080 Binder.restoreCallingIdentity(ident);
6081 }
6082 }
6083
James Mattis02220e22021-03-13 19:27:21 -08006084 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006085 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006086 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6087 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6088 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006089 }
6090
James Mattis02220e22021-03-13 19:27:21 -08006091 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006092 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006093 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006094 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006095 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006096 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006097 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6098 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6099 }
junyulaid91e7052020-08-28 13:44:33 +08006100 }
6101
James Mattis02220e22021-03-13 19:27:21 -08006102 private void onPackageChanged(@NonNull final String packageName) {
6103 // This is necessary in case a package is added or removed, but also when it's replaced to
6104 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6105 // as one in the preferences, then it should follow the same routing as that other package,
6106 // which means updating the rules is never to be needed in this case (whether it joins or
6107 // leaves a UID with a preference).
6108 if (isMappedInOemNetworkPreference(packageName)) {
6109 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6110 }
6111 }
6112
6113 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006114 @Override
6115 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006116 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006117 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006118 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006119
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006120 // User should be filled for below intents, check the existence.
6121 if (user == null) {
6122 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6123 return;
6124 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006125
Lorenzo Colitticd675292021-02-04 17:32:07 +09006126 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006127 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006128 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006129 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006130 } else {
junyulaid91e7052020-08-28 13:44:33 +08006131 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006132 }
6133 }
6134 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006135
James Mattis02220e22021-03-13 19:27:21 -08006136 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6137 @Override
6138 public void onReceive(Context context, Intent intent) {
6139 ensureRunningOnConnectivityServiceThread();
6140 switch (intent.getAction()) {
6141 case Intent.ACTION_PACKAGE_ADDED:
6142 case Intent.ACTION_PACKAGE_REMOVED:
6143 case Intent.ACTION_PACKAGE_REPLACED:
6144 onPackageChanged(intent.getData().getSchemeSpecificPart());
6145 break;
6146 default:
6147 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6148 }
6149 }
6150 };
6151
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006152 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006153 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006154
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006155 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006156 public final String name;
6157 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006158 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006159 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006160
lifraf3a3492021-03-10 13:58:14 +08006161 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6162 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006163 this.name = name;
6164 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006165 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006166 mDeathRecipient = deathRecipient;
6167
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006168 if (mDeathRecipient == null) {
6169 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006170 }
6171 }
6172
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006173 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006174 try {
6175 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6176 } catch (RemoteException e) {
6177 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006178 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006179 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006180 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006181
James Mattis4fce5d12020-11-12 15:53:42 -08006182 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6183 for (int i = 0; i < requests.size(); i++) {
6184 ensureNetworkRequestHasType(requests.get(i));
6185 }
6186 }
6187
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006188 private void ensureNetworkRequestHasType(NetworkRequest request) {
6189 if (request.type == NetworkRequest.Type.NONE) {
6190 throw new IllegalArgumentException(
6191 "All NetworkRequests in ConnectivityService must have a type");
6192 }
6193 }
6194
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006195 /**
6196 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006197 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006198 */
James Mattis258ea3c2020-11-15 15:04:40 -08006199 @VisibleForTesting
6200 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006201 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6202 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006203 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006204
James Mattisa076c532020-12-02 14:12:41 -08006205 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6206 void setSatisfier(
6207 @Nullable final NetworkAgentInfo satisfier,
6208 @Nullable final NetworkRequest activeRequest) {
6209 mSatisfier = satisfier;
6210 mActiveRequest = activeRequest;
6211 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006212
James Mattisd31bdfa2020-12-23 16:37:26 -08006213 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006214 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006215 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006216 private NetworkAgentInfo mSatisfier;
6217 NetworkAgentInfo getSatisfier() {
6218 return mSatisfier;
6219 }
6220
6221 // The request in mRequests assigned to a network agent. This is null if none of the
6222 // requests in mRequests can be satisfied. This member has the constraint of only being
6223 // accessible on the handler thread.
6224 @Nullable
6225 private NetworkRequest mActiveRequest;
6226 NetworkRequest getActiveRequest() {
6227 return mActiveRequest;
6228 }
6229
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006230 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006231 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006232 @Nullable
6233 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006234
6235 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006236 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006237 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006238 final int mPid;
6239 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006240 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006241 @Nullable
6242 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006243
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006244 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006245 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006246
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006247 // Effective UID of this request. This is different from mUid when a privileged process
6248 // files a request on behalf of another UID. This UID is used to determine blocked status,
6249 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6250 // maximum limit of registered callbacks per UID.
6251 final int mAsUid;
6252
paulhu48291862021-07-14 14:53:57 +08006253 // Preference order of this request.
6254 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006255
James Mattis3ce3d3c2021-02-09 18:18:28 -08006256 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6257 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6258 // maintained for keying off of. This is only a concern when the original nri
6259 // mNetworkRequests changes which happens currently for apps that register callbacks to
6260 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6261 // that match the per-app default nri that currently tracks the calling app's uid so that
6262 // callbacks are fired at the appropriate time. When the callbacks fire,
6263 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6264 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6265 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6266 @NonNull
6267 private final NetworkRequest mNetworkRequestForCallback;
6268 NetworkRequest getNetworkRequestForCallback() {
6269 return mNetworkRequestForCallback;
6270 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006271
James Mattisd31bdfa2020-12-23 16:37:26 -08006272 /**
6273 * Get the list of UIDs this nri applies to.
6274 */
6275 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006276 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006277 // networkCapabilities.getUids() returns a defensive copy.
6278 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006279 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6280 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006281 }
6282
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006283 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6284 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006285 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006286 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006287 }
6288
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006289 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006290 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006291 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006292 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006293 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006294 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006295 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006296 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006297 mBinder = null;
6298 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006299 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006300 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006301 mPerUidCounter = getRequestCounter(this);
6302 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006303 /**
6304 * Location sensitive data not included in pending intent. Only included in
6305 * {@link NetworkCallback}.
6306 */
6307 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006308 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006309 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006310 }
6311
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006312 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006313 @Nullable final IBinder binder,
6314 @NetworkCallback.Flag int callbackFlags,
6315 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006316 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6317 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006318 }
6319
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006320 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006321 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006322 @Nullable final IBinder binder,
6323 @NetworkCallback.Flag int callbackFlags,
6324 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006325 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006326 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006327 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006328 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006329 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006330 mBinder = binder;
6331 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006332 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006333 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006334 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006335 mPerUidCounter = getRequestCounter(this);
6336 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006337 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006338 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006339 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006340 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006341 }
6342
James Mattis3ce3d3c2021-02-09 18:18:28 -08006343 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6344 @NonNull final List<NetworkRequest> r) {
6345 super();
6346 ensureAllNetworkRequestsHaveType(r);
6347 mRequests = initializeRequests(r);
6348 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006349 final NetworkAgentInfo satisfier = nri.getSatisfier();
6350 if (null != satisfier) {
6351 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6352 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006353 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006354 // As this code creates a new NRI with a new set of requests, figure out which of
6355 // the list of requests should be the active request. It is always the first
6356 // request of the list that can be satisfied by the satisfier since the order of
6357 // requests is a priority order.
6358 // Note even in the presence of a satisfier there may not be an active request,
6359 // when the satisfier is the no-service network.
6360 NetworkRequest activeRequest = null;
6361 for (final NetworkRequest candidate : r) {
6362 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6363 activeRequest = candidate;
6364 break;
6365 }
6366 }
6367 setSatisfier(satisfier, activeRequest);
6368 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006369 mMessenger = nri.mMessenger;
6370 mBinder = nri.mBinder;
6371 mPid = nri.mPid;
6372 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006373 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006374 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006375 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006376 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006377 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006378 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006379 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006380 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006381 }
6382
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006383 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006384 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006385 }
6386
paulhue9913722021-05-26 15:19:20 +08006387 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006388 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006389 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006390 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006391 }
6392
James Mattis2516da32021-01-31 17:06:19 -08006393 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6394 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6395 // false.
6396 boolean isBeingSatisfied() {
6397 return (null != mSatisfier && null != mActiveRequest);
6398 }
6399
James Mattis3d229892020-11-16 16:46:28 -08006400 boolean isMultilayerRequest() {
6401 return mRequests.size() > 1;
6402 }
6403
James Mattis45d81842021-01-10 14:24:24 -08006404 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6405 // Creating a defensive copy to prevent the sender from modifying the list being
6406 // reflected in the return value of this method.
6407 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006408 return Collections.unmodifiableList(tempRequests);
6409 }
6410
James Mattisb1392002021-03-31 13:57:52 -07006411 void linkDeathRecipient() {
6412 if (null != mBinder) {
6413 try {
6414 mBinder.linkToDeath(this, 0);
6415 } catch (RemoteException e) {
6416 binderDied();
6417 }
6418 }
6419 }
6420
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006421 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006422 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006423 try {
6424 mBinder.unlinkToDeath(this, 0);
6425 } catch (NoSuchElementException e) {
6426 // Temporary workaround for b/194394697 pending analysis of additional logs
6427 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6428 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006429 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006430 }
6431
paulhu48291862021-07-14 14:53:57 +08006432 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6433 // Compare two preference orders.
6434 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006435 }
6436
paulhu48291862021-07-14 14:53:57 +08006437 int getPreferenceOrderForNetd() {
6438 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6439 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6440 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006441 }
paulhu48291862021-07-14 14:53:57 +08006442 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006443 }
6444
James Mattis4fce5d12020-11-12 15:53:42 -08006445 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006446 public void binderDied() {
6447 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006448 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006449 // As an immutable collection, mRequests cannot change by the time the
6450 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6451 // is acceptable. Use handleReleaseNetworkRequest and not directly
6452 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6453 // the app already unregistered the request.
6454 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6455 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006456 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006457
James Mattis4fce5d12020-11-12 15:53:42 -08006458 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006459 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006460 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6461 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006462 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006463 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006464 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006465 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006466 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006467 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006468 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006469 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006470 }
6471
Junyu Lai00d92df2022-07-05 11:01:52 +08006472 // Keep backward compatibility since the ServiceSpecificException is used by
6473 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6474 public static class RequestInfoPerUidCounter extends PerUidCounter {
6475 RequestInfoPerUidCounter(int maxCountPerUid) {
6476 super(maxCountPerUid);
6477 }
6478
6479 @Override
6480 public synchronized void incrementCountOrThrow(int uid) {
6481 try {
6482 super.incrementCountOrThrow(uid);
6483 } catch (IllegalStateException e) {
6484 throw new ServiceSpecificException(
6485 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6486 "Uid " + uid + " exceeded its allotted requests limit");
6487 }
6488 }
6489
6490 @Override
6491 public synchronized void decrementCountOrThrow(int uid) {
6492 throw new UnsupportedOperationException("Use decrementCount instead.");
6493 }
6494
6495 public synchronized void decrementCount(int uid) {
6496 try {
6497 super.decrementCountOrThrow(uid);
6498 } catch (IllegalStateException e) {
6499 logwtf("Exception when decrement per uid request count: ", e);
6500 }
6501 }
6502 }
6503
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006504 // This checks that the passed capabilities either do not request a
6505 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006506 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006507 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006508 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006509 throw new SecurityException("Insufficient permissions to request a specific SSID");
6510 }
paulhu1a407652019-03-22 16:35:06 +08006511
6512 if (nc.hasSignalStrength()
6513 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6514 throw new SecurityException(
6515 "Insufficient permissions to request a specific signal strength");
6516 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006517 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006518
junyulai2217bec2021-04-14 23:33:31 +08006519 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006520 enforceNetworkFactoryPermission();
6521 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006522 }
6523
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006524 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006525 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006526 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006527 // mNetworkRequests may contain the same value multiple times in case of
6528 // multilayer requests. It won't matter in this case because the thresholds
6529 // will then be the same and be deduplicated as they enter the `thresholds` set.
6530 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006531 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6532 for (final NetworkRequest req : nri.mRequests) {
6533 if (req.networkCapabilities.hasSignalStrength()
6534 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6535 thresholds.add(req.networkCapabilities.getSignalStrength());
6536 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006537 }
6538 }
6539 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006540 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006541 }
6542
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006543 private void updateSignalStrengthThresholds(
6544 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006545 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006546
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006547 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006548 String detail;
6549 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6550 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6551 } else {
6552 detail = reason;
6553 }
6554 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006555 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006556 }
6557
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006558 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006559 }
6560
Chalard Jeandd421992021-12-16 23:16:02 +09006561 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006562 if (nc == null) {
6563 return;
6564 }
6565 NetworkSpecifier ns = nc.getNetworkSpecifier();
6566 if (ns == null) {
6567 return;
6568 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006569 if (ns instanceof MatchAllNetworkSpecifier) {
6570 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6571 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006572 }
6573
Chalard Jeandd421992021-12-16 23:16:02 +09006574 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006575 ensureValidNetworkSpecifier(nc);
6576 if (nc.isPrivateDnsBroken()) {
6577 throw new IllegalArgumentException("Can't request broken private DNS");
6578 }
Chalard Jeande665262022-02-25 16:12:12 +09006579 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006580 throw new IllegalArgumentException("Can't request access UIDs");
6581 }
lucasline117e2e2019-10-22 18:27:33 +08006582 }
6583
Chalard Jeandd421992021-12-16 23:16:02 +09006584 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6585 ensureListenableCapabilities(nc);
6586 final String badCapability = nc.describeFirstNonRequestableCapability();
6587 if (badCapability != null) {
6588 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6589 }
6590 }
6591
Chiachang Wang3bc52762021-11-25 14:17:57 +08006592 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6593 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006594 private boolean isTargetSdkAtleast(int version, int callingUid,
6595 @NonNull String callingPackageName) {
6596 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006597 final PackageManager pm =
6598 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006599 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006600 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006601 if (callingVersion < version) return false;
6602 } catch (PackageManager.NameNotFoundException e) { }
6603 return true;
6604 }
6605
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006606 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006607 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006608 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006609 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006610 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006611 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006612 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6613 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006614 throw new SecurityException("Insufficient permissions to specify legacy type");
6615 }
markchienfac84a22020-03-18 21:16:15 +08006616 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006617 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006618 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006619 // Privileged callers can track the default network of another UID by passing in a UID.
6620 if (asUid != Process.INVALID_UID) {
6621 enforceSettingsPermission();
6622 } else {
6623 asUid = callingUid;
6624 }
junyulaiad010792021-01-11 16:53:38 +08006625 final NetworkRequest.Type reqType;
6626 try {
6627 reqType = NetworkRequest.Type.values()[reqTypeInt];
6628 } catch (ArrayIndexOutOfBoundsException e) {
6629 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6630 }
6631 switch (reqType) {
6632 case TRACK_DEFAULT:
6633 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006634 // is unused and will be replaced by ones appropriate for the UID (usually, the
6635 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006636 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006637 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006638 enforceAccessPermission();
6639 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006640 case TRACK_SYSTEM_DEFAULT:
6641 enforceSettingsPermission();
6642 networkCapabilities = new NetworkCapabilities(defaultNc);
6643 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006644 case BACKGROUND_REQUEST:
6645 enforceNetworkStackOrSettingsPermission();
6646 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006647 case REQUEST:
6648 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6649 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006650 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006651 // TODO: this is incorrect. We mark the request as metered or not depending on
6652 // the state of the app when the request is filed, but we never change the
6653 // request if the app changes network state. http://b/29964605
6654 enforceMeteredApnPolicy(networkCapabilities);
6655 break;
junyulai1b1c8742021-03-12 20:05:08 +08006656 case LISTEN_FOR_BEST:
6657 enforceAccessPermission();
6658 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6659 break;
junyulaiad010792021-01-11 16:53:38 +08006660 default:
6661 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006662 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006663 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006664 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006665 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006666
junyulai1b1c8742021-03-12 20:05:08 +08006667 // Enforce FOREGROUND if the caller does not have permission to use background network.
6668 if (reqType == LISTEN_FOR_BEST) {
6669 restrictBackgroundRequestForCaller(networkCapabilities);
6670 }
6671
6672 // Set the UID range for this request to the single UID of the requester, unless the
6673 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006674 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6675 // are no visible methods to set the UIDs, an app could use reflection to try and get
6676 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006677 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006678 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6679 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006680
Etan Cohen85000162017-02-05 10:42:27 -08006681 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006682 throw new IllegalArgumentException("Bad timeout specified");
6683 }
Etan Cohen9786d922015-11-18 10:56:15 -08006684
James Mattis3ce3d3c2021-02-09 18:18:28 -08006685 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006686 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006687 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006688 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006689 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006690 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006691
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006692 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6693 // copied from the default request above. (This is necessary to ensure, for example, that
6694 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6695 // changes don't alter request matching.
6696 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6697 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006698 throw new IllegalStateException(
6699 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006700 + networkCapabilities + " vs. " + defaultNc);
6701 }
6702
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006703 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006704 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006705 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006706 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006707 }
6708 return networkRequest;
6709 }
6710
James Mattis3ce3d3c2021-02-09 18:18:28 -08006711 /**
6712 * Return the nri to be used when registering a network request. Specifically, this is used with
6713 * requests registered to track the default request. If there is currently a per-app default
6714 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6715 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006716 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6717 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006718 * @param nr the network request for the nri.
6719 * @param msgr the messenger for the nri.
6720 * @param binder the binder for the nri.
6721 * @param callingAttributionTag the calling attribution tag for the nri.
6722 * @return the nri to register.
6723 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006724 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006725 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006726 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006727 @Nullable String callingAttributionTag) {
6728 final List<NetworkRequest> requests;
6729 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6730 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006731 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006732 } else {
6733 requests = Collections.singletonList(nr);
6734 }
Roshan Pius951c0032020-12-22 15:10:42 -08006735 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006736 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006737 }
6738
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006739 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006740 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006741 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006742 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6743 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6744 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6745 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006746 }
junyulai96bd9fe2022-03-08 17:36:42 +08006747 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006748 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006749 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006750 }
6751 }
6752
fenglu3f357402015-03-20 11:29:56 -07006753 @Override
fenglub00f4882015-04-21 17:12:05 -07006754 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006755 enforceAccessPermission();
6756 NetworkAgentInfo nai = null;
6757 if (network == null) {
6758 return false;
6759 }
6760 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006761 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006762 }
6763 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006764 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006765 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006766 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006767 Integer uidReqs = mBandwidthRequests.get(uid);
6768 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006769 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006770 }
6771 mBandwidthRequests.put(uid, ++uidReqs);
6772 }
fenglu3f357402015-03-20 11:29:56 -07006773 return true;
6774 }
6775 return false;
6776 }
6777
Felipe Leme0a5ae422016-06-20 16:36:29 -07006778 private boolean isSystem(int uid) {
6779 return uid < Process.FIRST_APPLICATION_UID;
6780 }
fenglu3f357402015-03-20 11:29:56 -07006781
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006782 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006783 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006784 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006785 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006786 return;
6787 }
Hugo Benichi39621362017-02-11 17:04:43 +09006788 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6789 // Policy already enforced.
6790 return;
6791 }
paulhuaf50d7d2020-12-24 19:47:34 +08006792 final long ident = Binder.clearCallingIdentity();
6793 try {
6794 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6795 // If UID is restricted, don't allow them to bring up metered APNs.
6796 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6797 }
6798 } finally {
6799 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006800 }
6801 }
6802
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006803 @Override
6804 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006805 PendingIntent operation, @NonNull String callingPackageName,
6806 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006807 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006808 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006809 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006810 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006811 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006812 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006813 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006814 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006815 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006816 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6817 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006818
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006819 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006820 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006821 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6822 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006823 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6825 nri));
6826 return networkRequest;
6827 }
6828
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006829 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6830 mHandler.sendMessageDelayed(
6831 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006832 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006833 }
6834
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006835 @Override
6836 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006837 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006838 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006839 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006840 }
6841
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006842 // In order to implement the compatibility measure for pre-M apps that call
6843 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6844 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6845 // This ensures it has permission to do so.
6846 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6847 if (nc == null) {
6848 return false;
6849 }
6850 int[] transportTypes = nc.getTransportTypes();
6851 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6852 return false;
6853 }
6854 try {
6855 mContext.enforceCallingOrSelfPermission(
6856 android.Manifest.permission.ACCESS_WIFI_STATE,
6857 "ConnectivityService");
6858 } catch (SecurityException e) {
6859 return false;
6860 }
6861 return true;
6862 }
6863
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006864 @Override
6865 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006866 Messenger messenger, IBinder binder,
6867 @NetworkCallback.Flag int callbackFlags,
6868 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006869 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006870 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6871 enforceAccessPermission();
6872 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006873
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006874 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006875 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006876 Binder.getCallingPid(), callingUid, callingPackageName);
6877 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006878 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6879 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6880 // onLost and onAvailable callbacks when networks move in and out of the background.
6881 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6882 // can't request networks.
6883 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006884 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006885
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006886 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006887 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006888 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006889 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006890 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006891 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006892
6893 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6894 return networkRequest;
6895 }
6896
6897 @Override
6898 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006899 PendingIntent operation, @NonNull String callingPackageName,
6900 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006901 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006902 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006903 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6904 enforceAccessPermission();
6905 }
Chalard Jeandd421992021-12-16 23:16:02 +09006906 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006907 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006908 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006909 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006910 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006911
6912 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006913 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006914 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6915 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006916 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006917
WeiZhang1cc3f172021-06-03 19:02:04 -05006918 mHandler.sendMessage(mHandler.obtainMessage(
6919 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006920 }
6921
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006922 /** Returns the next Network provider ID. */
6923 public final int nextNetworkProviderId() {
6924 return mNextNetworkProviderId.getAndIncrement();
6925 }
6926
Erik Kline0c04b742016-07-07 16:50:58 +09006927 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006928 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006929 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006930 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006931 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006932 }
6933
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006934 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6935 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006936 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6937 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6938 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006939 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006940 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006941 return;
6942 }
6943
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006944 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6945 mNetworkProviderInfos.put(npi.messenger, npi);
6946 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006947 }
6948
6949 @Override
6950 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006951 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006952 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006953 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006954 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006955 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6956 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006957 }
6958
6959 @Override
6960 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006961 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006962 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006963 }
6964
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006965 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006966 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006967 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6968 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006969 Objects.requireNonNull(score);
6970 Objects.requireNonNull(caps);
6971 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006972 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006973 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006974 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6975 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006976 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6977 }
6978
Chalard Jeanbb902a52021-08-18 01:35:19 +09006979 private void updateOfferScore(final NetworkOffer offer) {
6980 final boolean yieldToBadWiFi =
6981 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6982 final NetworkOffer newOffer = new NetworkOffer(
6983 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6984 offer.caps, offer.callback, offer.providerId);
6985 if (offer.equals(newOffer)) return;
6986 handleRegisterNetworkOffer(newOffer);
6987 }
6988
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006989 @Override
6990 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006991 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006992 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6993 }
6994
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006995 private void handleUnregisterNetworkProvider(Messenger messenger) {
6996 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6997 if (npi == null) {
6998 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006999 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007000 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007001 // Unregister all the offers from this provider
7002 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7003 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007004 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007005 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7006 toRemove.add(noi);
7007 }
7008 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007009 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007010 handleUnregisterNetworkOffer(noi);
7011 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007012 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007013 }
7014
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007015 @Override
James Mattisf7027322020-12-13 16:28:14 -08007016 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007017 if (request.hasTransport(TRANSPORT_TEST)) {
7018 enforceNetworkFactoryOrTestNetworksPermission();
7019 } else {
7020 enforceNetworkFactoryPermission();
7021 }
James Mattisf7027322020-12-13 16:28:14 -08007022 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7023 if (nri != null) {
7024 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7025 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7026 mHandler.post(() -> handleReleaseNetworkRequest(
7027 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7028 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007029 }
7030
Paul Jensen1f567382015-02-13 14:18:39 -05007031 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7032 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007033 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007034 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007035 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007036 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007037 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007038
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007039 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007040 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007041 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007042
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007043 // UID ranges for users that are currently blocked by VPNs.
7044 // This array is accessed and iterated on multiple threads without holding locks, so its
7045 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7046 // (on the handler thread).
7047 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7048
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007049 // Must only be accessed on the handler thread
7050 @NonNull
7051 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7052
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007053 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007054 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007055
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007056 // Current OEM network preferences. This object must only be written to on the handler thread.
7057 // Since it is immutable and always non-null, other threads may read it if they only care
7058 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007059 @NonNull
7060 private OemNetworkPreferences mOemNetworkPreferences =
7061 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007062 // Current per-profile network preferences. This object follows the same threading rules as
7063 // the OEM network preferences above.
7064 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007065 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7066 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007067
paulhu51f77dc2021-06-07 02:34:20 +00007068 // A set of UIDs that should use mobile data preferentially if available. This object follows
7069 // the same threading rules as the OEM network preferences above.
7070 @NonNull
7071 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7072
James Mattiscb1e0362021-04-06 17:07:42 -07007073 // OemNetworkPreferences activity String log entries.
7074 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7075 @NonNull
7076 private final LocalLog mOemNetworkPreferencesLogs =
7077 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7078
James Mattis02220e22021-03-13 19:27:21 -08007079 /**
7080 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7081 * @param packageName the package name to check existence of a mapping for.
7082 * @return true if a mapping exists, false otherwise
7083 */
7084 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7085 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7086 }
7087
James Mattise3ef1912020-12-20 11:09:58 -08007088 // The always-on request for an Internet-capable network that apps without a specific default
7089 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007090 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007091 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007092 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007093 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007094 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007095 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007096 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007097
James Mattisd31bdfa2020-12-23 16:37:26 -08007098 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7099 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7100 }
7101
7102 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007103 * Return the default network request currently tracking the given uid.
7104 * @param uid the uid to check.
7105 * @return the NetworkRequestInfo tracking the given uid.
7106 */
7107 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007108 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007109 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007110 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007111 // Checking the first request is sufficient as only multilayer requests will have more
7112 // than one request and for multilayer, all requests will track the same uids.
7113 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007114 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007115 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007116 highestPriorityNri = nri;
7117 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007118 }
7119 }
paulhuaa0743d2021-05-26 21:56:03 +08007120 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007121 }
7122
7123 /**
7124 * Get a copy of the network requests of the default request that is currently tracking the
7125 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007126 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7127 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007128 * @param requestorUid the uid to check the default for.
7129 * @param requestorPackageName the requestor's package name.
7130 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7131 */
7132 @NonNull
7133 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007134 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007135 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007136 getDefaultRequestTrackingUid(asUid).mRequests,
7137 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007138 }
7139
7140 /**
7141 * Copy the given nri's NetworkRequest collection.
7142 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007143 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7144 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007145 * @param requestorUid the uid to set on the copied collection.
7146 * @param requestorPackageName the package name to set on the copied collection.
7147 * @return the copied NetworkRequest collection.
7148 */
7149 @NonNull
7150 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007151 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7152 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007153 final List<NetworkRequest> requests = new ArrayList<>();
7154 for (final NetworkRequest nr : requestsToCopy) {
7155 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007156 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007157 nr.legacyType, nextNetworkRequestId(), nr.type));
7158 }
7159 return requests;
7160 }
7161
7162 @NonNull
7163 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007164 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7165 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007166 // These capabilities are for a TRACK_DEFAULT callback, so:
7167 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7168 // mDefaultRequest and a per-UID default request.
7169 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007170 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007171 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007172 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7173 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007174 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007175 restrictRequestUidsForCallerAndSetRequestorInfo(
7176 netCap, requestorUid, requestorPackageName);
7177 return netCap;
7178 }
7179
7180 /**
7181 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7182 * @param nr the network request to check for equality against.
7183 * @return the nri if one exists, null otherwise.
7184 */
7185 @Nullable
7186 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7187 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7188 if (nri.getNetworkRequestForCallback().equals(nr)) {
7189 return nri;
7190 }
7191 }
7192 return null;
7193 }
7194
7195 /**
7196 * Check if an nri is currently being managed by per-app default networking.
7197 * @param nri the nri to check.
7198 * @return true if this nri is currently being managed by per-app default networking.
7199 */
7200 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7201 // nri.mRequests.get(0) is only different from the original request filed in
7202 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7203 // functionality therefore if these two don't match, it means this particular nri is
7204 // currently being managed by a per-app default.
7205 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7206 }
7207
7208 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007209 * Determine if an nri is a managed default request that disallows default networking.
7210 * @param nri the request to evaluate
7211 * @return true if device-default networking is disallowed
7212 */
7213 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7214 // Check if this nri is a managed default that supports the default network at its
7215 // lowest priority request.
7216 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7217 final NetworkCapabilities lowestPriorityNetCap =
7218 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7219 return isPerAppDefaultRequest(nri)
7220 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7221 lowestPriorityNetCap));
7222 }
7223
Erik Kline05f2b402015-04-30 12:58:40 +09007224 // Request used to optionally keep mobile data active even when higher
7225 // priority networks like Wi-Fi are active.
7226 private final NetworkRequest mDefaultMobileDataRequest;
7227
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007228 // Request used to optionally keep wifi data active even when higher
7229 // priority networks like ethernet are active.
7230 private final NetworkRequest mDefaultWifiRequest;
7231
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007232 // Request used to optionally keep vehicle internal network always active
7233 private final NetworkRequest mDefaultVehicleRequest;
7234
James Mattisd31bdfa2020-12-23 16:37:26 -08007235 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7236 // network with no service. This NAI should never be matched against, nor should any public API
7237 // ever return the associated network. For this reason, this NAI is not in the list of available
7238 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7239 // default requests that don't support using the device default network which will ultimately
7240 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7241 @VisibleForTesting
7242 final NetworkAgentInfo mNoServiceNetwork;
7243
Chalard Jean5b409c72021-02-04 13:12:59 +09007244 // The NetworkAgentInfo currently satisfying the default request, if any.
7245 private NetworkAgentInfo getDefaultNetwork() {
7246 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007247 }
7248
James Mattis2516da32021-01-31 17:06:19 -08007249 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007250 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007251 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7252 // Currently, all network requests will have the same uids therefore checking the first
7253 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007254 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007255 if (null == uids) {
7256 continue;
7257 }
7258 for (final UidRange range : uids) {
7259 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007260 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007261 highestPriorityNri = nri;
7262 }
James Mattis2516da32021-01-31 17:06:19 -08007263 }
7264 }
7265 }
paulhuaa0743d2021-05-26 21:56:03 +08007266 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007267 }
7268
Varun Ananddf569952019-02-06 10:13:38 -08007269 @Nullable
7270 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7271 return nai != null ? nai.network : null;
7272 }
7273
7274 private void ensureRunningOnConnectivityServiceThread() {
7275 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7276 throw new IllegalStateException(
7277 "Not running on ConnectivityService thread: "
7278 + Thread.currentThread().getName());
7279 }
7280 }
7281
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007282 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007283 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7284 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007285 }
7286
Chalard Jean29d06db2018-05-02 21:14:54 +09007287 /**
7288 * Register a new agent with ConnectivityService to handle a network.
7289 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007290 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007291 * @param networkInfo the initial info associated with this network. It can be updated later :
7292 * see {@link #updateNetworkInfo}.
7293 * @param linkProperties the initial link properties of this network. They can be updated
7294 * later : see {@link #updateLinkProperties}.
7295 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007296 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007297 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007298 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007299 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007300 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007301 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007302 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007303 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007304 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7305 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007306 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7307 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7308 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007309 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007310 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007311 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007312 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007313 } else {
7314 enforceNetworkFactoryPermission();
7315 }
7316
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007317 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007318 final long token = Binder.clearCallingIdentity();
7319 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007320 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007321 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007322 } finally {
7323 Binder.restoreCallingIdentity(token);
7324 }
7325 }
7326
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007327 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007328 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007329 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7330 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007331
Chalard Jeandbc46952022-02-02 00:14:18 +09007332 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7333 // and mutate them at any time.
7334 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7335 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7336 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7337
Chalard Jean366c5252022-01-25 18:27:53 +09007338 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007339 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007340 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7341 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007342 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007343 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007344 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007345 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7346 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007347
Chalard Jeandbc46952022-02-02 00:14:18 +09007348 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007349 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007350 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007351 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007352 mDeps.getNetworkStack().makeNetworkMonitor(
7353 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007354 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7355 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007356 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007357 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007358 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007359 }
7360
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007361 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007362 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007363 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007364 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007365 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007366 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7367 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7368 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007369
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007370 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007371
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007372 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007373 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007374 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007375 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007376
7377 try {
7378 networkMonitor.start();
7379 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007380 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007381 }
Chalard Jean366c5252022-01-25 18:27:53 +09007382
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007383 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007384 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007385 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007386 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007387 }
7388
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007389 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7390 @NonNull public final NetworkOffer offer;
7391
7392 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7393 this.offer = offer;
7394 }
7395
7396 @Override
7397 public void binderDied() {
7398 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7399 }
7400 }
7401
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007402 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7403 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7404 if (npi.providerId == providerId) return true;
7405 }
7406 return false;
7407 }
7408
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007409 /**
7410 * Register or update a network offer.
7411 * @param newOffer The new offer. If the callback member is the same as an existing
7412 * offer, it is an update of that offer.
7413 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007414 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007415 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7416 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007417 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007418 // This may actually happen if a provider updates its score or registers and then
7419 // immediately unregisters. The offer would still be in the handler queue, but the
7420 // provider would have been removed.
7421 if (DBG) log("Received offer from an unregistered provider");
7422 return;
7423 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007424 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7425 if (null != existingOffer) {
7426 handleUnregisterNetworkOffer(existingOffer);
7427 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007428 if (DBG) {
7429 // handleUnregisterNetworkOffer has already logged the old offer
7430 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7431 }
7432 } else {
7433 if (DBG) {
7434 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7435 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007436 }
7437 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7438 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007439 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007440 } catch (RemoteException e) {
7441 noi.binderDied();
7442 return;
7443 }
7444 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007445 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007446 }
7447
7448 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7449 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007450 if (DBG) {
7451 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7452 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007453
7454 // If the provider removes the offer and dies immediately afterwards this
7455 // function may be called twice in a row, but the array will no longer contain
7456 // the offer.
7457 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007458 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007459 }
7460
7461 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7462 @NonNull final INetworkOfferCallback callback) {
7463 ensureRunningOnConnectivityServiceThread();
7464 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007465 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007466 }
7467 return null;
7468 }
7469
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007470 /**
7471 * Called when receiving LinkProperties directly from a NetworkAgent.
7472 * Stores into |nai| any data coming from the agent that might also be written to the network's
7473 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7474 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007475 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007476 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007477 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7478 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007479 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007480 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007481 }
7482
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007483 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007484 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007485 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007486
Lorenzo Colittid523d142020-04-01 20:16:30 +09007487 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7488 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7489 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007490 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007491
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007492 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007493
7494 // update filtering rules, need to happen after the interface update so netd knows about the
7495 // new interface (the interface name -> index map becomes initialized)
7496 updateVpnFiltering(newLp, oldLp, networkAgent);
7497
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007498 updateMtu(newLp, oldLp);
7499 // TODO - figure out what to do for clat
7500// for (LinkProperties lp : newLp.getStackedLinks()) {
7501// updateMtu(lp, null);
7502// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007503 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007504 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7505 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007506
Erik Klineb9888902016-04-05 13:30:49 +09007507 updateRoutes(newLp, oldLp, netId);
7508 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007509 // Make sure LinkProperties represents the latest private DNS status.
7510 // This does not need to be done before updateDnses because the
7511 // LinkProperties are not the source of the private DNS configuration.
7512 // updateDnses will fetch the private DNS configuration from DnsManager.
7513 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007514
Chalard Jean5b409c72021-02-04 13:12:59 +09007515 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007516 handleApplyDefaultProxy(newLp.getHttpProxy());
7517 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007518 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007519 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007520
7521 updateWakeOnLan(newLp);
7522
Hai Shalome58bdc62021-01-11 18:45:34 -08007523 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7524 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7525 // does, it needs to be merged here.
7526 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7527 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007528
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007529 // TODO - move this check to cover the whole function
7530 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007531 synchronized (networkAgent) {
7532 networkAgent.linkProperties = newLp;
7533 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007534 // Start or stop DNS64 detection and 464xlat according to network state.
7535 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007536 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007537 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7538 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007539 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007540 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007541
7542 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007543 }
7544
Hai Shalome58bdc62021-01-11 18:45:34 -08007545 /**
7546 * @param naData captive portal data from NetworkAgent
7547 * @param apiData captive portal data from capport API
7548 */
7549 @Nullable
7550 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7551 CaptivePortalData apiData) {
7552 if (naData == null || apiData == null) {
7553 return naData == null ? apiData : naData;
7554 }
7555 final CaptivePortalData.Builder captivePortalBuilder =
7556 new CaptivePortalData.Builder(naData);
7557
7558 if (apiData.isCaptive()) {
7559 captivePortalBuilder.setCaptive(true);
7560 }
7561 if (apiData.isSessionExtendable()) {
7562 captivePortalBuilder.setSessionExtendable(true);
7563 }
7564 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7565 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7566 // otherwise data would be inconsistent. Prefer the capport API info if present,
7567 // as it can generally be refreshed more often.
7568 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7569 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7570 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7571 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7572 // No source has time / bytes remaining information: surface the newest refresh time
7573 // for other fields
7574 captivePortalBuilder.setRefreshTime(
7575 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7576 }
7577
Hai Shalom7c6ab402021-02-04 19:34:06 -08007578 // Prioritize the user portal URL from the network agent if the source is authenticated.
7579 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7580 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7581 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7582 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007583 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007584 // Prioritize the venue information URL from the network agent if the source is
7585 // authenticated.
7586 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7587 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7588 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7589 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007590 }
7591 return captivePortalBuilder.build();
7592 }
7593
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007594 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007595 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007596 // marks on unsupported interfaces is harmless.
7597 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7598 return;
7599 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007600
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007601 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7602 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7603
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007604 // Mask/mark of zero will not detect anything interesting.
7605 // Don't install rules unless both values are nonzero.
7606 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007607 return;
7608 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007609
7610 final String prefix = "iface:" + iface;
7611 try {
7612 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007613 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007614 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007615 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007616 }
7617 } catch (Exception e) {
7618 loge("Exception modifying wakeup packet monitoring: " + e);
7619 }
7620
Joel Scherpelza235a812017-05-22 13:47:41 +09007621 }
7622
Chalard Jean9589e722019-11-19 19:03:53 +09007623 private void updateInterfaces(final @Nullable LinkProperties newLp,
7624 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007625 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007626 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007627 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7628 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007629 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007630 for (final String iface : interfaceDiff.added) {
7631 try {
7632 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007633 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007634 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007635 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7636 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007637 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007638 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007639 }
Paul Jensenbff73492014-04-28 10:33:11 -04007640 }
7641 }
Chalard Jean9589e722019-11-19 19:03:53 +09007642 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007643 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007644 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007645 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007646 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007647 } catch (Exception e) {
7648 loge("Exception removing interface: " + e);
7649 }
7650 }
7651 }
7652
Tyler Weare4314862019-12-05 14:55:30 -08007653 // TODO: move to frameworks/libs/net.
7654 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7655 final String nextHop;
7656
7657 switch (route.getType()) {
7658 case RouteInfo.RTN_UNICAST:
7659 if (route.hasGateway()) {
7660 nextHop = route.getGateway().getHostAddress();
7661 } else {
7662 nextHop = INetd.NEXTHOP_NONE;
7663 }
7664 break;
7665 case RouteInfo.RTN_UNREACHABLE:
7666 nextHop = INetd.NEXTHOP_UNREACHABLE;
7667 break;
7668 case RouteInfo.RTN_THROW:
7669 nextHop = INetd.NEXTHOP_THROW;
7670 break;
7671 default:
7672 nextHop = INetd.NEXTHOP_NONE;
7673 break;
7674 }
7675
7676 final RouteInfoParcel rip = new RouteInfoParcel();
7677 rip.ifName = route.getInterface();
7678 rip.destination = route.getDestination().toString();
7679 rip.nextHop = nextHop;
7680 rip.mtu = route.getMtu();
7681
7682 return rip;
7683 }
7684
Paul Jensene0fd4a82014-08-06 15:51:33 -04007685 /**
7686 * Have netd update routes from oldLp to newLp.
7687 * @return true if routes changed between oldLp and newLp
7688 */
7689 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007690 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007691 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7692 new CompareOrUpdateResult<>(
7693 oldLp != null ? oldLp.getAllRoutes() : null,
7694 newLp != null ? newLp.getAllRoutes() : null,
7695 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007696
7697 // add routes before removing old in case it helps with continuous connectivity
7698
Chalard Jean9dd11612018-06-04 16:52:49 +09007699 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007700 for (RouteInfo route : routeDiff.added) {
7701 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007702 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007703 try {
Tyler Weare4314862019-12-05 14:55:30 -08007704 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007705 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007706 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007707 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007708 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007709 }
7710 }
7711 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007712 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007713 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007714 try {
Tyler Weare4314862019-12-05 14:55:30 -08007715 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007716 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007717 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007718 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007719 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007720 }
7721 }
7722
7723 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007724 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007725 try {
Tyler Weare4314862019-12-05 14:55:30 -08007726 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007727 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007728 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007729 }
7730 }
Tyler Weare4314862019-12-05 14:55:30 -08007731
7732 for (RouteInfo route : routeDiff.updated) {
7733 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7734 try {
7735 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7736 } catch (Exception e) {
7737 loge("Exception in networkUpdateRouteParcel: " + e);
7738 }
7739 }
7740 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7741 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007742 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007743
Erik Klineb9888902016-04-05 13:30:49 +09007744 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7745 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7746 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007747 }
Erik Klineb9888902016-04-05 13:30:49 +09007748
Erik Kline31b4a9e2018-01-11 21:07:29 +09007749 if (DBG) {
7750 final Collection<InetAddress> dnses = newLp.getDnsServers();
7751 log("Setting DNS servers for network " + netId + " to " + dnses);
7752 }
Erik Klineb9888902016-04-05 13:30:49 +09007753 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007754 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007755 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007756 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007757 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007758 }
Erik Kline54e35c02017-04-07 15:29:29 +09007759 }
7760
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007761 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7762 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007763 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7764 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007765 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7766 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007767
7768 if (!wasFiltering && !needsFiltering) {
7769 // Nothing to do.
7770 return;
7771 }
7772
7773 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7774 // Nothing changed.
7775 return;
7776 }
7777
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007778 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007779 if (ranges == null || ranges.isEmpty()) {
7780 return;
7781 }
7782
Qingxi Libb8da982020-01-17 17:54:27 -08007783 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007784 // TODO: this create a window of opportunity for apps to receive traffic between the time
7785 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007786 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007787 // old rules are being removed.
7788 if (wasFiltering) {
7789 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7790 }
7791 if (needsFiltering) {
7792 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7793 }
7794 }
7795
Valentin Iftime9fa35092019-09-24 13:32:13 +02007796 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007797 if (mWolSupportedInterfaces == null) {
7798 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007799 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007800 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007801 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7802 }
7803
Luke Huangb913c812018-08-24 20:33:16 +08007804 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007805 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007806 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007807 }
7808 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007809 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007810 }
Luke Huangb913c812018-08-24 20:33:16 +08007811 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007812 }
7813
Chalard Jean62edfd82019-12-02 18:39:29 +09007814 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7815 @NonNull final NetworkCapabilities newNc) {
7816 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7817 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007818 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007819 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007820 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007821 } catch (RemoteException | ServiceSpecificException e) {
7822 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007823 }
7824 }
7825 }
7826
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007827 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007828 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007829 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007830 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007831 underlyingNetworks = underlyingNetworksOrDefault(
7832 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007833 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007834 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7835 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007836 // metered if any underlying is metered, or originally declared metered by the agent.
7837 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007838 boolean roaming = false; // roaming if any underlying is roaming
7839 boolean congested = false; // congested if any underlying is congested
7840 boolean suspended = true; // suspended if all underlying are suspended
7841
7842 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007843 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007844 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007845 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007846 for (Network underlyingNetwork : underlyingNetworks) {
7847 final NetworkAgentInfo underlying =
7848 getNetworkAgentInfoForNetwork(underlyingNetwork);
7849 if (underlying == null) continue;
7850
7851 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7852 hadUnderlyingNetworks = true;
7853 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007854 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007855 }
7856
7857 // Merge capabilities of this underlying network. For bandwidth, assume the
7858 // worst case.
7859 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7860 underlyingCaps.getLinkDownstreamBandwidthKbps());
7861 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7862 underlyingCaps.getLinkUpstreamBandwidthKbps());
7863 // If this underlying network is metered, the VPN is metered (it may cost money
7864 // to send packets on this network).
7865 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7866 // If this underlying network is roaming, the VPN is roaming (the billing structure
7867 // is different than the usual, local one).
7868 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7869 // If this underlying network is congested, the VPN is congested (the current
7870 // condition of the network affects the performance of this network).
7871 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7872 // If this network is not suspended, the VPN is not suspended (the VPN
7873 // is able to transfer some data).
7874 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007875 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007876 }
7877 }
7878 if (!hadUnderlyingNetworks) {
7879 // No idea what the underlying networks are; assume reasonable defaults
7880 metered = true;
7881 roaming = false;
7882 congested = false;
7883 suspended = false;
7884 }
7885
lifrade6c2a2021-03-04 14:08:08 +08007886 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007887 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7888 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7889 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7890 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7891 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7892 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007893 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007894 }
7895
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007896 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007897 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7898 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7899 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007900 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007901 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007902 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007903 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007904 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7905 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007906 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007907 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007908 if (nai.everConnected()
7909 && !nai.isVPN()
7910 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007911 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007912 // does not cause any request (that is not a listen) currently matching that agent to
7913 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007914 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007915 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007916 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007917 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007918 }
7919
Paul Jensen53f08952015-06-16 14:27:36 -04007920 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007921 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007922 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007923 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007924 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007925 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007926 }
Chalard Jean254bd162022-08-25 13:04:51 +09007927 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007928 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007929 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007930 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007931 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007932 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007933 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007934 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007935 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007936 }
Chalard Jean254bd162022-08-25 13:04:51 +09007937 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007938 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7939 } else {
7940 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7941 }
lucasline117e2e2019-10-22 18:27:33 +08007942 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007943
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007944 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007945 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7946 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007947 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007948 }
7949
Lorenzo Colittibd079452021-07-02 11:47:57 +09007950 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007951 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007952 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007953 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007954 }
7955
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007956 return newNc;
7957 }
7958
Lorenzo Colitti44840702021-01-11 22:27:57 +09007959 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7960 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7961 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7962 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7963 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7964 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7965 if (prevSuspended != suspended) {
7966 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7967 // onResumed have been removed.
7968 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7969 : ConnectivityManager.CALLBACK_RESUMED);
7970 }
7971 if (prevSuspended != suspended || prevRoaming != roaming) {
7972 // updateNetworkInfo will mix in the suspended info from the capabilities and
7973 // take appropriate action for the network having possibly changed state.
7974 updateNetworkInfo(nai, nai.networkInfo);
7975 }
7976 }
7977
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007978 /**
7979 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7980 *
7981 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7982 * capabilities we manage and store in {@code nai}, such as validated status and captive
7983 * portal status)
7984 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7985 * potentially triggers rematches.
7986 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7987 * change.)
7988 *
7989 * @param oldScore score of the network before any of the changes that prompted us
7990 * to call this function.
7991 * @param nai the network having its capabilities updated.
7992 * @param nc the new network capabilities.
7993 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007994 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007995 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007996 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007997 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007998 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007999 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008000
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008001 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008002 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008003 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008004
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008005 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008006 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8007 // the change we're processing can't affect any requests, it can only affect the listens
8008 // on this network. We might have been called by rematchNetworkAndRequests when a
8009 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008010 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008011 } else {
8012 // If the requestable capabilities have changed or the score changed, we can't have been
8013 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008014 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008015 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008016 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008017 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008018
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008019 final boolean oldMetered = prevNc.isMetered();
8020 final boolean newMetered = newNc.isMetered();
8021 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008022
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008023 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008024 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8025 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008026 }
junyulaif2c67e42018-08-07 19:50:45 +08008027
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008028 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8029 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008030
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008031 // Report changes that are interesting for network statistics tracking.
8032 if (meteredChanged || roamingChanged) {
8033 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008034 }
8035
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008036 // This network might have been underlying another network. Propagate its capabilities.
8037 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008038
8039 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008040 mDnsManager.updateTransportsForNetwork(
8041 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008042 }
lucaslin53e8a262021-06-08 01:43:59 +08008043
8044 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008045 }
8046
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008047 /** Convenience method to update the capabilities for a given network. */
8048 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008049 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008050 }
8051
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008052 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008053 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008054 *
8055 * Ingress interface filtering enforces that all apps under the given network can only receive
8056 * packets from the network's interface (and loopback). This is important for VPNs because
8057 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8058 * non-VPN interfaces.
8059 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008060 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008061 * 1. the network is an app VPN (not legacy VPN)
8062 * 2. the VPN does not allow bypass
8063 * 3. the VPN is fully-routed
8064 * 4. the VPN interface is non-null
8065 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008066 * @see INetd#firewallAddUidInterfaceRules
8067 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008068 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008069 @Nullable
8070 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008071 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008072 if (nc == null || lp == null) return null;
8073 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008074 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008075 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008076 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008077 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008078 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008079 && !lp.hasExcludeRoute()) {
8080 return lp.getInterfaceName();
8081 }
8082 return null;
8083 }
8084
8085 /**
8086 * Returns whether we need to set interface filtering rule or not
8087 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008088 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008089 String isolationIface) {
8090 // Allow rules are always needed if VPN isolation is enabled.
8091 if (isolationIface != null) return true;
8092
8093 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8094 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8095 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8096 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008097 }
8098
Chiachang Wang28afaff2020-12-10 22:24:47 +08008099 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8100 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8101 int index = 0;
8102 for (UidRange range : ranges) {
8103 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8104 index++;
8105 }
8106 return stableRanges;
8107 }
8108
Chalard Jeane6c95272022-01-25 21:04:21 +09008109 private static UidRangeParcel[] intsToUidRangeStableParcels(
8110 final @NonNull ArraySet<Integer> uids) {
8111 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8112 int index = 0;
8113 for (int uid : uids) {
8114 stableRanges[index] = new UidRangeParcel(uid, uid);
8115 index++;
8116 }
8117 return stableRanges;
8118 }
8119
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008120 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8121 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8122 for (int i = 0; i < ranges.length; i++) {
8123 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8124 }
8125 return stableRanges;
8126 }
8127
Ken Chen5e65a852020-12-24 12:59:10 +08008128 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8129 int[] exemptUids) {
8130 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8131 try {
8132 mNetd.socketDestroy(ranges, exemptUids);
8133 } catch (Exception e) {
8134 loge("Exception in socket destroy: ", e);
8135 }
8136 }
8137 }
8138
paulhuaa0743d2021-05-26 21:56:03 +08008139 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008140 int[] exemptUids = new int[2];
8141 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8142 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8143 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8144 exemptUids[0] = VPN_UID;
8145 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8146 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8147
8148 maybeCloseSockets(nai, ranges, exemptUids);
8149 try {
8150 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008151 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008152 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008153 } else {
paulhu0e79d952021-06-09 16:11:35 +08008154 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008155 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008156 }
8157 } catch (Exception e) {
8158 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8159 " on netId " + nai.network.netId + ". " + e);
8160 }
8161 maybeCloseSockets(nai, ranges, exemptUids);
8162 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008163
lucaslin53e8a262021-06-08 01:43:59 +08008164 private boolean isProxySetOnAnyDefaultNetwork() {
8165 ensureRunningOnConnectivityServiceThread();
8166 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8167 final NetworkAgentInfo nai = nri.getSatisfier();
8168 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8169 return true;
8170 }
8171 }
8172 return false;
8173 }
8174
8175 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8176 NetworkCapabilities newNc) {
8177 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8178 // the proxy might be changed since the default network satisfied by the apps might also
8179 // changed.
8180 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8181 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008182 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8183 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008184 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008185 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8186 mProxyTracker.sendProxyBroadcast();
8187 }
8188 }
8189
Chalard Jeane6c95272022-01-25 21:04:21 +09008190 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8191 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008192 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8193 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008194 if (null == prevRanges) prevRanges = new ArraySet<>();
8195 if (null == newRanges) newRanges = new ArraySet<>();
8196 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8197
8198 prevRanges.removeAll(newRanges);
8199 newRanges.removeAll(prevRangesCopy);
8200
8201 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008202 // When updating the VPN uid routing rules, add the new range first then remove the old
8203 // range. If old range were removed first, there would be a window between the old
8204 // range being removed and the new range being added, during which UIDs contained
8205 // in both ranges are not subject to any VPN routing rules. Adding new range before
8206 // removing old range works because, unlike the filtering rules below, it's possible to
8207 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008208 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8209 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8210 // [1-5] & [1-2],[4-5] == [3]
8211 // Then we can do:
8212 // maybeCloseSockets([3])
8213 // mNetd.networkAddUidRanges([1-2],[4-5])
8214 // mNetd.networkRemoveUidRanges([1-5])
8215 // maybeCloseSockets([3])
8216 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8217 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008218 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008219 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008220 }
8221 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008222 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008223 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008224 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8225 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008226 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8227 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008228 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008229 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008230 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8231 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8232 // were added first and then newRanges got removed later, there would be only one uid
8233 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8234 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8235 // Note that this is in contrast with the (more robust) update of VPN routing rules
8236 // above, where the addition of new ranges happens before the removal of old ranges.
8237 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8238 // to be removed will never overlap with the new range to be added.
8239 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008240 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8241 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008242 }
8243 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008244 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008245 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008246 } catch (Exception e) {
8247 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008248 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008249 }
8250 }
8251
Chalard Jeande665262022-02-25 16:12:12 +09008252 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008253 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8254 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008255 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8256 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008257 if (prevEmpty && newEmpty) return;
8258
8259 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008260 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008261 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008262 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008263
8264 if (prevUids.equals(newUids)) return;
8265
8266 // This implementation is very simple and vastly faster for sets of Integers than
8267 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8268 // a key computed from the value and has storage for that.
8269 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8270 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8271 toRemove.removeAll(newUids);
8272 toAdd.removeAll(prevUids);
8273
8274 try {
8275 if (!toAdd.isEmpty()) {
8276 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8277 nai.network.netId,
8278 intsToUidRangeStableParcels(toAdd),
8279 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8280 }
8281 if (!toRemove.isEmpty()) {
8282 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8283 nai.network.netId,
8284 intsToUidRangeStableParcels(toRemove),
8285 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8286 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008287 } catch (ServiceSpecificException e) {
8288 // Has the interface disappeared since the network was built ?
8289 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008290 } catch (RemoteException e) {
8291 // Netd died. This usually causes a runtime restart anyway.
8292 }
8293 }
8294
Hugo Benichi9d35b752017-09-01 01:23:32 +00008295 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008296 ensureRunningOnConnectivityServiceThread();
8297
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008298 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008299 // Ignore updates for disconnected networks
8300 return;
8301 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008302 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008303 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008304 + "; created=" + nai.getCreatedTime()
8305 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008306 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008307 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8308 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008309 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008310 }
8311
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008312 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8313 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008314 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008315 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008316 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008317 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8318 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8319 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008320 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8321 // need to be sent as a separate extra.
8322 final NetworkRequest req = nri.isMultilayerRequest()
8323 ? nri.getActiveRequest()
8324 // Non-multilayer listen requests do not have an active request
8325 : nri.mRequests.get(0);
8326 if (req == null) {
8327 Log.wtf(TAG, "No request in NRI " + nri);
8328 }
8329 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008330 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008331 sendIntent(nri.mPendingIntent, intent);
8332 }
8333 // else not handled
8334 }
8335
8336 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8337 mPendingIntentWakeLock.acquire();
8338 try {
8339 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008340 final BroadcastOptions options = BroadcastOptions.makeBasic();
8341 if (SdkLevel.isAtLeastT()) {
8342 // Explicitly disallow the receiver from starting activities, to prevent apps from
8343 // utilizing the PendingIntent as a backdoor to do this.
8344 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8345 }
8346 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8347 null /* requiredPermission */,
8348 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008349 } catch (PendingIntent.CanceledException e) {
8350 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8351 mPendingIntentWakeLock.release();
8352 releasePendingNetworkRequest(pendingIntent);
8353 }
8354 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8355 }
8356
8357 @Override
8358 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8359 String resultData, Bundle resultExtras) {
8360 if (DBG) log("Finished sending " + pendingIntent);
8361 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008362 // Release with a delay so the receiving client has an opportunity to put in its
8363 // own request.
8364 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008365 }
8366
Chalard Jean46bfbf02022-02-02 00:56:25 +09008367 // networkAgent is only allowed to be null if notificationType is
8368 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8369 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008370 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008371 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008372 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008373 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008374 // Default request has no msgr. Also prevents callbacks from being invoked for
8375 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8376 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8377 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008378 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008379 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008380 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008381 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008382 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008383 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008384 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008385 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8386 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008387 }
Roshan Pius951c0032020-12-22 15:10:42 -08008388 final boolean includeLocationSensitiveInfo =
8389 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008390 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008391 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008392 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008393 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008394 networkCapabilitiesRestrictedForCallerPermissions(
8395 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8396 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008397 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008398 nri.mCallingAttributionTag);
8399 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008400 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8401 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008402 // For this notification, arg1 contains the blocked status.
8403 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008404 break;
8405 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008406 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008407 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008408 break;
8409 }
8410 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008411 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008412 final NetworkCapabilities netCap =
8413 networkCapabilitiesRestrictedForCallerPermissions(
8414 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8415 putParcelable(
8416 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008417 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008418 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008419 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008420 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008421 break;
8422 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008423 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008424 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8425 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008426 break;
8427 }
junyulaif2c67e42018-08-07 19:50:45 +08008428 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008429 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008430 msg.arg1 = arg1;
8431 break;
8432 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008433 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008434 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008435 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008436 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008437 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008438 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008439 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008440 }
James Mattis45d81842021-01-10 14:24:24 -08008441 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008442 } catch (RemoteException e) {
8443 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008444 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008445 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008446 }
8447
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008448 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8449 bundle.putParcelable(t.getClass().getSimpleName(), t);
8450 }
8451
Chalard Jean0702f982021-09-16 21:50:07 +09008452 /**
8453 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8454 *
8455 * When a request should be assigned to a new network, it is normally lingered to give
8456 * time for apps to gracefully migrate their connections. When both networks are on the same
8457 * radio, but that radio can't do time-sharing efficiently, this may end up being
8458 * counter-productive because any traffic on the old network may drastically reduce the
8459 * performance of the new network.
8460 * The stack supports a configuration to let modem vendors state that their radio can't
8461 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8462 * from one cell network to another can't be done gracefully.
8463 *
8464 * @param oldNai the old network serving the request
8465 * @param newNai the new network serving the request
8466 * @return whether the switch can be graceful
8467 */
8468 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8469 @NonNull final NetworkAgentInfo newSatisfier) {
8470 if (mCellularRadioTimesharingCapable) return true;
8471 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8472 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8473 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8474 }
8475
Paul Jensenaf94b982014-09-30 15:37:41 -04008476 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008477 if (nai.numRequestNetworkRequests() != 0) {
8478 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8479 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008480 // Ignore listening and track default requests.
8481 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008482 loge("Dead network still had at least " + nr);
8483 break;
8484 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008485 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008486 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008487 }
8488
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008489 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8490 if (oldNetwork == null) {
8491 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8492 return;
8493 }
Chalard Jean49707572019-12-10 21:07:02 +09008494 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008495
8496 // If we get here it means that the last linger timeout for this network expired. So there
8497 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008498 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008499
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008500 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008501 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008502 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008503 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008504 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008505 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008506 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008507 }
8508
James Mattise3ef1912020-12-20 11:09:58 -08008509 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8510 boolean isDefaultChanged = false;
8511 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8512 final NetworkReassignment.RequestReassignment reassignment =
8513 changes.getReassignment(defaultRequestInfo);
8514 if (null == reassignment) {
8515 continue;
8516 }
8517 // reassignment only contains those instances where the satisfying network changed.
8518 isDefaultChanged = true;
8519 // Notify system services of the new default.
8520 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8521 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008522
James Mattise3ef1912020-12-20 11:09:58 -08008523 if (isDefaultChanged) {
8524 // Hold a wakelock for a short time to help apps in migrating to a new default.
8525 scheduleReleaseNetworkTransitionWakelock();
8526 }
8527 }
8528
8529 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8530 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8531 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8532 if (DBG) {
8533 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8534 }
Chalard Jean8e382112019-12-03 20:45:30 +09008535
James Mattisd31bdfa2020-12-23 16:37:26 -08008536 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8537 if (newDefaultNetwork != null) {
8538 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008539 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008540
James Mattisd31bdfa2020-12-23 16:37:26 -08008541 // Set an app level managed default and return since further processing only applies to the
8542 // default network.
8543 if (mDefaultRequest != nri) {
8544 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8545 return;
8546 }
8547
8548 makeDefaultNetwork(newDefaultNetwork);
8549
James Mattise3ef1912020-12-20 11:09:58 -08008550 if (oldDefaultNetwork != null) {
8551 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8552 }
8553 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008554 handleApplyDefaultProxy(null != newDefaultNetwork
8555 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8556 updateTcpBufferSizes(null != newDefaultNetwork
8557 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008558 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008559 }
8560
James Mattisd31bdfa2020-12-23 16:37:26 -08008561 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8562 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8563 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8564 try {
8565 if (VDBG) {
8566 log("Setting default network for " + nri
8567 + " using UIDs " + nri.getUids()
8568 + " with old network " + (oldDefaultNetwork != null
8569 ? oldDefaultNetwork.network().getNetId() : "null")
8570 + " and new network " + (newDefaultNetwork != null
8571 ? newDefaultNetwork.network().getNetId() : "null"));
8572 }
8573 if (nri.getUids().isEmpty()) {
8574 throw new IllegalStateException("makeDefaultForApps called without specifying"
8575 + " any applications to set as the default." + nri);
8576 }
8577 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008578 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008579 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008580 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008581 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008582 }
8583 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008584 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008585 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008586 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008587 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008588 }
8589 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008590 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008591 }
8592 }
8593
8594 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8595 try {
8596 if (null != newDefaultNetwork) {
8597 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8598 } else {
8599 mNetd.networkClearDefault();
8600 }
8601 } catch (RemoteException | ServiceSpecificException e) {
8602 loge("Exception setting default network :" + e);
8603 }
8604 }
8605
Chalard Jean05cbe972019-12-09 11:50:38 +09008606 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008607 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008608 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008609 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008610 processNewlySatisfiedListenRequests(nai);
8611 }
8612
8613 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008614 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8615 if (nri.isMultilayerRequest()) {
8616 continue;
8617 }
8618 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008619 if (!nr.isListen()) continue;
8620 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008621 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008622 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8623 }
8624 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008625 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008626
Chalard Jeancd397a22019-11-22 22:33:33 +09008627 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008628 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8629 if (nri.isMultilayerRequest()) {
8630 continue;
8631 }
8632 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008633 if (!nr.isListen()) continue;
8634 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8635 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008636 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008637 }
8638 }
8639 }
8640
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008641 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008642 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008643 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008644 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008645 @Nullable public final NetworkRequest mOldNetworkRequest;
8646 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008647 @Nullable public final NetworkAgentInfo mOldNetwork;
8648 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008649 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008650 @Nullable final NetworkRequest oldNetworkRequest,
8651 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008652 @Nullable final NetworkAgentInfo oldNetwork,
8653 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008654 mNetworkRequestInfo = networkRequestInfo;
8655 mOldNetworkRequest = oldNetworkRequest;
8656 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008657 mOldNetwork = oldNetwork;
8658 mNewNetwork = newNetwork;
8659 }
Chalard Jean49707572019-12-10 21:07:02 +09008660
8661 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008662 final NetworkRequest requestToShow = null != mNewNetworkRequest
8663 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8664 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008665 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8666 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008667 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008668 }
8669
Chalard Jean46a62372019-12-10 21:25:24 +09008670 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008671
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008672 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008673 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008674 }
8675
8676 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008677 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008678 // The code is never supposed to add two reassignments of the same request. Make
8679 // sure this stays true, but without imposing this expensive check on all
8680 // reassignments on all user devices.
8681 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008682 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008683 throw new IllegalStateException("Trying to reassign ["
8684 + reassignment + "] but already have ["
8685 + existing + "]");
8686 }
8687 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008688 }
Chalard Jean46a62372019-12-10 21:25:24 +09008689 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008690 }
8691
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008692 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008693 // the passed request.
8694 @Nullable
8695 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008696 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008697 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008698 }
8699 return null;
8700 }
Chalard Jean49707572019-12-10 21:07:02 +09008701
8702 public String toString() {
8703 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8704 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008705 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008706 for (final RequestReassignment rr : getRequestReassignments()) {
8707 sj.add(rr.toString());
8708 }
8709 return sj.toString();
8710 }
8711
8712 public String debugString() {
8713 final StringBuilder sb = new StringBuilder();
8714 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008715 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008716 for (final RequestReassignment rr : getRequestReassignments()) {
8717 sb.append("\n ").append(rr);
8718 }
8719 return sb.append("\n").toString();
8720 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008721 }
8722
Chalard Jean24344d72019-12-04 13:32:31 +09008723 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008724 @Nullable final NetworkRequest previousRequest,
8725 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008726 @Nullable final NetworkAgentInfo previousSatisfier,
8727 @Nullable final NetworkAgentInfo newSatisfier,
8728 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008729 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008730 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008731 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008732 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008733 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008734 }
James Mattisa076c532020-12-02 14:12:41 -08008735 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008736 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008737 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008738 // If this network switch can't be supported gracefully, the request is not
8739 // lingered. This allows letting go of the network sooner to reclaim some
8740 // performance on the new network, since the radio can't do both at the same
8741 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008742 //
8743 // Also don't linger the request if the old network has been destroyed.
8744 // A destroyed network does not provide actual network connectivity, so
8745 // lingering it is not useful. In particular this ensures that a destroyed
8746 // network is outscored by its replacement,
8747 // then it is torn down immediately instead of being lingered, and any apps that
8748 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008749 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8750 }
Chalard Jean24344d72019-12-04 13:32:31 +09008751 } else {
8752 if (VDBG || DDBG) log(" accepting network in place of null");
8753 }
junyulai0ac374f2020-12-14 18:41:52 +08008754
8755 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8756 // and immediately satisfies a request then remove the timer. This will happen for
8757 // all networks except in the case of an underlying network for a VCN.
8758 if (newSatisfier.isNascent()) {
8759 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008760 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008761 }
8762
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008763 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008764 newSatisfier.unlingerRequest(newRequest.requestId);
8765 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008766 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008767 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008768 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008769 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008770 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008771 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008772 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008773 }
James Mattisa076c532020-12-02 14:12:41 -08008774 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008775 }
James Mattisa076c532020-12-02 14:12:41 -08008776 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008777 }
8778
James Mattisa076c532020-12-02 14:12:41 -08008779 /**
8780 * This function is triggered when something can affect what network should satisfy what
8781 * request, and it computes the network reassignment from the passed collection of requests to
8782 * network match to the one that the system should now have. That data is encoded in an
8783 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8784 * satisfier.
8785 *
8786 * After the reassignment is computed, it is applied to the state objects.
8787 *
8788 * @param networkRequests the nri objects to evaluate for possible network reassignment
8789 * @return NetworkReassignment listing of proposed network assignment changes
8790 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008791 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008792 private NetworkReassignment computeNetworkReassignment(
8793 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008794 final NetworkReassignment changes = new NetworkReassignment();
8795
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008796 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008797 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008798 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008799 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008800 }
Chalard Jean857a1712019-12-10 21:08:07 +09008801
James Mattisa076c532020-12-02 14:12:41 -08008802 for (final NetworkRequestInfo nri : networkRequests) {
8803 // Non-multilayer listen requests can be ignored.
8804 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8805 continue;
8806 }
8807 NetworkAgentInfo bestNetwork = null;
8808 NetworkRequest bestRequest = null;
8809 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008810 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008811 // Stop evaluating as the highest possible priority request is satisfied.
8812 if (null != bestNetwork) {
8813 bestRequest = req;
8814 break;
8815 }
8816 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008817 if (null == bestNetwork && isDefaultBlocked(nri)) {
8818 // Remove default networking if disallowed for managed default requests.
8819 bestNetwork = mNoServiceNetwork;
8820 }
8821 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008822 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008823 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008824 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008825 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008826 }
8827 return changes;
8828 }
8829
James Mattisa076c532020-12-02 14:12:41 -08008830 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8831 return new HashSet<>(mNetworkRequests.values());
8832 }
8833
Paul Jensenc88b39b2015-06-16 14:27:36 -04008834 /**
James Mattisa076c532020-12-02 14:12:41 -08008835 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008836 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008837 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008838 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008839 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8840 }
8841
8842 /**
8843 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8844 * being disconnected.
8845 */
8846 private void rematchNetworksAndRequests(
8847 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8848 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008849 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008850 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008851 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008852 final long computed = SystemClock.elapsedRealtime();
8853 applyNetworkReassignment(changes, start);
8854 final long applied = SystemClock.elapsedRealtime();
8855 issueNetworkNeeds();
8856 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008857 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008858 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8859 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008860 log(changes.debugString());
8861 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008862 // Shorter form, only one line of log
8863 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8864 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008865 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008866 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008867
Chalard Jeand7f762d2019-12-10 19:01:29 +09008868 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008869 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008870 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008871
8872 // Since most of the time there are only 0 or 1 background networks, it would probably
8873 // be more efficient to just use an ArrayList here. TODO : measure performance
8874 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8875 for (final NetworkAgentInfo nai : nais) {
8876 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8877 }
8878
Chalard Jeand7f762d2019-12-10 19:01:29 +09008879 // First, update the lists of satisfied requests in the network agents. This is necessary
8880 // because some code later depends on this state to be correct, most prominently computing
8881 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008882 for (final NetworkReassignment.RequestReassignment event :
8883 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008884 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8885 event.mOldNetworkRequest, event.mNewNetworkRequest,
8886 event.mOldNetwork, event.mNewNetwork,
8887 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008888 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008889
James Mattise3ef1912020-12-20 11:09:58 -08008890 // Process default network changes if applicable.
8891 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008892
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008893 // Notify requested networks are available after the default net is switched, but
8894 // before LegacyTypeTracker sends legacy broadcasts
8895 for (final NetworkReassignment.RequestReassignment event :
8896 changes.getRequestReassignments()) {
8897 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008898 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008899 } else {
James Mattisa076c532020-12-02 14:12:41 -08008900 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008901 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008902 }
8903 }
8904
junyulai0ac374f2020-12-14 18:41:52 +08008905 // Update the inactivity state before processing listen callbacks, because the background
8906 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008907 // just yet though, because they have to be sent after the listens are processed to keep
8908 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008909 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008910 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008911 // Rematching may have altered the inactivity state of some networks, so update all
8912 // inactivity timers. updateInactivityState reads the state from the network agent
8913 // and does nothing if the state has not changed : the source of truth is controlled
8914 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8915 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008916 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008917 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008918 }
8919 }
8920
Chalard Jeanb10ab412019-12-11 14:12:30 +09008921 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008922 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008923 // Process listen requests and update capabilities if the background state has
8924 // changed for this network. For consistency with previous behavior, send onLost
8925 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008926 processNewlyLostListenRequests(nai);
8927 if (oldBackground != nai.isBackgroundNetwork()) {
8928 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008929 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008930 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008931 }
8932
junyulai0ac374f2020-12-14 18:41:52 +08008933 for (final NetworkAgentInfo nai : inactiveNetworks) {
8934 // For nascent networks, if connecting with no foreground request, skip broadcasting
8935 // LOSING for backward compatibility. This is typical when mobile data connected while
8936 // wifi connected with mobile data always-on enabled.
8937 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008938 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008939 }
8940
James Mattise3ef1912020-12-20 11:09:58 -08008941 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008942
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008943 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008944 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008945 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008946 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008947 // This network has active linger timers and no requests, but is not
8948 // lingering. Linger it.
8949 //
8950 // One way (the only way?) this can happen if this network is unvalidated
8951 // and became unneeded due to another network improving its score to the
8952 // point where this network will no longer be able to satisfy any requests
8953 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008954 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008955 notifyNetworkLosing(nai, now);
8956 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008957 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008958 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008959 teardownUnneededNetwork(nai);
8960 }
8961 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008962 }
8963 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008964
Chalard Jean62edfd82019-12-02 18:39:29 +09008965 /**
8966 * Apply a change in background state resulting from rematching networks with requests.
8967 *
8968 * During rematch, a network may change background states by starting to satisfy or stopping
8969 * to satisfy a foreground request. Listens don't count for this. When a network changes
8970 * background states, its capabilities need to be updated and callbacks fired for the
8971 * capability change.
8972 *
8973 * @param nai The network that changed background states
8974 */
8975 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8976 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8977 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8978 updateNetworkPermissions(nai, newNc);
8979 nai.getAndSetNetworkCapabilities(newNc);
8980 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8981 }
8982
Chalard Jeanf0344532019-11-19 19:23:38 +09008983 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008984 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008985 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008986 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8987 changes.getReassignment(mDefaultRequest);
8988 final NetworkAgentInfo oldDefaultNetwork =
8989 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8990 final NetworkAgentInfo newDefaultNetwork =
8991 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008992
Chalard Jean5b409c72021-02-04 13:12:59 +09008993 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008994 // Maintain the illusion : since the legacy API only understands one network at a time,
8995 // if the default network changed, apps should see a disconnected broadcast for the
8996 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008997 if (oldDefaultNetwork != null) {
8998 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8999 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009000 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009001 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009002 // The new default network can be newly null if and only if the old default
9003 // network doesn't satisfy the default request any more because it lost a
9004 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009005 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009006 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009007 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009008 }
9009 }
9010
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009011 // Now that all the callbacks have been sent, send the legacy network broadcasts
9012 // as needed. This is necessary so that legacy requests correctly bind dns
9013 // requests to this network. The legacy users are listening for this broadcast
9014 // and will generally do a dns request so they can ensureRouteToHost and if
9015 // they do that before the callbacks happen they'll use the default network.
9016 //
9017 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9018 // callbacks, but if apps can receive the broadcast before the callback, they still might
9019 // have an inconsistent view of networking.
9020 //
9021 // This *does* introduce a race where if the user uses the new api
9022 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9023 // they may get old info. Reverse this after the old startUsing api is removed.
9024 // This is on top of the multiple intent sequencing referenced in the todo above.
9025 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009026 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009027 addNetworkToLegacyTypeTracker(nai);
9028 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009029 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009030 }
9031
Chalard Jean0354d8c2021-01-12 10:58:56 +09009032 private void issueNetworkNeeds() {
9033 ensureRunningOnConnectivityServiceThread();
9034 for (final NetworkOfferInfo noi : mNetworkOffers) {
9035 issueNetworkNeeds(noi);
9036 }
9037 }
9038
9039 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9040 ensureRunningOnConnectivityServiceThread();
9041 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9042 informOffer(nri, noi.offer, mNetworkRanker);
9043 }
9044 }
9045
9046 /**
9047 * Inform a NetworkOffer about any new situation of a request.
9048 *
9049 * This function handles updates to offers. A number of events may happen that require
9050 * updating the registrant for this offer about the situation :
9051 * • The offer itself was updated. This may lead the offer to no longer being able
9052 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9053 * or conversely being strengthened enough to beat the satisfier (and therefore
9054 * start being needed)
9055 * • The network satisfying a request changed (including cases where the request
9056 * starts or stops being satisfied). The new network may be a stronger or weaker
9057 * match than the old one, possibly affecting whether the offer is needed.
9058 * • The network satisfying a request updated their score. This may lead the offer
9059 * to no longer be able to beat it if the current satisfier got better, or
9060 * conversely start being a good choice if the current satisfier got weaker.
9061 *
9062 * @param nri The request
9063 * @param offer The offer. This may be an updated offer.
9064 */
9065 private static void informOffer(@NonNull NetworkRequestInfo nri,
9066 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9067 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9068 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009069
9070 // Multi-layer requests have a currently active request, the one being satisfied.
9071 // Since the system will try to bring up a better network than is currently satisfying
9072 // the request, NetworkProviders need to be told the offers matching the requests *above*
9073 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9074 // not needed, and the offer is needed for the active request iff the offer can beat
9075 // the satisfier.
9076 // For non-multilayer requests, the logic above gracefully degenerates to only the
9077 // last case.
9078 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9079 // providers that the offer is needed for this request, until the active request is found.
9080 // In a second phase, deal with the currently active request. In a third phase, inform
9081 // the providers that offer is unneeded for the remaining requests.
9082
9083 // First phase : inform providers of all requests above the active request.
9084 int i;
9085 for (i = 0; nri.mRequests.size() > i; ++i) {
9086 final NetworkRequest request = nri.mRequests.get(i);
9087 if (activeRequest == request) break; // Found the active request : go to phase 2
9088 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9089 // Since this request is higher-priority than the one currently satisfied, if the
9090 // offer can satisfy it, the provider should try and bring up the network for sure ;
9091 // no need to even ask the ranker – an offer that can satisfy is always better than
9092 // no network. Hence tell the provider so unless it already knew.
9093 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9094 offer.onNetworkNeeded(request);
9095 }
9096 }
9097
9098 // Second phase : deal with the active request (if any)
9099 if (null != activeRequest && activeRequest.isRequest()) {
9100 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009101 // If an offer can satisfy the request, it is considered needed if it is currently
9102 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009103 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009104 && satisfier.factorySerialNumber == offer.providerId
9105 && activeRequest.canBeSatisfiedBy(offer.caps);
9106 final boolean newNeeded = currentlyServing
9107 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009108 if (newNeeded != oldNeeded) {
9109 if (newNeeded) {
9110 offer.onNetworkNeeded(activeRequest);
9111 } else {
9112 // The offer used to be able to beat the satisfier. Now it can't.
9113 offer.onNetworkUnneeded(activeRequest);
9114 }
9115 }
9116 }
9117
9118 // Third phase : inform the providers that the offer isn't needed for any request
9119 // below the active one.
9120 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9121 final NetworkRequest request = nri.mRequests.get(i);
9122 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9123 // Since this request is lower-priority than the one currently satisfied, if the
9124 // offer can satisfy it, the provider should not try and bring up the network.
9125 // Hence tell the provider so unless it already knew.
9126 if (offer.neededFor(request)) {
9127 offer.onNetworkUnneeded(request);
9128 }
9129 }
9130 }
9131
Chalard Jean61c79252019-11-07 23:07:32 +09009132 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9133 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9134 NetworkRequest nr = nai.requestAt(i);
9135 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9136 // legacy type tracker filters out repeat adds
9137 mLegacyTypeTracker.add(nr.legacyType, nai);
9138 }
9139 }
9140
9141 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009142 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009143 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9144 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9145 if (nai.isVPN()) {
9146 mLegacyTypeTracker.add(TYPE_VPN, nai);
9147 }
9148 }
9149
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009150 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009151 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009152 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009153 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009154 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009155 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009156
Chalard Jean254bd162022-08-25 13:04:51 +09009157 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009158 // Don't repeat publish.
9159 if (newInetCondition == mDefaultInetConditionPublished) return;
9160
9161 mDefaultInetConditionPublished = newInetCondition;
9162 sendInetConditionBroadcast(nai.networkInfo);
9163 }
9164
Chalard Jeand61375d2020-01-14 22:46:36 +09009165 @NonNull
9166 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9167 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009168 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009169 final boolean suspended =
9170 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9171 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9172 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9173 // state. This is because the network could have been suspended before connecting,
9174 // or it could be disconnecting while being suspended, and in both these cases
9175 // the state should not be overridden. Note that the only detailed state that
9176 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9177 // worry about multiple different substates of CONNECTED.
9178 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9179 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009180 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9181 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9182 // network agent is created, then goes to suspended, then goes out of suspended without
9183 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009184 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009185 ? NetworkInfo.DetailedState.CONNECTED
9186 : NetworkInfo.DetailedState.CONNECTING,
9187 info.getReason(),
9188 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009189 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009190 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009191 return newInfo;
9192 }
9193
9194 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9195 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9196
Erik Kline99f301b2017-02-15 19:59:17 +09009197 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009198 NetworkInfo oldInfo = null;
9199 synchronized (networkAgent) {
9200 oldInfo = networkAgent.networkInfo;
9201 networkAgent.networkInfo = newInfo;
9202 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009203
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009204 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009205 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9206 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009207 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009208
Chalard Jean254bd162022-08-25 13:04:51 +09009209 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009210 && (state == NetworkInfo.State.CONNECTED
9211 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009212
9213 // A network that has just connected has zero requests and is thus a foreground network.
9214 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9215
Luke Huangfdd11f82019-04-09 18:41:49 +08009216 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009217 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009218 // Initialize the network's capabilities to their starting values according to the
9219 // underlying networks. This ensures that the capabilities are correct before
9220 // anything happens to the network.
9221 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009222 }
Chalard Jean254bd162022-08-25 13:04:51 +09009223 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009224 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009225 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009226 }
9227
Chalard Jean254bd162022-08-25 13:04:51 +09009228 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9229 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009230
lucaslin45e639b2019-04-03 17:09:28 +08009231 // NetworkCapabilities need to be set before sending the private DNS config to
9232 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009233 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9234
Erik Kline9a62f012018-03-21 07:18:33 -07009235 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009236 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9237 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009238
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009239 // If a rate limit has been configured and is applicable to this network (network
9240 // provides internet connectivity), apply it. The tc police filter cannot be attached
9241 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9242 // updateInterfaces -> INetd#networkAddInterface.
9243 // Note: in case of a system server crash, the NetworkController constructor in netd
9244 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9245 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9246 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9247 mIngressRateLimit);
9248 }
9249
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009250 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9251 // command must be sent after updating LinkProperties to maximize chances of
9252 // NetworkMonitor seeing the correct LinkProperties when starting.
9253 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009254 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009255 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009256 }
Chalard Jeand4900722022-02-06 12:25:38 +09009257 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9258 params.networkAgentConfig = networkAgent.networkAgentConfig;
9259 params.networkCapabilities = networkAgent.networkCapabilities;
9260 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9261 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009262 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9263 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9264 // call that would cause a Log.wtf to be emitted from the system_server process, and
9265 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9266 // process to check the interface version, just use an SDK check. NetworkStack will
9267 // always be new enough when running on T+.
9268 if (SdkLevel.isAtLeastT()) {
9269 networkAgent.networkMonitor().notifyNetworkConnected(params);
9270 } else {
9271 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9272 params.networkCapabilities);
9273 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009274 final long delay = activelyPreferBadWifi()
9275 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9276 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9277 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009278
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009279 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9280 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9281 // capabilities, so it only needs to be done once on initial connect, not every time the
9282 // network's capabilities change. Note that we do this before rematching the network,
9283 // so we could decide to tear it down immediately afterwards. That's fine though - on
9284 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9285 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009286 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009287
junyulai0ac374f2020-12-14 18:41:52 +08009288 // Before first rematching networks, put an inactivity timer without any request, this
9289 // allows {@code updateInactivityState} to update the state accordingly and prevent
9290 // tearing down for any {@code unneeded} evaluation in this period.
9291 // Note that the timer will not be rescheduled since the expiry time is
9292 // fixed after connection regardless of the network satisfying other requests or not.
9293 // But it will be removed as soon as the network satisfies a request for the first time.
9294 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9295 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009296 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009297
Paul Jensen05e85ee2014-09-11 11:00:39 -04009298 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009299 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009300
9301 // This has to happen after matching the requests, because callbacks are just requests.
9302 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009303 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009304 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009305 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009306 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009307 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009308 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009309 if (networkAgent.isVPN()) {
9310 // As the active or bound network changes for apps, broadcast the default proxy, as
9311 // apps may need to update their proxy data. This is called after disconnecting from
9312 // VPN to make sure we do not broadcast the old proxy data.
9313 // TODO(b/122649188): send the broadcast only to VPN users.
9314 mProxyTracker.sendProxyBroadcast();
9315 }
Chalard Jean254bd162022-08-25 13:04:51 +09009316 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9317 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009318 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009319 }
9320 }
9321
Chalard Jean28018572020-12-21 18:36:52 +09009322 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009323 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9324 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009325 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009326 }
9327
Erik Kline99f301b2017-02-15 19:59:17 +09009328 // Notify only this one new request of the current state. Transfer all the
9329 // current state by calling NetworkCapabilities and LinkProperties callbacks
9330 // so that callers can be guaranteed to have as close to atomicity in state
9331 // transfer as can be supported by this current API.
9332 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009333 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009334 if (nri.mPendingIntent != null) {
9335 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9336 // Attempt no subsequent state pushes where intents are involved.
9337 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009338 }
Erik Kline99f301b2017-02-15 19:59:17 +09009339
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009340 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009341 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009342 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9343 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9344 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009345 }
9346
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009347 // Notify the requests on this NAI that the network is now lingered.
9348 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009349 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009350 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9351 }
9352
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009353 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9354 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9355 return vpnBlocked
9356 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9357 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9358 }
9359
9360 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9361 if (blockedReasons == BLOCKED_REASON_NONE) {
9362 mUidBlockedReasons.delete(uid);
9363 } else {
9364 mUidBlockedReasons.put(uid, blockedReasons);
9365 }
9366 }
9367
junyulaif2c67e42018-08-07 19:50:45 +08009368 /**
9369 * Notify of the blocked state apps with a registered callback matching a given NAI.
9370 *
9371 * Unlike other callbacks, blocked status is different between each individual uid. So for
9372 * any given nai, all requests need to be considered according to the uid who filed it.
9373 *
9374 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009375 * @param oldMetered True if the previous network capabilities were metered.
9376 * @param newMetered True if the current network capabilities are metered.
9377 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9378 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009379 */
9380 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009381 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9382 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009383
9384 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9385 NetworkRequest nr = nai.requestAt(i);
9386 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009387
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009388 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9389 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9390 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009391 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009392 : oldVpnBlocked;
9393
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009394 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9395 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9396 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009397 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009398 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009399 }
9400 }
9401 }
9402
9403 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009404 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009405 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009406 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009407 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009408 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009409 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009410 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009411 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009412
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009413 final int oldBlockedState = getBlockedState(
9414 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9415 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9416 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009417 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009418 }
junyulaif2c67e42018-08-07 19:50:45 +08009419 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9420 NetworkRequest nr = nai.requestAt(i);
9421 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009422 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009423 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9424 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009425 }
9426 }
9427 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009428 }
9429
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009430 @VisibleForTesting
9431 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009432 // The NetworkInfo we actually send out has no bearing on the real
9433 // state of affairs. For example, if the default connection is mobile,
9434 // and a request for HIPRI has just gone away, we need to pretend that
9435 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9436 // the state to DISCONNECTED, even though the network is of type MOBILE
9437 // and is still connected.
9438 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9439 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009440 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009441 if (state != DetailedState.DISCONNECTED) {
9442 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009443 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009444 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009445 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009446 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9447 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9448 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9449 if (info.isFailover()) {
9450 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9451 nai.networkInfo.setFailover(false);
9452 }
9453 if (info.getReason() != null) {
9454 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9455 }
9456 if (info.getExtraInfo() != null) {
9457 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9458 }
9459 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009460 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009461 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009462 if (newDefaultAgent != null) {
9463 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9464 newDefaultAgent.networkInfo);
9465 } else {
9466 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9467 }
9468 }
9469 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9470 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009471 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009472 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009473 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009474 }
9475 }
9476 }
9477
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009478 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009479 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009480 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009481 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009482 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009483 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9484 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009485 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9486 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009487 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009488 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009489 } else {
9490 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9491 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009492 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009493 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009494
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009495 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9496 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9497 }
9498
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009499 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009500 * Returns the list of all interfaces that could be used by network traffic that does not
9501 * explicitly specify a network. This includes the default network, but also all VPNs that are
9502 * currently connected.
9503 *
9504 * Must be called on the handler thread.
9505 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009506 @NonNull
9507 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009508 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009509 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009510 final Set<Integer> activeNetIds = new ArraySet<>();
9511 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9512 if (nri.isBeingSatisfied()) {
9513 activeNetIds.add(nri.getSatisfier().network().netId);
9514 }
9515 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009516 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009517 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009518 defaultNetworks.add(nai.network);
9519 }
9520 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009521 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009522 }
9523
9524 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009525 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9526 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009527 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009528 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009529 ensureRunningOnConnectivityServiceThread();
9530 String activeIface = null;
9531 LinkProperties activeLinkProperties = getActiveLinkProperties();
9532 if (activeLinkProperties != null) {
9533 activeIface = activeLinkProperties.getInterfaceName();
9534 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009535
junyulai2050bed2021-01-23 09:46:34 +08009536 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009537 try {
junyulaide41fc22021-01-22 22:46:01 +08009538 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009539 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009540 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9541 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009542 } catch (Exception ignored) {
9543 }
9544 }
9545
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009546 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009547 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009548 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009549 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009550 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009551
9552 if (!TextUtils.isEmpty(settingUrl)) {
9553 return settingUrl;
9554 }
9555
9556 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009557 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009558 if (!TextUtils.isEmpty(settingUrl)) {
9559 return settingUrl;
9560 }
9561
9562 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009563 }
9564
9565 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009566 public void startNattKeepalive(Network network, int intervalSeconds,
9567 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009568 enforceKeepalivePermission();
9569 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009570 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009571 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009572 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009573 }
9574
9575 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009576 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009577 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009578 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009579 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009580 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009581 mKeepaliveTracker.startNattKeepalive(
9582 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9583 intervalSeconds, cb,
9584 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9585 } finally {
9586 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9587 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009588 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9589 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009590 }
9591 }
junyulaid05a1922019-01-15 11:32:44 +08009592 }
9593
9594 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009595 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009596 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009597 try {
9598 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009599 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009600 mKeepaliveTracker.startTcpKeepalive(
9601 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9602 } finally {
9603 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9604 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009605 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9606 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009607 }
9608 }
junyulai0835a1e2019-01-08 20:04:33 +08009609 }
9610
9611 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009612 public void stopKeepalive(Network network, int slot) {
9613 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009614 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009615 }
9616
9617 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009618 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009619 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009620
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009621 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009622 final long token = Binder.clearCallingIdentity();
9623 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009624 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9625 UserHandle.getUserHandleForUid(uid))) {
9626 return;
9627 }
9628
Heemin Seogdb8489d2019-06-12 09:21:44 -07009629 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9630 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009631
9632 // Turn airplane mode off
9633 setAirplaneMode(false);
9634
9635 // restore private DNS settings to default mode (opportunistic)
9636 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9637 UserHandle.getUserHandleForUid(uid))) {
9638 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9639 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9640 }
9641
9642 Settings.Global.putString(mContext.getContentResolver(),
9643 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009644 } finally {
9645 Binder.restoreCallingIdentity(token);
9646 }
Stuart Scottd5463642015-04-02 18:00:02 -07009647 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009648
Ricky Wai7097cc92018-01-23 04:09:45 +00009649 @Override
9650 public byte[] getNetworkWatchlistConfigHash() {
9651 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9652 if (nwm == null) {
9653 loge("Unable to get NetworkWatchlistManager");
9654 return null;
9655 }
9656 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9657 return nwm.getWatchlistConfigHash();
9658 }
9659
Hugo Benichibe0c7652016-05-31 16:28:06 +09009660 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009661 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009662 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009663 }
Hugo Benichif4210292017-04-21 15:07:12 +09009664
9665 private static boolean toBool(int encodedBoolean) {
9666 return encodedBoolean != 0; // Only 0 means false.
9667 }
9668
9669 private static int encodeBool(boolean b) {
9670 return b ? 1 : 0;
9671 }
mswest4632928412018-03-12 10:34:34 -07009672
9673 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009674 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9675 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9676 @NonNull String[] args) {
9677 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9678 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009679 }
9680
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009681 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009682 @Override
9683 public int onCommand(String cmd) {
9684 if (cmd == null) {
9685 return handleDefaultCommands(cmd);
9686 }
9687 final PrintWriter pw = getOutPrintWriter();
9688 try {
9689 switch (cmd) {
9690 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009691 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9692 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009693 final String action = getNextArg();
9694 if ("enable".equals(action)) {
9695 setAirplaneMode(true);
9696 return 0;
9697 } else if ("disable".equals(action)) {
9698 setAirplaneMode(false);
9699 return 0;
9700 } else if (action == null) {
9701 final ContentResolver cr = mContext.getContentResolver();
9702 final int enabled = Settings.Global.getInt(cr,
9703 Settings.Global.AIRPLANE_MODE_ON);
9704 pw.println(enabled == 0 ? "disabled" : "enabled");
9705 return 0;
9706 } else {
9707 onHelp();
9708 return -1;
9709 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009710 case "reevaluate":
9711 // Usage : adb shell cmd connectivity reevaluate <netId>
9712 // If netId is omitted, then reevaluate the default network
9713 final String netId = getNextArg();
9714 final NetworkAgentInfo nai;
9715 if (null == netId) {
9716 // Note that the command is running on the wrong thread to call this,
9717 // so this could in principle return stale data. But it can't crash.
9718 nai = getDefaultNetwork();
9719 } else {
9720 // If netId can't be parsed, this throws NumberFormatException, which
9721 // is passed back to adb who prints it.
9722 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
9723 }
9724 if (null == nai) {
9725 pw.println("Unknown network (net ID not found or no default network)");
9726 return 0;
9727 }
9728 Log.d(TAG, "Reevaluating network " + nai.network);
9729 reportNetworkConnectivity(nai.network, !nai.isValidated());
9730 return 0;
mswest4632928412018-03-12 10:34:34 -07009731 default:
9732 return handleDefaultCommands(cmd);
9733 }
9734 } catch (Exception e) {
9735 pw.println(e);
9736 }
9737 return -1;
9738 }
9739
9740 @Override
9741 public void onHelp() {
9742 PrintWriter pw = getOutPrintWriter();
9743 pw.println("Connectivity service commands:");
9744 pw.println(" help");
9745 pw.println(" Print this help text.");
9746 pw.println(" airplane-mode [enable|disable]");
9747 pw.println(" Turn airplane mode on or off.");
9748 pw.println(" airplane-mode");
9749 pw.println(" Get airplane mode.");
9750 }
9751 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009752
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009753 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009754 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9755 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9756 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009757 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009758 }
9759
he_won.hwang881307a2022-03-15 21:23:52 +09009760 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9761 if (nai == null) return;
9762 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9763 final TransportInfo newInfo = nc.getTransportInfo();
9764 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9765 return;
9766 }
9767 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009768 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009769 }
9770 }
9771
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009772 /**
9773 * @param connectionInfo the connection to resolve.
9774 * @return {@code uid} if the connection is found and the app has permission to observe it
9775 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9776 * connection is not found.
9777 */
9778 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009779 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9780 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9781 }
9782
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009783 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009784 connectionInfo.local, connectionInfo.remote);
9785
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009786 if (uid == INVALID_UID) return uid; // Not found.
9787
9788 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9789 // VPN, if any, that applies to the UID that owns the connection.
9790 if (checkNetworkStackPermission()) return uid;
9791
9792 final NetworkAgentInfo vpn = getVpnForUid(uid);
9793 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009794 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009795 return INVALID_UID;
9796 }
9797
9798 return uid;
9799 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009800
Benedict Wong493e04b2018-11-09 14:45:34 -08009801 /**
9802 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9803 *
9804 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9805 */
9806 @Override
9807 public IBinder startOrGetTestNetworkService() {
9808 synchronized (mTNSLock) {
9809 TestNetworkService.enforceTestNetworkPermissions(mContext);
9810
9811 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009812 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009813 }
9814
9815 return mTNS;
9816 }
9817 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009818
Cody Kesting73708bf2019-12-18 10:57:50 -08009819 /**
9820 * Handler used for managing all Connectivity Diagnostics related functions.
9821 *
9822 * @see android.net.ConnectivityDiagnosticsManager
9823 *
9824 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9825 */
9826 @VisibleForTesting
9827 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009828 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9829
Cody Kesting73708bf2019-12-18 10:57:50 -08009830 /**
9831 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9832 * android.net.ConnectivityDiagnosticsManager}.
9833 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9834 * NetworkRequestInfo to be registered
9835 */
9836 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9837
9838 /**
9839 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9840 * android.net.ConnectivityDiagnosticsManager}.
9841 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9842 * arg1 = the uid of the caller
9843 */
9844 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9845
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009846 /**
9847 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009848 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009849 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9850 * NetworkMonitor.
9851 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009852 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009853 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009854
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009855 /**
9856 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9857 * been detected on the network.
9858 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9859 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9860 * arg2 = NetID.
9861 * data = PersistableBundle of extras passed from NetworkMonitor.
9862 */
9863 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9864
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009865 /**
9866 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9867 * the platform. This event will invoke {@link
9868 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9869 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009870 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009871 */
9872 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9873
Cody Kesting73708bf2019-12-18 10:57:50 -08009874 private ConnectivityDiagnosticsHandler(Looper looper) {
9875 super(looper);
9876 }
9877
9878 @Override
9879 public void handleMessage(Message msg) {
9880 switch (msg.what) {
9881 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9882 handleRegisterConnectivityDiagnosticsCallback(
9883 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9884 break;
9885 }
9886 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9887 handleUnregisterConnectivityDiagnosticsCallback(
9888 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9889 break;
9890 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009891 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009892 final ConnectivityReportEvent reportEvent =
9893 (ConnectivityReportEvent) msg.obj;
9894
Aaron Huang959d3642021-01-21 15:47:41 +08009895 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009896 break;
9897 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009898 case EVENT_DATA_STALL_SUSPECTED: {
9899 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009900 final Pair<Long, PersistableBundle> arg =
9901 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009902 if (nai == null) break;
9903
Aaron Huang959d3642021-01-21 15:47:41 +08009904 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009905 break;
9906 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009907 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009908 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009909 break;
9910 }
9911 default: {
9912 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9913 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009914 }
9915 }
9916 }
9917
9918 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9919 @VisibleForTesting
9920 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9921 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9922 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009923 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009924
9925 @VisibleForTesting
9926 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009927 @NonNull IConnectivityDiagnosticsCallback cb,
9928 @NonNull NetworkRequestInfo nri,
9929 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009930 mCb = cb;
9931 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009932 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009933 }
9934
9935 @Override
9936 public void binderDied() {
9937 log("ConnectivityDiagnosticsCallback IBinder died.");
9938 unregisterConnectivityDiagnosticsCallback(mCb);
9939 }
9940 }
9941
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009942 /**
9943 * Class used for sending information from {@link
9944 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9945 */
9946 private static class NetworkTestedResults {
9947 private final int mNetId;
9948 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009949 @Nullable private final String mRedirectUrl;
9950
9951 private NetworkTestedResults(
9952 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9953 mNetId = netId;
9954 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009955 mRedirectUrl = redirectUrl;
9956 }
9957 }
9958
9959 /**
9960 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9961 * ConnectivityDiagnosticsHandler}.
9962 */
9963 private static class ConnectivityReportEvent {
9964 private final long mTimestampMillis;
9965 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009966 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009967
Aaron Huang959d3642021-01-21 15:47:41 +08009968 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9969 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009970 mTimestampMillis = timestampMillis;
9971 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009972 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009973 }
9974 }
9975
Cody Kestingf1120be2020-08-03 18:01:40 -07009976 /**
9977 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9978 * ConnectivityDiagnosticsHandler}.
9979 */
9980 private static class ReportedNetworkConnectivityInfo {
9981 public final boolean hasConnectivity;
9982 public final boolean isNetworkRevalidating;
9983 public final int reporterUid;
9984 @NonNull public final NetworkAgentInfo nai;
9985
9986 private ReportedNetworkConnectivityInfo(
9987 boolean hasConnectivity,
9988 boolean isNetworkRevalidating,
9989 int reporterUid,
9990 @NonNull NetworkAgentInfo nai) {
9991 this.hasConnectivity = hasConnectivity;
9992 this.isNetworkRevalidating = isNetworkRevalidating;
9993 this.reporterUid = reporterUid;
9994 this.nai = nai;
9995 }
9996 }
9997
Cody Kesting73708bf2019-12-18 10:57:50 -08009998 private void handleRegisterConnectivityDiagnosticsCallback(
9999 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10000 ensureRunningOnConnectivityServiceThread();
10001
10002 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010003 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010004 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10005
James Mattis64b8b0f2020-11-24 17:40:49 -080010006 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10007 // confusing for these networks to change when an NRI is satisfied in another layer.
10008 if (nri.isMultilayerRequest()) {
10009 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10010 + "network requests.");
10011 }
10012
Cody Kesting73708bf2019-12-18 10:57:50 -080010013 // This means that the client registered the same callback multiple times. Do
10014 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010015 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010016 if (VDBG) log("Diagnostics callback is already registered");
10017
10018 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10019 // incremented when the NetworkRequestInfo is created as part of
10020 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010021 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010022 return;
10023 }
10024
Cody Kesting31f1ff62020-03-05 10:46:02 -080010025 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010026
10027 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010028 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010029 } catch (RemoteException e) {
10030 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010031 return;
10032 }
10033
10034 // Once registered, provide ConnectivityReports for matching Networks
10035 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10036 synchronized (mNetworkForNetId) {
10037 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10038 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010039 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10040 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010041 matchingNetworks.add(nai);
10042 }
10043 }
10044 }
10045 for (final NetworkAgentInfo nai : matchingNetworks) {
10046 final ConnectivityReport report = nai.getConnectivityReport();
10047 if (report == null) {
10048 continue;
10049 }
10050 if (!checkConnectivityDiagnosticsPermissions(
10051 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10052 continue;
10053 }
10054
10055 try {
10056 cb.onConnectivityReportAvailable(report);
10057 } catch (RemoteException e) {
10058 // Exception while sending the ConnectivityReport. Move on to the next network.
10059 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010060 }
10061 }
10062
10063 private void handleUnregisterConnectivityDiagnosticsCallback(
10064 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10065 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010066 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010067
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010068 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10069 mConnectivityDiagnosticsCallbacks.remove(iCb);
10070 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010071 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10072 return;
10073 }
10074
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010075 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010076
Cody Kesting70fa2b22020-12-02 12:16:56 -080010077 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10078 // (if the Binder died)
10079 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10080 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010081 return;
10082 }
10083
Cody Kesting46cb1672020-03-04 13:35:20 -080010084 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10085 // incremented when the NetworkRequestInfo is created as part of
10086 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010087 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010088
Cody Kesting31f1ff62020-03-05 10:46:02 -080010089 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010090 }
10091
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010092 private void handleNetworkTestedWithExtras(
10093 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10094 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010095 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010096 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010097 final ConnectivityReport report =
10098 new ConnectivityReport(
10099 reportEvent.mNai.network,
10100 reportEvent.mTimestampMillis,
10101 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010102 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010103 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010104 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010105
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010106 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010107 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010108 for (final IConnectivityDiagnosticsCallback cb : results) {
10109 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010110 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010111 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010112 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010113 }
10114 }
10115 }
10116
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010117 private void handleDataStallSuspected(
10118 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10119 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010120 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010121 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010122 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010123 new DataStallReport(
10124 nai.network,
10125 timestampMillis,
10126 detectionMethod,
10127 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010128 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010129 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010130 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010131 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010132 for (final IConnectivityDiagnosticsCallback cb : results) {
10133 try {
10134 cb.onDataStallSuspected(report);
10135 } catch (RemoteException ex) {
10136 loge("Error invoking onDataStallSuspected", ex);
10137 }
10138 }
10139 }
10140
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010141 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010142 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10143 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10144 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10145
10146 // If the Network is being re-validated as a result of this call to
10147 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10148 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010149 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010150 getMatchingPermissionedCallbacks(
10151 nai,
10152 reportedNetworkConnectivityInfo.isNetworkRevalidating
10153 ? Process.INVALID_UID
10154 : reportedNetworkConnectivityInfo.reporterUid);
10155
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010156 for (final IConnectivityDiagnosticsCallback cb : results) {
10157 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010158 cb.onNetworkConnectivityReported(
10159 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010160 } catch (RemoteException ex) {
10161 loge("Error invoking onNetworkConnectivityReported", ex);
10162 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010163
10164 // If the Network isn't re-validating, also provide the cached report. If there is no
10165 // cached report, the Network is still being validated and a report will be sent once
10166 // validation is complete. Note that networks which never undergo validation will still
10167 // have a cached ConnectivityReport with RESULT_SKIPPED.
10168 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10169 try {
10170 cb.onConnectivityReportAvailable(cachedReport);
10171 } catch (RemoteException ex) {
10172 loge("Error invoking onConnectivityReportAvailable", ex);
10173 }
10174 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010175 }
10176 }
10177
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010178 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010179 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10180 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010181 sanitized.setUids(null);
10182 sanitized.setAdministratorUids(new int[0]);
10183 sanitized.setOwnerUid(Process.INVALID_UID);
10184 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010185 }
10186
Cody Kestingf1120be2020-08-03 18:01:40 -070010187 /**
10188 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10189 *
10190 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10191 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010192 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010193 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010194 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010195 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010196 mConnectivityDiagnosticsCallbacks.entrySet()) {
10197 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10198 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010199
James Mattis64b8b0f2020-11-24 17:40:49 -080010200 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010201 if (!nai.satisfies(nri.mRequests.get(0))) {
10202 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010203 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010204
10205 // UID for this callback must either be:
10206 // - INVALID_UID (which sends callbacks to all UIDs), or
10207 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10208 // notified as a result)
10209 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10210 continue;
10211 }
10212
10213 if (!checkConnectivityDiagnosticsPermissions(
10214 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10215 continue;
10216 }
10217
10218 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010219 }
10220 return results;
10221 }
10222
Cody Kesting7474f672021-05-11 14:22:40 -070010223 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10224 @NonNull NetworkAgentInfo nai) {
10225 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10226 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10227 }
10228
Cody Kesting160ef392021-05-05 13:17:22 -070010229 private boolean hasLocationPermission(String packageName, int uid) {
10230 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10231 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10232 // call in a try-catch.
10233 try {
10234 if (!mLocationPermissionChecker.checkLocationPermission(
10235 packageName, null /* featureId */, uid, null /* message */)) {
10236 return false;
10237 }
10238 } catch (SecurityException e) {
10239 return false;
10240 }
10241
10242 return true;
10243 }
10244
10245 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10246 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010247 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010248 && virtual.networkCapabilities.getOwnerUid() == uid
10249 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10250 return true;
10251 }
10252 }
10253
10254 return false;
10255 }
10256
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010257 @VisibleForTesting
10258 boolean checkConnectivityDiagnosticsPermissions(
10259 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10260 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10261 return true;
10262 }
10263
Cody Kesting160ef392021-05-05 13:17:22 -070010264 // Administrator UIDs also contains the Owner UID
10265 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10266 if (!CollectionUtils.contains(administratorUids, callbackUid)
10267 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010268 return false;
10269 }
10270
Cody Kesting7474f672021-05-11 14:22:40 -070010271 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10272 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010273 }
10274
Cody Kestingd199a9d2019-12-17 12:55:28 -080010275 @Override
10276 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010277 @NonNull IConnectivityDiagnosticsCallback callback,
10278 @NonNull NetworkRequest request,
10279 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010280 Objects.requireNonNull(callback, "callback must not be null");
10281 Objects.requireNonNull(request, "request must not be null");
10282 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10283
Cody Kesting73708bf2019-12-18 10:57:50 -080010284 if (request.legacyType != TYPE_NONE) {
10285 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10286 + " Please use NetworkCapabilities instead.");
10287 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010288 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010289 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010290
10291 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10292 // and administrator uids to be safe.
10293 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010294 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010295
10296 final NetworkRequest requestWithId =
10297 new NetworkRequest(
10298 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10299
10300 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10301 //
10302 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10303 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10304 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010305 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010306 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010307 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010308
10309 mConnectivityDiagnosticsHandler.sendMessage(
10310 mConnectivityDiagnosticsHandler.obtainMessage(
10311 ConnectivityDiagnosticsHandler
10312 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10313 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010314 }
10315
10316 @Override
10317 public void unregisterConnectivityDiagnosticsCallback(
10318 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010319 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010320 mConnectivityDiagnosticsHandler.sendMessage(
10321 mConnectivityDiagnosticsHandler.obtainMessage(
10322 ConnectivityDiagnosticsHandler
10323 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010324 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010325 0,
10326 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010327 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010328
10329 @Override
10330 public void simulateDataStall(int detectionMethod, long timestampMillis,
10331 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010332 Objects.requireNonNull(network, "network must not be null");
10333 Objects.requireNonNull(extras, "extras must not be null");
10334
paulhu3ffffe72021-09-16 10:15:22 +080010335 enforceAnyPermissionOf(mContext,
10336 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010337 android.Manifest.permission.NETWORK_STACK);
10338 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10339 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010340 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010341 }
10342
10343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010344 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010345 throw new SecurityException("Data Stall simulation is only possible for network "
10346 + "creators");
10347 }
10348
Cody Kesting652e3ec2020-05-21 12:08:21 -070010349 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10350 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10351 // Data Stall information as a DataStallReportParcelable and passing to
10352 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10353 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010354 final DataStallReportParcelable p = new DataStallReportParcelable();
10355 p.timestampMillis = timestampMillis;
10356 p.detectionMethod = detectionMethod;
10357
10358 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10359 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10360 }
10361 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10362 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10363 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10364 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10365 }
10366
Serik Beketayevec8ad212020-12-07 22:43:07 -080010367 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010368 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010369
lucaslin66f44212021-02-23 01:12:55 +080010370 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10371 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010372 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010373 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010374 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010375 }
lucaslin37a16d92021-01-21 19:48:09 +080010376
10377 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010378 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010379 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010380 nai.clatd.interfaceLinkStateChanged(iface, up);
10381 }
10382 }
10383
10384 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010385 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010386 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010387 nai.clatd.interfaceRemoved(iface);
10388 }
lucaslin66f44212021-02-23 01:12:55 +080010389 }
10390 }
10391
lucaslin1a8b4c62021-01-21 02:02:55 +080010392 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10393
10394 /**
10395 * Class used for updating network activity tracking with netd and notify network activity
10396 * changes.
10397 */
10398 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010399 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010400 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010401 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010402 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10403 new RemoteCallbackList<>();
10404 // Indicate the current system default network activity is active or not.
10405 @GuardedBy("mActiveIdleTimers")
10406 private boolean mNetworkActive;
10407 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010408 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010409 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010410
Chalard Jean46bfbf02022-02-02 00:56:25 +090010411 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010412 public final int timeout;
10413 public final int transportType;
10414
10415 IdleTimerParams(int timeout, int transport) {
10416 this.timeout = timeout;
10417 this.transportType = transport;
10418 }
10419 }
10420
10421 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010422 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010423 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010424 mNetd = netd;
10425 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010426 }
10427
lucaslin66f44212021-02-23 01:12:55 +080010428 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10429 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10430 synchronized (mActiveIdleTimers) {
10431 mNetworkActive = active;
10432 // If there are no idle timers, it means that system is not monitoring
10433 // activity, so the system default network for those default network
10434 // unspecified apps is always considered active.
10435 //
10436 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10437 // any network activity change event. Whenever this event is received,
10438 // the mActiveIdleTimers should be always not empty. The legacy behavior
10439 // is no-op. Remove to refer to mNetworkActive only.
10440 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10441 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10442 }
10443 }
10444 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010445
lucaslin1193a5d2021-01-21 02:04:15 +080010446 // The network activity should only be updated from ConnectivityService handler thread
10447 // when mActiveIdleTimers lock is held.
10448 @GuardedBy("mActiveIdleTimers")
10449 private void reportNetworkActive() {
10450 final int length = mNetworkActivityListeners.beginBroadcast();
10451 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10452 try {
10453 for (int i = 0; i < length; i++) {
10454 try {
10455 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10456 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010457 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010458 }
10459 }
10460 } finally {
10461 mNetworkActivityListeners.finishBroadcast();
10462 }
10463 }
10464
10465 @GuardedBy("mActiveIdleTimers")
10466 public void handleReportNetworkActivity() {
10467 synchronized (mActiveIdleTimers) {
10468 reportNetworkActive();
10469 }
10470 }
10471
lucaslin1a8b4c62021-01-21 02:02:55 +080010472 // This is deprecated and only to support legacy use cases.
10473 private int transportTypeToLegacyType(int type) {
10474 switch (type) {
10475 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010476 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010477 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010478 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010479 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010480 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010481 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010482 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010483 default:
10484 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10485 }
10486 return ConnectivityManager.TYPE_NONE;
10487 }
10488
10489 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10490 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10491 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10492 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10493 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10494 final long ident = Binder.clearCallingIdentity();
10495 try {
10496 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10497 RECEIVE_DATA_ACTIVITY_CHANGE,
10498 null /* resultReceiver */,
10499 null /* scheduler */,
10500 0 /* initialCode */,
10501 null /* initialData */,
10502 null /* initialExtra */);
10503 } finally {
10504 Binder.restoreCallingIdentity(ident);
10505 }
10506 }
10507
10508 /**
10509 * Setup data activity tracking for the given network.
10510 *
10511 * Every {@code setupDataActivityTracking} should be paired with a
10512 * {@link #removeDataActivityTracking} for cleanup.
10513 */
10514 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10515 final String iface = networkAgent.linkProperties.getInterfaceName();
10516
10517 final int timeout;
10518 final int type;
10519
10520 if (networkAgent.networkCapabilities.hasTransport(
10521 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10522 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010523 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010524 10);
10525 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10526 } else if (networkAgent.networkCapabilities.hasTransport(
10527 NetworkCapabilities.TRANSPORT_WIFI)) {
10528 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010529 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010530 15);
10531 type = NetworkCapabilities.TRANSPORT_WIFI;
10532 } else {
10533 return; // do not track any other networks
10534 }
10535
lucaslinb961efc2021-01-21 02:03:17 +080010536 updateRadioPowerState(true /* isActive */, type);
10537
lucaslin1a8b4c62021-01-21 02:02:55 +080010538 if (timeout > 0 && iface != null) {
10539 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010540 synchronized (mActiveIdleTimers) {
10541 // Networks start up.
10542 mNetworkActive = true;
10543 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10544 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10545 reportNetworkActive();
10546 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010547 } catch (Exception e) {
10548 // You shall not crash!
10549 loge("Exception in setupDataActivityTracking " + e);
10550 }
10551 }
10552 }
10553
10554 /**
10555 * Remove data activity tracking when network disconnects.
10556 */
10557 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10558 final String iface = networkAgent.linkProperties.getInterfaceName();
10559 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10560
lucaslinb961efc2021-01-21 02:03:17 +080010561 if (iface == null) return;
10562
10563 final int type;
10564 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10565 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10566 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10567 type = NetworkCapabilities.TRANSPORT_WIFI;
10568 } else {
10569 return; // do not track any other networks
10570 }
10571
10572 try {
10573 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010574 synchronized (mActiveIdleTimers) {
10575 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10576 // The call fails silently if no idle timer setup for this interface
10577 mNetd.idletimerRemoveInterface(iface, params.timeout,
10578 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010579 }
lucaslinb961efc2021-01-21 02:03:17 +080010580 } catch (Exception e) {
10581 // You shall not crash!
10582 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010583 }
10584 }
10585
10586 /**
10587 * Update data activity tracking when network state is updated.
10588 */
10589 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10590 NetworkAgentInfo oldNetwork) {
10591 if (newNetwork != null) {
10592 setupDataActivityTracking(newNetwork);
10593 }
10594 if (oldNetwork != null) {
10595 removeDataActivityTracking(oldNetwork);
10596 }
10597 }
lucaslinb961efc2021-01-21 02:03:17 +080010598
10599 private void updateRadioPowerState(boolean isActive, int transportType) {
10600 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10601 switch (transportType) {
10602 case NetworkCapabilities.TRANSPORT_CELLULAR:
10603 bs.reportMobileRadioPowerState(isActive, NO_UID);
10604 break;
10605 case NetworkCapabilities.TRANSPORT_WIFI:
10606 bs.reportWifiRadioPowerState(isActive, NO_UID);
10607 break;
10608 default:
10609 logw("Untracked transport type:" + transportType);
10610 }
10611 }
lucaslin1193a5d2021-01-21 02:04:15 +080010612
10613 public boolean isDefaultNetworkActive() {
10614 synchronized (mActiveIdleTimers) {
10615 // If there are no idle timers, it means that system is not monitoring activity,
10616 // so the default network is always considered active.
10617 //
10618 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10619 // tracking is disabled (negative idle timer value configured), or no active default
10620 // network. In the latter case, this reports active but it should report inactive.
10621 return mNetworkActive || mActiveIdleTimers.isEmpty();
10622 }
10623 }
10624
10625 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10626 mNetworkActivityListeners.register(l);
10627 }
10628
10629 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10630 mNetworkActivityListeners.unregister(l);
10631 }
lucaslin012f7a12021-01-21 02:04:35 +080010632
10633 public void dump(IndentingPrintWriter pw) {
10634 synchronized (mActiveIdleTimers) {
10635 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10636 pw.println("Idle timers:");
10637 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10638 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10639 final IdleTimerParams params = ent.getValue();
10640 pw.print(" timeout="); pw.print(params.timeout);
10641 pw.print(" type="); pw.println(params.transportType);
10642 }
10643 }
10644 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010645 }
James Mattis47db0582021-01-01 14:13:35 -080010646
Daniel Brightf9e945b2020-06-15 16:10:01 -070010647 /**
10648 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10649 *
10650 * @param socketInfo the socket information
10651 * @param callback the callback to register
10652 */
10653 @Override
10654 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10655 @NonNull final IQosCallback callback) {
10656 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10657 if (nai == null || nai.networkCapabilities == null) {
10658 try {
10659 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10660 } catch (final RemoteException ex) {
10661 loge("registerQosCallbackInternal: RemoteException", ex);
10662 }
10663 return;
10664 }
10665 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10666 }
10667
10668 /**
10669 * Register a {@link IQosCallback} with base {@link QosFilter}.
10670 *
10671 * @param filter the filter to register
10672 * @param callback the callback to register
10673 * @param nai the agent information related to the filter's network
10674 */
10675 @VisibleForTesting
10676 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10677 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010678 Objects.requireNonNull(filter, "filter must be non-null");
10679 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010680
10681 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010682 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10683 // on this network is unregistered when the app loses permission or b) no QoS
10684 // callbacks are sent for restricted networks unless the app currently has permission
10685 // to access restricted networks.
10686 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010687 }
10688 mQosCallbackTracker.registerCallback(callback, filter, nai);
10689 }
10690
10691 /**
10692 * Unregisters the given callback.
10693 *
10694 * @param callback the callback to unregister
10695 */
10696 @Override
10697 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010698 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010699 mQosCallbackTracker.unregisterCallback(callback);
10700 }
James Mattis47db0582021-01-01 14:13:35 -080010701
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010702 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10703 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10704 // Enterprise device can be fully managed like device owner and such use case
10705 // also should be supported. Calling app check for work profile and fully managed device
10706 // is already done in DevicePolicyManager.
10707 // This check is an extra caution to be sure device is fully managed or not.
10708 final UserManager um = mContext.getSystemService(UserManager.class);
10709 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10710 if (um.isManagedProfile(profile.getIdentifier())) {
10711 return true;
10712 }
10713 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10714 return false;
10715 }
10716
James Mattis45d81842021-01-10 14:24:24 -080010717 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010718 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010719 *
10720 * See the documentation for the individual preferences for a description of the supported
10721 * behaviors.
10722 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010723 * @param profile If the device owner is set, any profile is allowed.
10724 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010725 * @param preferences the list of profile network preferences for the
10726 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010727 * @param listener an optional listener to listen for completion of the operation.
10728 */
10729 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010730 public void setProfileNetworkPreferences(
10731 @NonNull final UserHandle profile,
10732 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010733 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010734 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010735 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010736
10737 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010738 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10739 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10740 .build();
10741 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010742 }
10743
paulhu3ffffe72021-09-16 10:15:22 +080010744 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010745 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010746 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010747 }
10748 if (profile.getIdentifier() < 0) {
10749 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10750 + "UserHandle.CURRENT not supported)");
10751 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010752 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10753 throw new IllegalArgumentException("Profile must be a managed profile "
10754 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010755 }
paulhuaa0743d2021-05-26 21:56:03 +080010756
Chalard Jean46bfbf02022-02-02 00:56:25 +090010757 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010758 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010759 for (final ProfileNetworkPreference preference : preferences) {
10760 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010761 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010762 switch (preference.getPreference()) {
10763 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10764 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010765 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010766 if (preference.getPreferenceEnterpriseId() != 0) {
10767 throw new IllegalArgumentException(
10768 "Invalid enterprise identifier in setProfileNetworkPreferences");
10769 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010770 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010771 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10772 allowFallback = false;
10773 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010774 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010775 // This code is needed even though there is a check later on,
10776 // because isRangeAlreadyInPreferenceList assumes that every preference
10777 // has a UID list.
10778 if (hasDefaultPreference) {
10779 throw new IllegalArgumentException(
10780 "Default profile preference should not be set along with other "
10781 + "preference");
10782 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010783 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10784 throw new IllegalArgumentException(
10785 "Invalid enterprise identifier in setProfileNetworkPreferences");
10786 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010787 final Set<UidRange> uidRangeSet =
10788 getUidListToBeAppliedForNetworkPreference(profile, preference);
10789 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10790 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10791 } else {
10792 throw new IllegalArgumentException(
10793 "Overlapping uid range in setProfileNetworkPreferences");
10794 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010795 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010796 nc.addEnterpriseId(
10797 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010798 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10799 break;
10800 default:
10801 throw new IllegalArgumentException(
10802 "Invalid preference in setProfileNetworkPreferences");
10803 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010804 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10805 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010806 if (hasDefaultPreference && preferenceList.size() > 1) {
10807 throw new IllegalArgumentException(
10808 "Default profile preference should not be set along with other preference");
10809 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010810 }
10811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010812 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010813 }
10814
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010815 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10816 @NonNull final UserHandle profile,
10817 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10818 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010819 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10820 profileNetworkPreference.getIncludedUids());
10821
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010822 if (uidRangeSet.size() > 0) {
10823 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10824 throw new IllegalArgumentException(
10825 "Allow uid range is outside the uid range of profile.");
10826 }
10827 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010828 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010829 profileNetworkPreference.getExcludedUids());
10830 if (disallowUidRangeSet.size() > 0) {
10831 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10832 throw new IllegalArgumentException(
10833 "disallow uid range is outside the uid range of profile.");
10834 }
10835 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10836 disallowUidRangeSet);
10837 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010838 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010839 uidRangeSet.add(profileUids);
10840 }
10841 }
10842 return uidRangeSet;
10843 }
10844
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010845 private boolean isEnterpriseIdentifierValid(
10846 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010847 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010848 return true;
10849 }
10850 return false;
10851 }
10852
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010853 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010854 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010855 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010856 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010857 // The NRI for a user should contain the request for capabilities.
10858 // If fallback to default network is needed then NRI should include
10859 // the request for the default network. Create an image of it to
10860 // have the correct UIDs in it (also a request can only be part of one NRI, because
10861 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010862 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10863 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010864 if (pref.allowFallback) {
10865 nrs.add(createDefaultInternetRequestForTransport(
10866 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10867 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010868 if (VDBG) {
10869 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10870 pref.capabilities.getUids()));
10871 }
10872
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010873 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010874 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010875 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010876 result.add(nri);
10877 }
10878 return result;
10879 }
10880
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010881 /**
10882 * Compare if the given UID range sets have the same UIDs.
10883 *
10884 */
10885 private boolean isRangeAlreadyInPreferenceList(
10886 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10887 @NonNull Set<UidRange> uidRangeSet) {
10888 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10889 return false;
10890 }
10891 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10892 if (UidRangeUtils.doesRangeSetOverlap(
10893 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10894 return true;
10895 }
10896 }
10897 return false;
10898 }
10899
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010900 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010901 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010902 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010903 /*
10904 * handleSetProfileNetworkPreference is always called for single user.
10905 * preferenceList only contains preferences for different uids within the same user
10906 * (enforced by getUidListToBeAppliedForNetworkPreference).
10907 * Clear all the existing preferences for the user before applying new preferences.
10908 *
10909 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010910 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010911 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010912 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010913 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10914 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010915
paulhu74128522021-09-28 02:29:03 +000010916 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10917 addPerAppDefaultNetworkRequests(
10918 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010919
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010920 // Finally, rematch.
10921 rematchAllNetworksAndRequests();
10922
10923 if (null != listener) {
10924 try {
10925 listener.onComplete();
10926 } catch (RemoteException e) {
10927 loge("Listener for setProfileNetworkPreference has died");
10928 }
10929 }
10930 }
10931
paulhu51f77dc2021-06-07 02:34:20 +000010932 @VisibleForTesting
10933 @NonNull
10934 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10935 @NonNull final Set<Integer> uids) {
10936 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10937 if (uids.size() == 0) {
10938 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10939 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10940 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10941 return nris;
10942 }
10943
10944 final List<NetworkRequest> requests = new ArrayList<>();
10945 // The NRI should be comprised of two layers:
10946 // - The request for the mobile network preferred.
10947 // - The request for the default network, for fallback.
10948 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010949 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010950 requests.add(createDefaultInternetRequestForTransport(
10951 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10952 final Set<UidRange> ranges = new ArraySet<>();
10953 for (final int uid : uids) {
10954 ranges.add(new UidRange(uid, uid));
10955 }
10956 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010957 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010958 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010959 return nris;
10960 }
10961
10962 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010963 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010964 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10965 addPerAppDefaultNetworkRequests(
10966 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010967 // Finally, rematch.
10968 rematchAllNetworksAndRequests();
10969 }
10970
Patrick Rohr2857ac42022-01-21 14:58:16 +010010971 private void handleIngressRateLimitChanged() {
10972 final long oldIngressRateLimit = mIngressRateLimit;
10973 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10974 mContext);
10975 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10976 if (canNetworkBeRateLimited(networkAgent)) {
10977 // If rate limit has previously been enabled, remove the old limit first.
10978 if (oldIngressRateLimit >= 0) {
10979 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10980 }
10981 if (mIngressRateLimit >= 0) {
10982 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10983 mIngressRateLimit);
10984 }
10985 }
10986 }
10987 }
10988
10989 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010990 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10991 if (!SdkLevel.isAtLeastT()) return false;
10992
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010993 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10994 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10995 // internet connectivity can be rate limited.
10996 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10997 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010998 return false;
10999 }
11000
11001 final String iface = networkAgent.linkProperties.getInterfaceName();
11002 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011003 // This may happen in tests, but if there is no interface then there is nothing that
11004 // can be rate limited.
11005 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011006 return false;
11007 }
11008 return true;
11009 }
11010
James Mattis45d81842021-01-10 14:24:24 -080011011 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011012 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11013 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011014 }
11015
11016 /**
11017 * Used by automotive devices to set the network preferences used to direct traffic at an
11018 * application level as per the given OemNetworkPreferences. An example use-case would be an
11019 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11020 * vehicle via a particular network.
11021 *
11022 * Calling this will overwrite the existing preference.
11023 *
James Mattisda32cfe2021-01-26 16:23:52 -080011024 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011025 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011026 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011027 */
James Mattis47db0582021-01-01 14:13:35 -080011028 @Override
James Mattis45d81842021-01-10 14:24:24 -080011029 public void setOemNetworkPreference(
11030 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011031 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011032
James Mattisfa270db2021-05-31 17:11:10 -070011033 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11034 // Only bypass the permission/device checks if this is a valid test request.
11035 if (isValidTestOemNetworkPreference(preference)) {
11036 enforceManageTestNetworksPermission();
11037 } else {
11038 enforceAutomotiveDevice();
11039 enforceOemNetworkPreferencesPermission();
11040 validateOemNetworkPreferences(preference);
11041 }
James Mattis45d81842021-01-10 14:24:24 -080011042
James Mattis45d81842021-01-10 14:24:24 -080011043 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11044 new Pair<>(preference, listener)));
11045 }
11046
James Mattisfa270db2021-05-31 17:11:10 -070011047 /**
11048 * Check the validity of an OEM network preference to be used for testing purposes.
11049 * @param preference the preference to validate
11050 * @return true if this is a valid OEM network preference test request.
11051 */
11052 private boolean isValidTestOemNetworkPreference(
11053 @NonNull final OemNetworkPreferences preference) {
11054 // Allow for clearing of an existing OemNetworkPreference used for testing.
11055 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11056 // changes after this check is complete. This is an unlikely scenario as calling of this API
11057 // is controlled by the OEM therefore the added complexity is not worth adding given those
11058 // circumstances. That said, it is an edge case to be aware of hence this comment.
11059 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11060 && isTestOemNetworkPreference(mOemNetworkPreferences);
11061 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11062 }
11063
11064 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11065 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11066 return prefMap.size() == 1
11067 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11068 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11069 }
11070
James Mattis45d81842021-01-10 14:24:24 -080011071 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11072 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11073 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011074 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11075 throw new IllegalArgumentException(
11076 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11077 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011078 }
11079 }
11080 }
11081
11082 private void handleSetOemNetworkPreference(
11083 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011084 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011085 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11086 if (DBG) {
11087 log("set OEM network preferences :" + preference.toString());
11088 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011089
James Mattiscb1e0362021-04-06 17:07:42 -070011090 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011091 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11092 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11093 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011094 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011095
11096 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011097 try {
11098 listener.onComplete();
11099 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011100 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011101 }
James Mattis45d81842021-01-10 14:24:24 -080011102 }
11103 }
11104
paulhu74128522021-09-28 02:29:03 +000011105 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011106 // Skip the requests which are set by other network preference. Because the uid range rules
11107 // should stay in netd.
11108 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011109 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011110 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011111 }
11112
James Mattis3ce3d3c2021-02-09 18:18:28 -080011113 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11114 ensureRunningOnConnectivityServiceThread();
11115 mDefaultNetworkRequests.addAll(nris);
11116 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11117 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011118 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011119 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11120 nrisToRegister.addAll(
11121 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11122 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011123 }
11124
11125 /**
11126 * All current requests that are tracking the default network need to be assessed as to whether
11127 * or not the current set of per-application default requests will be changing their default
11128 * network. If so, those requests will need to be updated so that they will send callbacks for
11129 * default network changes at the appropriate time. Additionally, those requests tracking the
11130 * default that were previously updated by this flow will need to be reassessed.
11131 * @return the nris which will need to be updated.
11132 */
11133 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11134 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11135 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11136 // same nri in the map's values for each of its NetworkRequest objects.
11137 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011138 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011139 // Include this nri if it is currently being tracked.
11140 if (isPerAppTrackedNri(nri)) {
11141 defaultCallbackRequests.add(nri);
11142 continue;
11143 }
11144 // We only track callbacks for requests tracking the default.
11145 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11146 continue;
11147 }
11148 // Include this nri if it will be tracked by the new per-app default requests.
11149 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011150 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011151 if (isNriGoingToBeTracked) {
11152 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011153 }
11154 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011155 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011156 }
11157
James Mattis3ce3d3c2021-02-09 18:18:28 -080011158 /**
11159 * Create nris for those network requests that are currently tracking the default network that
11160 * are being controlled by a per-application default.
11161 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11162 * foundation when creating the nri. Important items include the calling uid's original
11163 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11164 * requests are assumed to have already been validated as needing to be updated.
11165 * @return the Set of nris to use when registering network requests.
11166 */
11167 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11168 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11169 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11170 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11171 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011172 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011173
Chalard Jean9473c982021-07-29 20:03:04 +090011174 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011175 if (trackingNri == mDefaultRequest) {
11176 callbackRequestsToRegister.add(new NetworkRequestInfo(
11177 callbackRequest,
11178 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11179 continue;
11180 }
11181
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011182 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011183 callbackRequestsToRegister.add(new NetworkRequestInfo(
11184 callbackRequest,
11185 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011186 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011187 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011188 }
11189 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011190 }
11191
Chalard Jean17215832021-03-01 14:06:28 +090011192 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11193 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011194 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011195 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011196 }
11197 }
11198
James Mattis45d81842021-01-10 14:24:24 -080011199 /**
11200 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11201 */
11202 @VisibleForTesting
11203 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011204 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011205 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011206 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011207 final SparseArray<Set<Integer>> uids =
11208 createUidsFromOemNetworkPreferences(preference);
11209 for (int i = 0; i < uids.size(); i++) {
11210 final int key = uids.keyAt(i);
11211 final Set<Integer> value = uids.valueAt(i);
11212 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11213 // No need to add an nri without any requests.
11214 if (0 == nri.mRequests.size()) {
11215 continue;
11216 }
11217 nris.add(nri);
11218 }
11219
11220 return nris;
11221 }
11222
11223 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11224 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011225 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011226 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011227 final List<UserHandle> users =
11228 mContext.getSystemService(UserManager.class).getUserHandles(true);
11229 if (null == users || users.size() == 0) {
11230 if (VDBG || DDBG) {
11231 log("No users currently available for setting the OEM network preference.");
11232 }
James Mattisb6b6a432021-06-01 22:30:36 -070011233 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011234 }
James Mattis45d81842021-01-10 14:24:24 -080011235 for (final Map.Entry<String, Integer> entry :
11236 preference.getNetworkPreferences().entrySet()) {
11237 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011238 // Add the rules for all users as this policy is device wide.
11239 for (final UserHandle user : users) {
11240 try {
11241 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11242 if (!prefToUids.contains(pref)) {
11243 prefToUids.put(pref, new ArraySet<>());
11244 }
11245 prefToUids.get(pref).add(uid);
11246 } catch (PackageManager.NameNotFoundException e) {
11247 // Although this may seem like an error scenario, it is ok that uninstalled
11248 // packages are sent on a network preference as the system will watch for
11249 // package installations associated with this network preference and update
11250 // accordingly. This is done to minimize race conditions on app install.
11251 continue;
James Mattis45d81842021-01-10 14:24:24 -080011252 }
James Mattis45d81842021-01-10 14:24:24 -080011253 }
11254 }
James Mattisb6b6a432021-06-01 22:30:36 -070011255 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011256 }
11257
11258 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11259 @OemNetworkPreferences.OemNetworkPreference final int preference,
11260 @NonNull final Set<Integer> uids) {
11261 final List<NetworkRequest> requests = new ArrayList<>();
11262 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11263 switch (preference) {
11264 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11265 requests.add(createUnmeteredNetworkRequest());
11266 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011267 requests.add(createDefaultInternetRequestForTransport(
11268 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011269 break;
11270 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11271 requests.add(createUnmeteredNetworkRequest());
11272 requests.add(createOemPaidNetworkRequest());
11273 break;
11274 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11275 requests.add(createOemPaidNetworkRequest());
11276 break;
11277 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11278 requests.add(createOemPrivateNetworkRequest());
11279 break;
James Mattisfa270db2021-05-31 17:11:10 -070011280 case OEM_NETWORK_PREFERENCE_TEST:
11281 requests.add(createUnmeteredNetworkRequest());
11282 requests.add(createTestNetworkRequest());
11283 requests.add(createDefaultRequest());
11284 break;
11285 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11286 requests.add(createTestNetworkRequest());
11287 break;
James Mattis45d81842021-01-10 14:24:24 -080011288 default:
11289 // This should never happen.
11290 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11291 + " called with invalid preference of " + preference);
11292 }
11293
James Mattisfa270db2021-05-31 17:11:10 -070011294 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011295 for (final int uid : uids) {
11296 ranges.add(new UidRange(uid, uid));
11297 }
11298 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011299 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011300 }
11301
11302 private NetworkRequest createUnmeteredNetworkRequest() {
11303 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11304 .addCapability(NET_CAPABILITY_NOT_METERED)
11305 .addCapability(NET_CAPABILITY_VALIDATED);
11306 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11307 }
11308
11309 private NetworkRequest createOemPaidNetworkRequest() {
11310 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11311 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11312 .addCapability(NET_CAPABILITY_OEM_PAID)
11313 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11314 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11315 }
11316
11317 private NetworkRequest createOemPrivateNetworkRequest() {
11318 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11319 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11320 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11321 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11322 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11323 }
11324
11325 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011326 final NetworkCapabilities netcap = new NetworkCapabilities();
11327 netcap.addCapability(NET_CAPABILITY_INTERNET);
11328 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11329 return netcap;
11330 }
11331
11332 private NetworkRequest createTestNetworkRequest() {
11333 final NetworkCapabilities netcap = new NetworkCapabilities();
11334 netcap.clearAll();
11335 netcap.addTransportType(TRANSPORT_TEST);
11336 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011337 }
James Mattis47db0582021-01-01 14:13:35 -080011338 }
markchien738ad912021-12-09 18:15:45 +080011339
11340 @Override
11341 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11342 enforceNetworkStackOrSettingsPermission();
11343
11344 try {
11345 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011346 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011347 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011348 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011349 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011350 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011351 throw new IllegalStateException(e);
11352 }
11353 }
11354
11355 @Override
11356 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11357 enforceNetworkStackOrSettingsPermission();
11358
11359 try {
11360 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011361 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011362 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011363 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011364 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011365 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011366 throw new IllegalStateException(e);
11367 }
11368 }
markchiene1561fa2021-12-09 22:00:56 +080011369
11370 @Override
markchien3c04e662022-03-22 16:29:56 +080011371 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011372 enforceNetworkStackOrSettingsPermission();
11373
markchien3c04e662022-03-22 16:29:56 +080011374 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11375 int firewallRule = getFirewallRuleType(chain, rule);
11376
11377 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11378 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11379 }
11380
markchiene1561fa2021-12-09 22:00:56 +080011381 try {
markchien3c04e662022-03-22 16:29:56 +080011382 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011383 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011384 throw new IllegalStateException(e);
11385 }
11386 }
markchien98a6f952022-01-13 23:43:53 +080011387
markchien3c04e662022-03-22 16:29:56 +080011388 private int getFirewallRuleType(int chain, int rule) {
11389 final int defaultRule;
11390 switch (chain) {
11391 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011392 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11393 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011394 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011395 defaultRule = FIREWALL_RULE_ALLOW;
11396 break;
11397 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11398 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11399 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11400 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11401 defaultRule = FIREWALL_RULE_DENY;
11402 break;
11403 default:
11404 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11405 }
11406 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11407
11408 return rule;
11409 }
11410
markchien98a6f952022-01-13 23:43:53 +080011411 @Override
11412 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11413 enforceNetworkStackOrSettingsPermission();
11414
11415 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011416 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011417 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011418 throw new IllegalStateException(e);
11419 }
11420 }
11421
markchien00a0bed2022-01-13 23:46:13 +080011422 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011423 public boolean getFirewallChainEnabled(final int chain) {
11424 enforceNetworkStackOrSettingsPermission();
11425
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011426 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011427 }
11428
11429 @Override
markchien00a0bed2022-01-13 23:46:13 +080011430 public void replaceFirewallChain(final int chain, final int[] uids) {
11431 enforceNetworkStackOrSettingsPermission();
11432
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011433 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011434 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011435}