blob: e3e12fd6b2c4be63e6bf5ee293103f67fc638d95 [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;
Paul Hu3c8c8102022-08-25 07:06:16 +0000213import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700215import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217import android.os.Looper;
218import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700219import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700220import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900221import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800222import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700223import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700224import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800225import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900227import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900228import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700229import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700230import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400231import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900233import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700234import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700235import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700236import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800237import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900238import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000239import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600240import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900241import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700242import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700243import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800244
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900245import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400246import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400247import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700248import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900249import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800250import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900251import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800252import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000253import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900254import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900255import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900256import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100257import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900258import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
259import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900260import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800261import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800262import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100263import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000264import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900265import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800266import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800267import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900268import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900269import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500270import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700271import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900272import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900273import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100274import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700275import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900276import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700277import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600278import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900279import com.android.server.connectivity.NetworkNotificationManager;
280import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900281import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900282import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900283import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700284import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900285import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900286import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700287import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800288import com.android.server.connectivity.UidRangeUtils;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800289import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600290
Josh Gao461a1222020-06-16 15:58:11 -0700291import libcore.io.IoUtils;
292
The Android Open Source Project28527d22009-03-03 19:31:44 -0800293import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100294import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800295import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900296import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700297import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700298import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900299import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700300import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700301import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700302import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700303import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800304import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900305import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800306import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700307import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700308import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700309import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700310import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900311import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700312import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900313import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600314import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900315import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600316import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900317import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800318
319/**
320 * @hide
321 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800322public class ConnectivityService extends IConnectivityManager.Stub
323 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900324 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800325
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900326 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900327 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900328 private static final String NETWORK_ARG = "networks";
329 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800330 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900331
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900332 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900333 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
334 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900336 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700337
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100338 /**
339 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
340 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800341 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100342 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
343 * (preferably via runtime resource overlays).
344 */
345 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
346 "http://connectivitycheck.gstatic.com/generate_204";
347
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700348 // TODO: create better separation between radio types and network types
349
Robert Greenwalt2034b912009-08-12 16:08:25 -0700350 // how long to wait before switching back to a radio's default network
351 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
352 // system property that can override the above value
353 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
354 "android.telephony.apn-restore";
355
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900356 // How long to wait before putting up a "This network doesn't have an Internet connection,
357 // connect anyway?" dialog after the user selects a network that doesn't validate.
358 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
359
Chalard Jean5fb43c72022-09-08 19:03:14 +0900360 // How long to wait before considering that a network is bad in the absence of any form
361 // of connectivity (valid, partial, captive portal). If none has been detected after this
362 // delay, the stack considers this network bad, which may affect how it's handled in ranking
363 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900364 // Timeout in case the "actively prefer bad wifi" feature is on
365 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
366 // Timeout in case the "actively prefer bad wifi" feature is off
367 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900368
junyulai0ac374f2020-12-14 18:41:52 +0800369 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900370 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
371 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800372 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700373
he_won.hwang881307a2022-03-15 21:23:52 +0900374 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900375 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900376
Daniel Brightf9e945b2020-06-15 16:10:01 -0700377 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900378 @VisibleForTesting
379 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700380
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900381 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700382 @VisibleForTesting
383 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900384
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900385 @VisibleForTesting
386 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800387 @VisibleForTesting
388 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900389 // True if the cell radio of the device is capable of time-sharing.
390 @VisibleForTesting
391 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900392
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800393 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800394 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800395 private final int mReleasePendingIntentDelayMs;
396
Chalard Jean46bfbf02022-02-02 00:56:25 +0900397 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900398
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000399 @VisibleForTesting
400 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700401
Chalard Jean9473c982021-07-29 20:03:04 +0900402 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800403 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700404 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800405 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700406
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900407 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700408
junyulaif2c67e42018-08-07 19:50:45 +0800409 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000410 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
411 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800412 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900413 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800414
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900415 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900416 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000417 // The Context is created for UserHandle.ALL.
418 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900419 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900420 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700421 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700422 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800423
Chenbo Feng15416292018-11-08 17:36:21 -0800424 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800425 protected IDnsResolver mDnsResolver;
426 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800427 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700428 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900429 private final NetworkStatsManager mStatsManager;
430 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800431 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700432
Benedict Wong493e04b2018-11-09 14:45:34 -0800433 /**
434 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
435 * instances.
436 */
437 @GuardedBy("mTNSLock")
438 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800439 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800440
441 private final Object mTNSLock = new Object();
442
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700443 private String mCurrentTcpBufferSizes;
444
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900445 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800446 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900447
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500448 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400449 // Tear down networks that have no chance (e.g. even if validated) of becoming
450 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500451 // all networks have been rematched against all NetworkRequests.
452 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400453 // Don't reap networks. This should be passed when some networks have not yet been
454 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500455 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900456 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500457
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900458 private enum UnneededFor {
459 LINGER, // Determine whether this network is unneeded and should be lingered.
460 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
461 }
462
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700463 /**
paulhuaa0743d2021-05-26 21:56:03 +0800464 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800465 * should have priority. The order is passed to netd which will use it together
466 * with UID ranges to generate the corresponding IP rule. This serves to
467 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800468 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800469 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000470 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800471 *
paulhu48291862021-07-14 14:53:57 +0800472 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
473 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800474 */
paulhu48291862021-07-14 14:53:57 +0800475 // Used when sending to netd to code for "no order".
476 static final int PREFERENCE_ORDER_NONE = 0;
477 // Order for requests that don't code for a per-app preference. As it is
478 // out of the valid range, the corresponding order should be
479 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800480 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800481 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800482 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800483 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
484 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800485 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800486 static final int PREFERENCE_ORDER_OEM = 10;
487 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800488 // See {@link #setProfileNetworkPreference}.
489 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800490 static final int PREFERENCE_ORDER_PROFILE = 20;
491 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800492 // better scores are connected.
493 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800494 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800495 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900496 // Preference order that signifies the network shouldn't be set as a default network for
497 // the UIDs, only give them access to it. TODO : replace this with a boolean
498 // in NativeUidRangeConfig
499 @VisibleForTesting
500 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
501 // Bound for the lowest valid preference order.
502 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800503
504 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700505 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700506 * from one net to another. Clear happens when we get a new
507 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
508 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700509 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700510 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700511
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700512 /**
513 * used internally to reload global proxy settings
514 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700515 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700516
Robert Greenwalt34848c02011-03-25 13:09:25 -0700517 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400518 * PAC manager has received new port.
519 */
520 private static final int EVENT_PROXY_HAS_CHANGED = 16;
521
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700522 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900523 * used internally when registering NetworkProviders
524 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700525 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900526 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700527
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700528 /**
529 * used internally when registering NetworkAgents
530 * obj = Messenger
531 */
532 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
533
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700534 /**
535 * used to add a network request
536 * includes a NetworkRequestInfo
537 */
538 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
539
540 /**
541 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900542 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700543 * cancel it.
544 * includes a NetworkRequestInfo
545 */
546 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
547
548 /**
549 * used to add a network listener - no request
550 * includes a NetworkRequestInfo
551 */
552 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
553
554 /**
555 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400556 * arg1 = UID of caller
557 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700558 */
559 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
560
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700561 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900562 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700563 * obj = Messenger
564 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900565 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700566
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700567 /**
568 * used internally to expire a wakelock when transitioning
569 * from one net to another. Expire happens when we fail to find
570 * a new network (typically after 1 minute) -
571 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
572 * a replacement network.
573 */
574 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
575
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700576 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800577 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400578 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800579 */
580 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
581
582 /**
583 * used to remove a pending intent and its associated network request.
584 * arg1 = UID of caller
585 * obj = PendingIntent
586 */
587 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
588
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900589 /**
590 * used to specify whether a network should be used even if unvalidated.
591 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
592 * arg2 = whether to remember this choice in the future (1 or 0)
593 * obj = network
594 */
595 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
596
597 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700598 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900599 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700600 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900601
Paul Jensenc8873fc2015-06-17 14:15:39 -0400602 /**
603 * used to add a network listener with a pending intent
604 * obj = NetworkRequestInfo
605 */
606 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
607
Hugo Benichid6b510a2017-04-06 17:22:18 +0900608 /**
609 * used to specify whether a network should not be penalized when it becomes unvalidated.
610 */
611 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
612
613 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700614 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900615 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700616 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900617
Erik Kline31b4a9e2018-01-11 21:07:29 +0900618 // Handle changes in Private DNS settings.
619 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
620
dalyk1720e542018-03-05 12:42:22 -0500621 // Handle private DNS validation status updates.
622 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
623
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900624 /**
625 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
626 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800627 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
628 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
629 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900630 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900631 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900632
633 /**
634 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
635 * config was resolved.
636 * obj = PrivateDnsConfig
637 * arg2 = netid
638 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900639 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900640
641 /**
642 * Request ConnectivityService display provisioning notification.
643 * arg1 = Whether to make the notification visible.
644 * arg2 = NetID.
645 * obj = Intent to be launched when notification selected by user, null if !arg1.
646 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900647 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900648
649 /**
lucaslin2240ef62019-03-12 13:08:03 +0800650 * Used to specify whether a network should be used even if connectivity is partial.
651 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
652 * false)
653 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
654 * obj = network
655 */
lucaslin444d43a2020-02-20 16:56:59 +0800656 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800657
658 /**
lucasline117e2e2019-10-22 18:27:33 +0800659 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
660 * Both of the arguments are bitmasks, and the value of bits come from
661 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900662 * arg1 = unused
663 * arg2 = netId
664 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800665 */
lucaslin444d43a2020-02-20 16:56:59 +0800666 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800667
668 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900669 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
670 * arg1 = unused
671 * arg2 = netId
672 * obj = captive portal data
673 */
lucaslin444d43a2020-02-20 16:56:59 +0800674 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900675
676 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900677 * Used by setRequireVpnForUids.
678 * arg1 = whether the specified UID ranges are required to use a VPN.
679 * obj = Array of UidRange objects.
680 */
681 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
682
683 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900684 * Used internally when setting the default networks for OemNetworkPreferences.
685 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800686 */
687 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
688
689 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800690 * Used to indicate the system default network becomes active.
691 */
692 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
693
694 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900695 * Used internally when setting a network preference for a user profile.
696 * obj = Pair<ProfileNetworkPreference, Listener>
697 */
698 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
699
700 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000701 * Event to specify that reasons for why an uid is blocked changed.
702 * arg1 = uid
703 * arg2 = blockedReasons
704 */
705 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
706
707 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900708 * Event to register a new network offer
709 * obj = NetworkOffer
710 */
711 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
712
713 /**
714 * Event to unregister an existing network offer
715 * obj = INetworkOfferCallback
716 */
717 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
718
719 /**
paulhu51f77dc2021-06-07 02:34:20 +0000720 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
721 */
722 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
723
724 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800725 * Event to set temporary allow bad wifi within a limited time to override
726 * {@code config_networkAvoidBadWifi}.
727 */
728 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
729
730 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100731 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
732 */
733 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
734
735 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900736 * The initial evaluation period is over for this network.
737 *
738 * If no form of connectivity has been found on this network (valid, partial, captive portal)
739 * then the stack will now consider it to have been determined bad.
740 */
741 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
742
743 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000744 * Used internally when the user does not want the network from captive portal app.
745 * obj = Network
746 */
747 private static final int EVENT_USER_DOES_NOT_WANT = 58;
748
749 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900750 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
751 * should be shown.
752 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900753 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900754
755 /**
756 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
757 * should be hidden.
758 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900759 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900760
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800761 /**
762 * The maximum alive time to allow bad wifi configuration for testing.
763 */
764 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
765
Patrick Rohr2857ac42022-01-21 14:58:16 +0100766 /**
767 * The priority of the tc police rate limiter -- smaller value is higher priority.
768 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
769 */
770 private static final short TC_PRIO_POLICE = 1;
771
772 /**
773 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
774 */
775 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700776 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100777
Hugo Benichi47011212017-03-30 10:46:05 +0900778 private static String eventName(int what) {
779 return sMagicDecoderRing.get(what, Integer.toString(what));
780 }
781
paulhua10d8212020-11-10 15:32:56 +0800782 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900783 final DnsResolverServiceManager dsm = context.getSystemService(
784 DnsResolverServiceManager.class);
785 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800786 }
787
Cody Kesting73708bf2019-12-18 10:57:50 -0800788 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900789 @VisibleForTesting
790 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700791 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700792 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700793 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700794 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800795 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
796 @VisibleForTesting
797 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
798
Erik Kline32120082017-12-13 19:40:49 +0900799 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900800 @VisibleForTesting
801 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700802
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400803 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800804 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400805
Chalard Jean46bfbf02022-02-02 00:56:25 +0900806 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800807 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700808
Chalard Jean5d70ba42018-06-07 16:44:04 +0900809 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
810 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000811 @VisibleForTesting
812 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400813
Erik Kline05f2b402015-04-30 12:58:40 +0900814 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700815
Chalard Jean46bfbf02022-02-02 00:56:25 +0900816 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400817
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700818 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900819 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700820
Valentin Iftime9fa35092019-09-24 13:32:13 +0200821 private Set<String> mWolSupportedInterfaces;
822
Roshan Pius08c94fb2020-01-16 12:17:17 -0800823 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800824 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800825 private final AppOpsManager mAppOpsManager;
826
827 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400828
Chalard Jean46bfbf02022-02-02 00:56:25 +0900829 private final KeepaliveTracker mKeepaliveTracker;
830 private final QosCallbackTracker mQosCallbackTracker;
831 private final NetworkNotificationManager mNotifier;
832 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900833
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700834 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800835 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700836
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900837 // Sequence number for NetworkProvider IDs.
838 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
839 NetworkProvider.FIRST_PROVIDER_ID);
840
Erik Klineedf878b2015-07-09 18:24:03 +0900841 // NetworkRequest activity String log entries.
842 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
843 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
844
Hugo Benichid159fdd2016-07-11 11:05:12 +0900845 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900846 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900847 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
848
Hugo Benichi47011212017-03-30 10:46:05 +0900849 private static final int MAX_WAKELOCK_LOGS = 20;
850 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900851 private int mTotalWakelockAcquisitions = 0;
852 private int mTotalWakelockReleases = 0;
853 private long mTotalWakelockDurationMs = 0;
854 private long mMaxWakelockDurationMs = 0;
855 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900856
Hugo Benichi208c0102016-07-28 17:53:06 +0900857 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900858
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700859 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900860 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700861
Erik Kline95ecfee2016-10-02 18:02:14 +0900862 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900863 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900864
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900865 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800866 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
867 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800868
Patrick Rohr2857ac42022-01-21 14:58:16 +0100869 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
870 // configured via {@link
871 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
872 // Only the handler thread is allowed to access this field.
873 private long mIngressRateLimit = -1;
874
Robert Greenwalt802c1102014-06-02 15:32:02 -0700875 /**
876 * Implements support for the legacy "one network per network type" model.
877 *
878 * We used to have a static array of NetworkStateTrackers, one for each
879 * network type, but that doesn't work any more now that we can have,
880 * for example, more that one wifi network. This class stores all the
881 * NetworkAgentInfo objects that support a given type, but the legacy
882 * API will only see the first one.
883 *
884 * It serves two main purposes:
885 *
886 * 1. Provide information about "the network for a given type" (since this
887 * API only supports one).
888 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
889 * the first network for a given type changes, or if the default network
890 * changes.
891 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900892 @VisibleForTesting
893 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900894
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900895 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900896 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900897
Robert Greenwalt802c1102014-06-02 15:32:02 -0700898 /**
899 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
900 * Each list holds references to all NetworkAgentInfos that are used to
901 * satisfy requests for that network type.
902 *
903 * This array is built out at startup such that an unsupported network
904 * doesn't get an ArrayList instance, making this a tristate:
905 * unsupported, supported but not active and active.
906 *
907 * The actual lists are populated when we scan the network types that
908 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900909 *
910 * Threading model:
911 * - addSupportedType() is only called in the constructor
912 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
913 * They are therefore not thread-safe with respect to each other.
914 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
915 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900916 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900917 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700918 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900919 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900920 @NonNull
921 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700922
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900923 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
924 // an entry have no timer (equivalent to -1). Lazily loaded.
925 @NonNull
926 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
927
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900928 LegacyTypeTracker(@NonNull ConnectivityService service) {
929 mService = service;
930 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700931 }
932
Chiachang Wang3bc52762021-11-25 14:17:57 +0800933 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
934 // addressed.
935 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900936 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
937 final PackageManager pm = ctx.getPackageManager();
938 if (pm.hasSystemFeature(FEATURE_WIFI)) {
939 addSupportedType(TYPE_WIFI);
940 }
941 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
942 addSupportedType(TYPE_WIFI_P2P);
943 }
944 if (tm.isDataCapable()) {
945 // Telephony does not have granular support for these types: they are either all
946 // supported, or none is supported
947 addSupportedType(TYPE_MOBILE);
948 addSupportedType(TYPE_MOBILE_MMS);
949 addSupportedType(TYPE_MOBILE_SUPL);
950 addSupportedType(TYPE_MOBILE_DUN);
951 addSupportedType(TYPE_MOBILE_HIPRI);
952 addSupportedType(TYPE_MOBILE_FOTA);
953 addSupportedType(TYPE_MOBILE_IMS);
954 addSupportedType(TYPE_MOBILE_CBS);
955 addSupportedType(TYPE_MOBILE_IA);
956 addSupportedType(TYPE_MOBILE_EMERGENCY);
957 }
958 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
959 addSupportedType(TYPE_BLUETOOTH);
960 }
961 if (pm.hasSystemFeature(FEATURE_WATCH)) {
962 // TYPE_PROXY is only used on Wear
963 addSupportedType(TYPE_PROXY);
964 }
965 // Ethernet is often not specified in the configs, although many devices can use it via
966 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000967 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900968 addSupportedType(TYPE_ETHERNET);
969 }
970
971 // Always add TYPE_VPN as a supported type
972 addSupportedType(TYPE_VPN);
973 }
974
975 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700976 if (mTypeLists[type] != null) {
977 throw new IllegalStateException(
978 "legacy list for type " + type + "already initialized");
979 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900980 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700981 }
982
Robert Greenwalt802c1102014-06-02 15:32:02 -0700983 public boolean isTypeSupported(int type) {
984 return isNetworkTypeValid(type) && mTypeLists[type] != null;
985 }
986
987 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900988 synchronized (mTypeLists) {
989 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
990 return mTypeLists[type].get(0);
991 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700992 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900993 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700994 }
995
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900996 public int getRestoreTimerForType(int type) {
997 synchronized (mTypeLists) {
998 if (mRestoreTimers == null) {
999 mRestoreTimers = loadRestoreTimers();
1000 }
1001 return mRestoreTimers.getOrDefault(type, -1);
1002 }
1003 }
1004
1005 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1006 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001007 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001008 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1009 for (final String config : configs) {
1010 final String[] splits = TextUtils.split(config, ",");
1011 if (splits.length != 2) {
1012 logwtf("Invalid restore timer token count: " + config);
1013 continue;
1014 }
1015 try {
1016 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1017 } catch (NumberFormatException e) {
1018 logwtf("Invalid restore timer number format: " + config, e);
1019 }
1020 }
1021 return ret;
1022 }
1023
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001024 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001025 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001026 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001027 log("Sending " + state
1028 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001029 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001030 }
1031 }
1032
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001033 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1034 // network type, to preserve previous behaviour.
1035 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1036 if (vpnNai != mService.getLegacyLockdownNai()) return;
1037
1038 if (vpnNai.declaredUnderlyingNetworks == null
1039 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1040 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1041 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1042 return;
1043 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001044 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001045 vpnNai.declaredUnderlyingNetworks[0]);
1046 if (underlyingNai == null) return;
1047
1048 final int type = underlyingNai.networkInfo.getType();
1049 final DetailedState state = DetailedState.CONNECTED;
1050 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1051 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1052 }
1053
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001054 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001055 public void add(int type, NetworkAgentInfo nai) {
1056 if (!isTypeSupported(type)) {
1057 return; // Invalid network type.
1058 }
1059 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1060
1061 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1062 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001063 return;
1064 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001065 synchronized (mTypeLists) {
1066 list.add(nai);
1067 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001068
Chalard Jean5b409c72021-02-04 13:12:59 +09001069 // Send a broadcast if this is the first network of its type or if it's the default.
1070 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001071
1072 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1073 // to preserve previous behaviour.
1074 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001075 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001076 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1077 mService.sendLegacyNetworkBroadcast(nai, state, type);
1078 }
1079
1080 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1081 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001082 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001083 }
1084
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001085 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001086 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001087 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1088 if (list == null || list.isEmpty()) {
1089 return;
1090 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001091 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001092
Hugo Benichi389633f2016-06-21 09:48:07 +09001093 synchronized (mTypeLists) {
1094 if (!list.remove(nai)) {
1095 return;
1096 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001097 }
1098
Lorenzo Colitti49767722015-05-01 00:30:10 +09001099 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001100 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1101 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001102 }
1103
1104 if (!list.isEmpty() && wasFirstNetwork) {
1105 if (DBG) log("Other network available for type " + type +
1106 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001107 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001108 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001109 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001110 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001111 }
1112 }
1113
1114 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001115 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1116 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001117 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001118 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001119 }
1120 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001121
Chalard Jean46bfbf02022-02-02 00:56:25 +09001122 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001123 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001124 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001125 final DetailedState state = nai.networkInfo.getDetailedState();
1126 for (int type = 0; type < mTypeLists.length; type++) {
1127 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001128 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001129 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001130 if (isFirst || contains && isDefault) {
1131 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001132 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001133 }
1134 }
1135 }
1136
Robert Greenwalt94e22142014-07-30 16:31:24 -07001137 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001138 pw.println("mLegacyTypeTracker:");
1139 pw.increaseIndent();
1140 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001141 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001142 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001143 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001144 pw.println();
1145 pw.println("Current state:");
1146 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001147 synchronized (mTypeLists) {
1148 for (int type = 0; type < mTypeLists.length; type++) {
1149 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1150 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001151 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001152 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001153 }
1154 }
1155 pw.decreaseIndent();
1156 pw.decreaseIndent();
1157 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001158 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001159 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001160 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001161
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001162 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001163 /**
1164 * Helper class which parses out priority arguments and dumps sections according to their
1165 * priority. If priority arguments are omitted, function calls the legacy dump command.
1166 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001167 private class LocalPriorityDump {
1168 private static final String PRIORITY_ARG = "--dump-priority";
1169 private static final String PRIORITY_ARG_HIGH = "HIGH";
1170 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1171
1172 LocalPriorityDump() {}
1173
1174 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1175 doDump(fd, pw, new String[] {DIAG_ARG});
1176 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001177 }
1178
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001179 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1180 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001181 }
1182
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001183 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1184 if (args == null) {
1185 dumpNormal(fd, pw, args);
1186 return;
1187 }
1188
1189 String priority = null;
1190 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1191 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1192 argIndex++;
1193 priority = args[argIndex];
1194 }
1195 }
1196
1197 if (PRIORITY_ARG_HIGH.equals(priority)) {
1198 dumpHigh(fd, pw);
1199 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1200 dumpNormal(fd, pw, args);
1201 } else {
1202 // ConnectivityService publishes binder service using publishBinderService() with
1203 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001204 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1205 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001206 // TODO: Integrate into signal dump.
1207 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001208 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001209 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001210 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001211
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001212 /**
1213 * Dependencies of ConnectivityService, for injection in tests.
1214 */
1215 @VisibleForTesting
1216 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001217 public int getCallingUid() {
1218 return Binder.getCallingUid();
1219 }
1220
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001221 /**
1222 * Get system properties to use in ConnectivityService.
1223 */
1224 public MockableSystemProperties getSystemProperties() {
1225 return new MockableSystemProperties();
1226 }
1227
1228 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001229 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1230 */
1231 public ConnectivityResources getResources(@NonNull Context ctx) {
1232 return new ConnectivityResources(ctx);
1233 }
1234
1235 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001236 * Create a HandlerThread to use in ConnectivityService.
1237 */
1238 public HandlerThread makeHandlerThread() {
1239 return new HandlerThread("ConnectivityServiceThread");
1240 }
1241
1242 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001243 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001244 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001245 public NetworkStackClientBase getNetworkStack() {
1246 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001247 }
1248
1249 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001250 * @see ProxyTracker
1251 */
1252 public ProxyTracker makeProxyTracker(@NonNull Context context,
1253 @NonNull Handler connServiceHandler) {
1254 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1255 }
1256
1257 /**
1258 * @see NetIdManager
1259 */
1260 public NetIdManager makeNetIdManager() {
1261 return new NetIdManager();
1262 }
1263
1264 /**
1265 * @see NetworkUtils#queryUserAccess(int, int)
1266 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001267 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1268 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001269 }
1270
1271 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001272 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1273 * requires CAP_NET_ADMIN, which the unit tests do not have.
1274 */
1275 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1276 InetSocketAddress remote) {
1277 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1278 }
1279
1280 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001281 * @see MultinetworkPolicyTracker
1282 */
1283 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1284 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1285 return new MultinetworkPolicyTracker(c, h, r);
1286 }
1287
Aaron Huang330a4c02020-10-27 03:36:19 +08001288 /**
1289 * @see BatteryStatsManager
1290 */
1291 public void reportNetworkInterfaceForTransports(Context context, String iface,
1292 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001293 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001294 context.getSystemService(BatteryStatsManager.class);
1295 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1296 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001297
1298 public boolean getCellular464XlatEnabled() {
1299 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1300 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001301
1302 /**
1303 * @see PendingIntent#intentFilterEquals
1304 */
1305 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1306 return a.intentFilterEquals(b);
1307 }
1308
1309 /**
1310 * @see LocationPermissionChecker
1311 */
1312 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1313 return new LocationPermissionChecker(context);
1314 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001315
1316 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001317 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001318 *
1319 * This method returns null in versions before T, where carrier privilege
1320 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001321 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001322 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001323 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1324 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1325 if (SdkLevel.isAtLeastT()) {
1326 return new CarrierPrivilegeAuthenticator(context, tm);
1327 } else {
1328 return null;
1329 }
1330 }
1331
1332 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001333 * @see DeviceConfigUtils#isFeatureEnabled
1334 */
1335 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1336 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1337 TETHERING_MODULE_NAME, defaultEnabled);
1338 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001339
1340 /**
1341 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001342 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001343 * @return BpfNetMaps implementation.
1344 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001345 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1346 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001347 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001348
1349 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001350 * @see ClatCoordinator
1351 */
1352 public ClatCoordinator getClatCoordinator(INetd netd) {
1353 return new ClatCoordinator(
1354 new ClatCoordinator.Dependencies() {
1355 @NonNull
1356 public INetd getNetd() {
1357 return netd;
1358 }
1359 });
1360 }
1361
1362 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001363 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1364 */
1365 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1366 final InterfaceParams params = InterfaceParams.getByName(iface);
1367 if (params == null) {
1368 // the interface might have disappeared.
1369 logw("Failed to get interface params for interface " + iface);
1370 return;
1371 }
1372 try {
1373 // converting rateInBytesPerSecond from long to int is safe here because the
1374 // setting's range is limited to INT_MAX.
1375 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001376 Log.i(TAG,
1377 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001378 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1379 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1380 } catch (IOException e) {
1381 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1382 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1383 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1384 + ") failure: ", e);
1385 }
1386 }
1387
1388 /**
1389 * Wraps {@link TcUtils#tcFilterDelDev}
1390 */
1391 public void disableIngressRateLimit(String iface) {
1392 final InterfaceParams params = InterfaceParams.getByName(iface);
1393 if (params == null) {
1394 // the interface might have disappeared.
1395 logw("Failed to get interface params for interface " + iface);
1396 return;
1397 }
1398 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001399 Log.i(TAG,
1400 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001401 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1402 } catch (IOException e) {
1403 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1404 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1405 }
1406 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001407 }
1408
junyulaie7c7d2a2021-01-26 15:29:15 +08001409 public ConnectivityService(Context context) {
1410 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001411 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1412 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001413 }
1414
1415 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001416 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1417 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001418 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001419
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001420 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001421 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001422 mSystemProperties = mDeps.getSystemProperties();
1423 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001424 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001425 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001426 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1427 // Pass limit - 1 to maintain backward compatibility.
1428 // TODO: Remove the workaround.
1429 mNetworkRequestCounter =
1430 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1431 mSystemNetworkRequestCounter =
1432 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001433
Hugo Benichi208c0102016-07-28 17:53:06 +09001434 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001435 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1436 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001437 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001438 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001439 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001440 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1441 mDefaultNetworkRequests.add(mDefaultRequest);
1442 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001443
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001444 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001445 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001446
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001447 // The default WiFi request is a background request so that apps using WiFi are
1448 // migrated to a better network (typically ethernet) when one comes up, instead
1449 // of staying on WiFi forever.
1450 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1451 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1452
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001453 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1454 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1455 NetworkRequest.Type.BACKGROUND_REQUEST);
1456
Chalard Jean0702f982021-09-16 21:50:07 +09001457 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1458 // TODO: Consider making the timer customizable.
1459 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1460 mCellularRadioTimesharingCapable =
1461 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1462
Paul Hu51f816b2022-08-11 14:43:47 +00001463 mNetd = netd;
1464 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001465 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001466 mPermissionMonitor =
1467 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001468 mHandlerThread.start();
1469 mHandler = new InternalHandler(mHandlerThread.getLooper());
1470 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001471 mConnectivityDiagnosticsHandler =
1472 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001473
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001474 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001475 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001476
junyulaie7c7d2a2021-01-26 15:29:15 +08001477 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001478 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001479 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001480 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001481
Wink Saville32506bc2013-06-29 21:10:57 -07001482 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001483 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001484 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001485 mCarrierPrivilegeAuthenticator =
1486 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001487
Sudheer Shanka9967d462021-03-18 19:09:25 +00001488 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001489 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1490 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001491 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001492
1493 final PowerManager powerManager = (PowerManager) context.getSystemService(
1494 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001495 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001496 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001497
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001498 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1499 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001500 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001501 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001502 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001503 mProtectedNetworks.add(p);
1504 } else {
1505 if (DBG) loge("Ignoring protectedNetwork " + p);
1506 }
1507 }
1508
soma, kawata29444ae2019-05-23 09:30:40 +09001509 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1510
James Mattis02220e22021-03-13 19:27:21 -08001511 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001512 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001513 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001514 final IntentFilter userIntentFilter = new IntentFilter();
1515 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1516 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1517 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1518 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001519
James Mattis02220e22021-03-13 19:27:21 -08001520 // Listen to package add/removes for netd
1521 final IntentFilter packageIntentFilter = new IntentFilter();
1522 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1523 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1524 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1525 packageIntentFilter.addDataScheme("package");
1526 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001527 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001528
lucaslind5c2d072021-02-20 18:59:47 +08001529 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001530
Chalard Jean46bfbf02022-02-02 00:56:25 +09001531 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001532 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001533 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001534 } catch (RemoteException | ServiceSpecificException e) {
1535 loge("Error registering event listener :" + e);
1536 }
1537
Erik Kline05f2b402015-04-30 12:58:40 +09001538 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1539 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001540
junyulai7e06ad42019-03-04 22:45:36 +08001541 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001542 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001543 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001544
1545 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001546 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001547 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1548 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001549 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001550 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1551 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001552
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001553 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001554 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001555 mNetworkRanker =
1556 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1557
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001558 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001559
Chiachang Wangc1215d32020-10-20 15:38:58 +08001560 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001561 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001562
Chalard Jean28018572020-12-21 18:36:52 +09001563 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1564 // request that doesn't allow fallback to the default network. It should never be visible
1565 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1566 // arguments like the handler or the DnsResolver.
1567 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001568 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001569 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001570 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001571 new LinkProperties(), new NetworkCapabilities(),
1572 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001573 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1574 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001575
1576 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001577 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1578 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1579 // Even if it could, running on S would at least require mocking out the BPF map,
1580 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1581 // the bpf syscall. http://aosp/1907693
1582 if (SdkLevel.isAtLeastT()) {
1583 mDscpPolicyTracker = new DscpPolicyTracker();
1584 }
Tyler Wear72388212021-09-09 14:49:02 -07001585 } catch (ErrnoException e) {
1586 loge("Unable to create DscpPolicyTracker");
1587 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001588
1589 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1590 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001591
1592 if (SdkLevel.isAtLeastT()) {
1593 mCdmps = new CompanionDeviceManagerProxyService(context);
1594 } else {
1595 mCdmps = null;
1596 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001597 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001598
Xiao Ma0a171c02022-01-23 16:14:51 +00001599 /**
1600 * Check whether or not the device supports Ethernet transport.
1601 */
1602 public static boolean deviceSupportsEthernet(final Context context) {
1603 final PackageManager pm = context.getPackageManager();
1604 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1605 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1606 }
1607
Chalard Jean46adcf32018-04-18 20:18:38 +09001608 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001609 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1610 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001611 }
1612
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001613 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1614 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001615 final NetworkCapabilities netCap = new NetworkCapabilities();
1616 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001617 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001618 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001619 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001620 return netCap;
1621 }
1622
James Mattis45d81842021-01-10 14:24:24 -08001623 private NetworkRequest createDefaultRequest() {
1624 return createDefaultInternetRequestForTransport(
1625 TYPE_NONE, NetworkRequest.Type.REQUEST);
1626 }
1627
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001628 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001629 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001630 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001631 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001632 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001633 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001634 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001635 netCap.addTransportType(transportType);
1636 }
James Mattis45d81842021-01-10 14:24:24 -08001637 return createNetworkRequest(type, netCap);
1638 }
1639
1640 private NetworkRequest createNetworkRequest(
1641 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001642 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001643 }
1644
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001645 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1646 NetworkRequest.Type type) {
1647 final NetworkCapabilities netCap = new NetworkCapabilities();
1648 netCap.clearAll();
1649 netCap.addCapability(capability);
1650 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1651 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1652 }
1653
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001654 // Used only for testing.
1655 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001656 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001657 // changing ContentResolver to make registerContentObserver non-final).
1658 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1659 // by subclassing SettingsObserver.
1660 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001661 void updateAlwaysOnNetworks() {
1662 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001663 }
1664
Erik Kline9a62f012018-03-21 07:18:33 -07001665 // See FakeSettingsProvider comment above.
1666 @VisibleForTesting
1667 void updatePrivateDnsSettings() {
1668 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1669 }
1670
paulhu51f77dc2021-06-07 02:34:20 +00001671 @VisibleForTesting
1672 void updateMobileDataPreferredUids() {
1673 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1674 }
1675
Patrick Rohr2857ac42022-01-21 14:58:16 +01001676 @VisibleForTesting
1677 void updateIngressRateLimit() {
1678 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1679 }
1680
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001681 private void handleAlwaysOnNetworkRequest(
1682 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001683 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001684 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001685 handleAlwaysOnNetworkRequest(networkRequest, enable);
1686 }
1687
1688 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001689 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001690 if (enable == isEnabled) {
1691 return; // Nothing to do.
1692 }
1693
1694 if (enable) {
1695 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001696 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001697 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001698 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001699 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001700 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1701 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001702 }
1703 }
1704
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001705 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001706 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1707 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1708 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1709 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001710 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1711 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001712 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001713 }
1714
paulhu51f77dc2021-06-07 02:34:20 +00001715 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001716 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001717 private void registerSettingsCallbacks() {
1718 // Watch for global HTTP proxy changes.
1719 mSettingsObserver.observe(
1720 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1721 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1722
Chalard Jean46bfbf02022-02-02 00:56:25 +09001723 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001724 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001725 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001726 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1727
Chalard Jean46bfbf02022-02-02 00:56:25 +09001728 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001729 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001730 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001731 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001732
1733 // Watch for mobile data preferred uids changes.
1734 mSettingsObserver.observe(
1735 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1736 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001737
1738 // Watch for ingress rate limit changes.
1739 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001740 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001741 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1742 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001743 }
1744
Erik Kline31b4a9e2018-01-11 21:07:29 +09001745 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001746 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1747 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001748 }
1749 }
1750
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001751 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001752 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1753 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001754 return mNextNetworkRequestId++;
1755 }
1756
junyulai74f9a8b2018-06-13 15:00:37 +08001757 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001758 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001759 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001760 if (network == null) {
1761 return null;
1762 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001763 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001764 }
1765
1766 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001767 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001768 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001769 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001770 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001771
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001772 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001773 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001774 private NetworkAgentInfo getVpnForUid(int uid) {
1775 synchronized (mNetworkForNetId) {
1776 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1777 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001778 if (nai.isVPN() && nai.everConnected()
1779 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001780 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001781 }
1782 }
1783 }
1784 return null;
1785 }
1786
Chalard Jean46bfbf02022-02-02 00:56:25 +09001787 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001788 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001789 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001790 final NetworkAgentInfo nai = getVpnForUid(uid);
1791 if (nai != null) return nai.declaredUnderlyingNetworks;
1792 return null;
1793 }
1794
Lorenzo Colittia7574052021-01-19 01:33:05 +09001795 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001796 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001797
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001798 final Network[] networks = getVpnUnderlyingNetworks(uid);
1799 if (networks != null) {
1800 // getUnderlyingNetworks() returns:
1801 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1802 // empty array => the VPN explicitly said "no default network".
1803 // non-empty array => the VPN specified one or more default networks; we use the
1804 // first one.
1805 if (networks.length > 0) {
1806 nai = getNetworkAgentInfoForNetwork(networks[0]);
1807 } else {
1808 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001809 }
1810 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001811 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001812 }
1813
1814 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001815 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001816 */
paulhu7aeba372020-12-30 00:42:19 +08001817 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1818 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001819 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001820 if (ignoreBlocked) {
1821 return false;
1822 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001823 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001824 final long ident = Binder.clearCallingIdentity();
1825 try {
1826 final boolean metered = nc == null ? true : nc.isMetered();
1827 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1828 } finally {
1829 Binder.restoreCallingIdentity(ident);
1830 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001831 }
1832
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001833 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001834 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1835 return;
1836 }
Hugo Benichi47011212017-03-30 10:46:05 +09001837 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001838 synchronized (mBlockedAppUids) {
1839 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001840 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001841 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001842 blocked = false;
1843 } else {
1844 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001845 }
1846 }
Hugo Benichi47011212017-03-30 10:46:05 +09001847 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1848 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1849 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001850 }
1851
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001852 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001853 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1854 return;
1855 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001856 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001857 final int requestId = nri.getActiveRequest() != null
1858 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001859 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001860 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001861 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001862 }
1863
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001864 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001865 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001866 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001867 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001868 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001869 @NonNull
1870 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1871 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001872 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1873 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1874 // but only exists if an app asks about them or requests them. Ensure the requesting app
1875 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001876 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001877 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1878 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1879 null /* extraInfo */);
1880 }
1881 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001882 return filtered;
1883 }
1884
1885 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1886 boolean ignoreBlocked) {
1887 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1888 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001889 }
1890
1891 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001892 * Return NetworkInfo for the active (i.e., connected) network interface.
1893 * It is assumed that at most one network is active at a time. If more
1894 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001895 * @return the info for the active network, or {@code null} if none is
1896 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001897 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001898 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001899 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001900 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001901 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001902 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001903 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1904 if (nai == null) return null;
1905 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1906 maybeLogBlockedNetworkInfo(networkInfo, uid);
1907 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 }
1909
Paul Jensen1f567382015-02-13 14:18:39 -05001910 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001911 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001912 public Network getActiveNetwork() {
1913 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001914 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001915 }
1916
1917 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001918 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001919 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001920 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001921 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001922 }
1923
Chalard Jean46bfbf02022-02-02 00:56:25 +09001924 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001925 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001926 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1927 if (vpnNai != null) {
1928 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1929 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1930 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001931 }
Paul Jensen1f567382015-02-13 14:18:39 -05001932 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001933
James Mattis2516da32021-01-31 17:06:19 -08001934 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001935 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1936 ignoreBlocked)) {
1937 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001938 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001939 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001940 }
1941
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001942 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001943 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001944 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001945 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001946 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1947 if (nai == null) return null;
1948 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001949 }
1950
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001951 /** Returns a NetworkInfo object for a network that doesn't exist. */
1952 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1953 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1954 getNetworkTypeName(networkType), "" /* subtypeName */);
1955 info.setIsAvailable(true);
1956 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1957 // background data is restricted.
1958 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1959 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1960 ? DetailedState.BLOCKED
1961 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001962 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1963 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001964 return info;
1965 }
1966
Lorenzo Colittia7574052021-01-19 01:33:05 +09001967 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001968 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1969 return null;
1970 }
1971 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001972 if (nai == null) {
1973 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001974 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001975 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1976 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001977 }
1978
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001979 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001980 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001981 public NetworkInfo getNetworkInfo(int networkType) {
1982 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001983 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001984 if (getVpnUnderlyingNetworks(uid) != null) {
1985 // A VPN is active, so we may need to return one of its underlying networks. This
1986 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001987 // getNetworkAgentInfoForUid.
1988 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1989 if (nai == null) return null;
1990 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1991 if (networkInfo.getType() == networkType) {
1992 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001993 }
1994 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001995 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001996 }
1997
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001998 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001999 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002000 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002001 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002002 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002003 if (nai == null) return null;
2004 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002005 }
2006
2007 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002008 public NetworkInfo[] getAllNetworkInfo() {
2009 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002010 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002011 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2012 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002013 NetworkInfo info = getNetworkInfo(networkType);
2014 if (info != null) {
2015 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002016 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002017 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002018 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002019 }
2020
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002021 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002022 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002023 public Network getNetworkForType(int networkType) {
2024 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002025 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2026 return null;
2027 }
2028 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2029 if (nai == null) {
2030 return null;
2031 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002032 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002033 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2034 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002035 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002036 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002037 }
2038
2039 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002040 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002041 public Network[] getAllNetworks() {
2042 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002043 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002044 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002045 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002046 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002047 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002048 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002049 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002050 }
2051
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002052 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002053 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002054 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002055 // The basic principle is: if an app's traffic could possibly go over a
2056 // network, without the app doing anything multinetwork-specific,
2057 // (hence, by "default"), then include that network's capabilities in
2058 // the array.
2059 //
2060 // In the normal case, app traffic only goes over the system's default
2061 // network connection, so that's the only network returned.
2062 //
2063 // With a VPN in force, some app traffic may go into the VPN, and thus
2064 // over whatever underlying networks the VPN specifies, while other app
2065 // traffic may go over the system default network (e.g.: a split-tunnel
2066 // VPN, or an app disallowed by the VPN), so the set of networks
2067 // returned includes the VPN's underlying networks and the system
2068 // default.
2069 enforceAccessPermission();
2070
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002071 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002072
James Mattis2516da32021-01-31 17:06:19 -08002073 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2074 if (!nri.isBeingSatisfied()) {
2075 continue;
2076 }
2077 final NetworkAgentInfo nai = nri.getSatisfier();
2078 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2079 if (null != nc
2080 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2081 && !result.containsKey(nai.network)) {
2082 result.put(
2083 nai.network,
2084 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002085 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002086 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2087 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002088 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002089 }
2090
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002091 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002092 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002093 if (null != networks) {
2094 for (final Network network : networks) {
2095 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2096 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002097 result.put(
2098 network,
2099 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002100 nc,
2101 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002102 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002103 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002104 }
2105 }
2106 }
2107
2108 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2109 out = result.values().toArray(out);
2110 return out;
2111 }
2112
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002113 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002114 public boolean isNetworkSupported(int networkType) {
2115 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002116 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002117 }
2118
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002119 /**
2120 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002121 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002122 * @return the ip properties for the active network, or {@code null} if
2123 * none is active
2124 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002125 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002126 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002127 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002128 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002129 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2130 if (nai == null) return null;
2131 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002132 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002133 }
2134
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002135 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002136 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002137 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002138 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002139 final LinkProperties lp = getLinkProperties(nai);
2140 if (lp == null) return null;
2141 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002142 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002143 }
2144
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002145 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002146 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002147 public LinkProperties getLinkProperties(Network network) {
2148 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002149 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2150 if (lp == null) return null;
2151 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002152 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002153 }
2154
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002155 @Nullable
2156 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002157 if (nai == null) {
2158 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002159 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002160 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002161 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002162 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002163 }
2164
lucaslinc582d502022-01-27 09:07:00 +08002165 @Override
2166 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002167 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002168 @NonNull String packageName, @Nullable String callingAttributionTag) {
2169 Objects.requireNonNull(packageName);
2170 Objects.requireNonNull(lp);
2171 enforceNetworkStackOrSettingsPermission();
2172 if (!checkAccessPermission(-1 /* pid */, uid)) {
2173 return null;
2174 }
2175 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2176 }
2177
Qingxi Lib2748102020-01-08 12:51:49 -08002178 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2179 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2180 }
2181
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002182 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002183 if (nai == null) return null;
2184 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002185 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002186 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002187 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002188 }
2189
2190 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002191 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2192 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002193 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002194 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002195 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002196 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002197 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002198 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002199 }
2200
lucaslinc582d502022-01-27 09:07:00 +08002201 @Override
lucaslind2b06132022-03-02 10:56:57 +08002202 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2203 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2204 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002205 Objects.requireNonNull(nc);
2206 Objects.requireNonNull(packageName);
2207 enforceNetworkStackOrSettingsPermission();
2208 if (!checkAccessPermission(-1 /* pid */, uid)) {
2209 return null;
2210 }
2211 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2212 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2213 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2214 callingAttributionTag);
2215 }
2216
lucaslin69e1aa92022-03-22 18:15:09 +08002217 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2218 if (nc.getUnderlyingNetworks() != null
2219 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2220 nc.setUnderlyingNetworks(null);
2221 }
2222 }
2223
Qingxi Libb8da982020-01-17 17:54:27 -08002224 @VisibleForTesting
2225 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002226 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002227 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2228 // this would be expensive (one more permission check every time any NC callback is
2229 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2230 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2231 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002232 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002233 if (!checkSettingsPermission(callerPid, callerUid)) {
2234 newNc.setUids(null);
2235 newNc.setSSID(null);
2236 }
Etan Cohen107ae952018-12-30 17:59:59 -08002237 if (newNc.getNetworkSpecifier() != null) {
2238 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2239 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002240 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2241 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2242 newNc.setAdministratorUids(new int[0]);
2243 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002244 if (!checkAnyPermissionOf(
2245 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002246 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002247 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002248 }
lucaslin69e1aa92022-03-22 18:15:09 +08002249 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002250
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002251 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002252 }
2253
Roshan Pius98f59ec2021-02-23 08:47:39 -08002254 /**
2255 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002256 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002257 * NetworkCapabilities.
2258 * Note: This wrapper does not support any sort of invalidation and thus must not be
2259 * persistent or long-lived. It may only be used for the time necessary to
2260 * compute the redactions required by one particular NetworkCallback or
2261 * synchronous call.
2262 */
2263 private class RedactionPermissionChecker {
2264 private final int mCallingPid;
2265 private final int mCallingUid;
2266 @NonNull private final String mCallingPackageName;
2267 @Nullable private final String mCallingAttributionTag;
2268
2269 private Boolean mHasLocationPermission = null;
2270 private Boolean mHasLocalMacAddressPermission = null;
2271 private Boolean mHasSettingsPermission = null;
2272
2273 RedactionPermissionChecker(int callingPid, int callingUid,
2274 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2275 mCallingPid = callingPid;
2276 mCallingUid = callingUid;
2277 mCallingPackageName = callingPackageName;
2278 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002279 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002280
2281 private boolean hasLocationPermissionInternal() {
2282 final long token = Binder.clearCallingIdentity();
2283 try {
2284 return mLocationPermissionChecker.checkLocationPermission(
2285 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2286 null /* message */);
2287 } finally {
2288 Binder.restoreCallingIdentity(token);
2289 }
2290 }
2291
2292 /**
2293 * Returns whether the app holds location permission or not (might return cached result
2294 * if the permission was already checked before).
2295 */
2296 public boolean hasLocationPermission() {
2297 if (mHasLocationPermission == null) {
2298 // If there is no cached result, perform the check now.
2299 mHasLocationPermission = hasLocationPermissionInternal();
2300 }
2301 return mHasLocationPermission;
2302 }
2303
2304 /**
2305 * Returns whether the app holds local mac address permission or not (might return cached
2306 * result if the permission was already checked before).
2307 */
2308 public boolean hasLocalMacAddressPermission() {
2309 if (mHasLocalMacAddressPermission == null) {
2310 // If there is no cached result, perform the check now.
2311 mHasLocalMacAddressPermission =
2312 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2313 }
2314 return mHasLocalMacAddressPermission;
2315 }
2316
2317 /**
2318 * Returns whether the app holds settings permission or not (might return cached
2319 * result if the permission was already checked before).
2320 */
2321 public boolean hasSettingsPermission() {
2322 if (mHasSettingsPermission == null) {
2323 // If there is no cached result, perform the check now.
2324 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2325 }
2326 return mHasSettingsPermission;
2327 }
2328 }
2329
2330 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2331 @NetworkCapabilities.NetCapability long redaction) {
2332 return (redactions & redaction) != 0;
2333 }
2334
2335 /**
2336 * Use the provided |applicableRedactions| to check the receiving app's
2337 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2338 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2339 * before being sent to the corresponding app.
2340 */
2341 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2342 @NetworkCapabilities.RedactionType long applicableRedactions,
2343 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2344 boolean includeLocationSensitiveInfo) {
2345 long redactions = applicableRedactions;
2346 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2347 if (includeLocationSensitiveInfo
2348 && redactionPermissionChecker.hasLocationPermission()) {
2349 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2350 }
2351 }
2352 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2353 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2354 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2355 }
2356 }
2357 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2358 if (redactionPermissionChecker.hasSettingsPermission()) {
2359 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2360 }
2361 }
2362 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002363 }
2364
Qingxi Lib2748102020-01-08 12:51:49 -08002365 @VisibleForTesting
2366 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002367 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002368 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002369 int callingPid, int callingUid, @NonNull String callingPkgName,
2370 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002371 if (nc == null) {
2372 return null;
2373 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002374 // Avoid doing location permission check if the transport info has no location sensitive
2375 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002376 final RedactionPermissionChecker redactionPermissionChecker =
2377 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2378 callingAttributionTag);
2379 final long redactions = retrieveRequiredRedactions(
2380 nc.getApplicableRedactions(), redactionPermissionChecker,
2381 includeLocationSensitiveInfo);
2382 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002383 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002384 // TODO : calling UID is redacted because apps should generally not know what UID is
2385 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002386 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002387 newNc.setOwnerUid(INVALID_UID);
2388 return newNc;
2389 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002390 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2391 if (nc.hasTransport(TRANSPORT_VPN)) {
2392 // Owner UIDs already checked above. No need to re-check.
2393 return newNc;
2394 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002395 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2396 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002397 // compatibility for older apps.
2398 if (!includeLocationSensitiveInfo
2399 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002400 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002401 newNc.setOwnerUid(INVALID_UID);
2402 return newNc;
2403 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002404 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002405 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002406 newNc.setOwnerUid(INVALID_UID);
2407 }
Qingxi Lib2748102020-01-08 12:51:49 -08002408 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002409 }
2410
lucaslinc582d502022-01-27 09:07:00 +08002411 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002412 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2413 LinkProperties lp, int callerPid, int callerUid) {
2414 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002415 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2416 // this would be expensive (one more permission check every time any LP callback is
2417 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2418 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2419 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002420
2421 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2422 final boolean needsSanitization =
2423 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2424 if (!needsSanitization) {
2425 return new LinkProperties(lp);
2426 }
2427
2428 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002429 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002430 }
2431
2432 final LinkProperties newLp = new LinkProperties(lp);
2433 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2434 // object gets parceled.
2435 newLp.setCaptivePortalApiUrl(null);
2436 newLp.setCaptivePortalData(null);
2437 return newLp;
2438 }
2439
Roshan Pius08c94fb2020-01-16 12:17:17 -08002440 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2441 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002442 // There is no need to track the effective UID of the request here. If the caller
2443 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002444 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002445 // Unprivileged apps can only pass in null or their own UID.
2446 if (nc.getUids() == null) {
2447 // If the caller passes in null, the callback will also match networks that do not
2448 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2449 // In this case, redact everything in the request immediately. This ensures that the
2450 // app is not able to get any redacted information by filing an unredacted request
2451 // and observing whether the request matches something.
2452 if (nc.getNetworkSpecifier() != null) {
2453 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2454 }
2455 } else {
2456 nc.setSingleUid(callerUid);
2457 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002458 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002459 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002460 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002461
2462 // Clear owner UID; this can never come from an app.
2463 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002464 }
2465
Chalard Jean38354d12018-03-20 19:13:57 +09002466 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002467 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002468 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2469 }
2470 }
2471
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002472 @Override
2473 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2474 enforceAccessPermission();
2475 final int callerUid = Binder.getCallingUid();
2476 final long token = Binder.clearCallingIdentity();
2477 try {
2478 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2479 } finally {
2480 Binder.restoreCallingIdentity(token);
2481 }
2482 }
2483
junyulaiebd15162021-03-03 12:09:05 +08002484 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002485 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002486 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002487 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002488 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002489
Serik Beketayev05130302021-01-15 16:47:25 -08002490 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002491 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002492 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2493 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002494 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002495 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002496 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002497 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2498 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002499 }
2500 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002501 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002502 }
2503
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002504 @Override
junyulaiebd15162021-03-03 12:09:05 +08002505 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002506 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002507 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002508 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002509
2510 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2511 for (Network network : getAllNetworks()) {
2512 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002513 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002514 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2515 // NetworkCapabilities, which may contain UIDs of apps to which the
2516 // network applies. Should the UIDs be cleared so as not to leak or
2517 // interfere ?
2518 result.add(nai.getNetworkStateSnapshot());
2519 }
2520 }
2521 return result;
2522 }
2523
2524 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002525 public boolean isActiveNetworkMetered() {
2526 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002527
Qingxi Lib2748102020-01-08 12:51:49 -08002528 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002529 if (caps != null) {
2530 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2531 } else {
2532 // Always return the most conservative value
2533 return true;
2534 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002535 }
2536
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002537 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002538 * Ensures that the system cannot call a particular method.
2539 */
2540 private boolean disallowedBecauseSystemCaller() {
2541 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002542 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2543 // for devices launched with Q and above. However, existing devices upgrading to Q and
2544 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002545 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002546 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002547 log("This method exists only for app backwards compatibility"
2548 + " and must not be called by system services.");
2549 return true;
2550 }
2551 return false;
2552 }
2553
paulhub2c28682021-08-18 18:35:54 +08002554 private int getAppUid(final String app, final UserHandle user) {
2555 final PackageManager pm =
2556 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2557 final long token = Binder.clearCallingIdentity();
2558 try {
2559 return pm.getPackageUid(app, 0 /* flags */);
2560 } catch (PackageManager.NameNotFoundException e) {
2561 return -1;
2562 } finally {
2563 Binder.restoreCallingIdentity(token);
2564 }
2565 }
2566
2567 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2568 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2569 if (getAppUid(packageName, user) != callingUid) {
2570 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2571 }
2572 }
2573
Lorenzo Colitti23862912018-09-28 11:31:55 +09002574 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002575 * Ensure that a network route exists to deliver traffic to the specified
2576 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002577 * @param networkType the type of the network over which traffic to the
2578 * specified host is to be routed
2579 * @param hostAddress the IP address of the host to which the route is
2580 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002581 * @return {@code true} on success, {@code false} on failure
2582 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002583 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002584 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2585 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002586 if (disallowedBecauseSystemCaller()) {
2587 return false;
2588 }
paulhub2c28682021-08-18 18:35:54 +08002589 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002590 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002591 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002592 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002593 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002594
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002595 InetAddress addr;
2596 try {
2597 addr = InetAddress.getByAddress(hostAddress);
2598 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002599 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002600 return false;
2601 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002602
The Android Open Source Project28527d22009-03-03 19:31:44 -08002603 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002604 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002605 return false;
2606 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002607
2608 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2609 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002610 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002611 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2612 } else {
2613 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2614 }
2615 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002616 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002617
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002618 DetailedState netState;
2619 synchronized (nai) {
2620 netState = nai.networkInfo.getDetailedState();
2621 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002622
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002623 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002624 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002625 log("requestRouteToHostAddress on down network "
2626 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002627 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002628 }
2629 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002630 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002631
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002632 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002633 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002634 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002635 LinkProperties lp;
2636 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002637 synchronized (nai) {
2638 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002639 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002640 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002641 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002642 if (DBG) {
2643 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2644 }
Wink Saville32506bc2013-06-29 21:10:57 -07002645 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002646 } finally {
2647 Binder.restoreCallingIdentity(token);
2648 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002649 }
2650
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002651 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002652 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002653 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002654 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002655 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002656 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002657 if (bestRoute.getGateway().equals(addr)) {
2658 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002659 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002660 } else {
2661 // if we will connect to this through another route, add a direct route
2662 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002663 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002664 }
2665 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002666 if (DBG) log("Adding legacy route " + bestRoute +
2667 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002668
2669 final String dst = bestRoute.getDestinationLinkAddress().toString();
2670 final String nextHop = bestRoute.hasGateway()
2671 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002672 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002673 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2674 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002675 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002676 return false;
2677 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002678 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002679 }
2680
paulhu7c0a2e62021-01-08 00:51:49 +08002681 class DnsResolverUnsolicitedEventCallback extends
2682 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002683 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002684 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002685 try {
2686 mHandler.sendMessage(mHandler.obtainMessage(
2687 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002688 new PrivateDnsValidationUpdate(event.netId,
2689 InetAddresses.parseNumericAddress(event.ipAddress),
2690 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002691 } catch (IllegalArgumentException e) {
2692 loge("Error parsing ip address in validation event");
2693 }
2694 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002695
2696 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002697 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2698 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002699 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2700 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2701 // event callback for certain nai. e.g. cellular. Register here to pass to
2702 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002703 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002704 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2705 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002706 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002707 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002708 }
2709 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002710
2711 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002712 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2713 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2714 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002715 }
dalyk1720e542018-03-05 12:42:22 -05002716
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002717 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002718 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002719 return this.VERSION;
2720 }
2721
2722 @Override
2723 public String getInterfaceHash() {
2724 return this.HASH;
2725 }
paulhu7c0a2e62021-01-08 00:51:49 +08002726 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002727
2728 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002729 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2730 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002731
paulhu7c0a2e62021-01-08 00:51:49 +08002732 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002733 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002734 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002735 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002736 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002737 }
2738 }
2739
Sudheer Shanka9967d462021-03-18 19:09:25 +00002740 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002741 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002742 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2744 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002745 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002746 };
2747
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002748 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002749 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002750 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002751 }
2752
paulhu1a407652019-03-22 16:35:06 +08002753 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2754 for (String permission : permissions) {
2755 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2756 return true;
2757 }
2758 }
2759 return false;
2760 }
2761
Paul Jensen83f5d572014-08-29 09:54:01 -04002762 private void enforceInternetPermission() {
2763 mContext.enforceCallingOrSelfPermission(
2764 android.Manifest.permission.INTERNET,
2765 "ConnectivityService");
2766 }
2767
The Android Open Source Project28527d22009-03-03 19:31:44 -08002768 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002769 mContext.enforceCallingOrSelfPermission(
2770 android.Manifest.permission.ACCESS_NETWORK_STATE,
2771 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002772 }
2773
lucaslinc582d502022-01-27 09:07:00 +08002774 private boolean checkAccessPermission(int pid, int uid) {
2775 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2776 == PERMISSION_GRANTED;
2777 }
2778
paulhua6ee2122021-02-22 15:40:43 +08002779 /**
2780 * Performs a strict and comprehensive check of whether a calling package is allowed to
2781 * change the state of network, as the condition differs for pre-M, M+, and
2782 * privileged/preinstalled apps. The caller is expected to have either the
2783 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2784 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2785 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2786 * permission and cannot be revoked. See http://b/23597341
2787 *
2788 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2789 * of this app will be updated to the current time.
2790 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002791 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002792 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2793 == PackageManager.PERMISSION_GRANTED) {
2794 return;
2795 }
2796
2797 if (callingPkg == null) {
2798 throw new SecurityException("Calling package name is null.");
2799 }
2800
2801 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2802 final int uid = mDeps.getCallingUid();
2803 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2804 callingPkg, callingAttributionTag, null /* message */);
2805
2806 if (mode == AppOpsManager.MODE_ALLOWED) {
2807 return;
2808 }
2809
2810 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2811 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2812 return;
2813 }
2814
2815 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2816 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2817 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002818 }
2819
Charles He9369e612017-05-15 17:07:18 +01002820 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002821 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002822 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002823 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002824 }
2825
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002826 private void enforceSettingsOrUseRestrictedNetworksPermission() {
2827 enforceAnyPermissionOf(mContext,
2828 android.Manifest.permission.NETWORK_SETTINGS,
2829 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2830 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
2831 }
2832
paulhu8e96a752019-08-12 16:25:11 +08002833 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002834 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002835 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002836 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002837 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002838 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002839 }
2840
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002841 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002842 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002843 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002844 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002845 android.Manifest.permission.NETWORK_SETTINGS,
2846 android.Manifest.permission.NETWORK_FACTORY,
2847 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2848 }
2849
2850 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002851 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002852 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002853 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002854 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2855 android.Manifest.permission.NETWORK_FACTORY,
2856 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2857 }
2858
lucaslin69e1aa92022-03-22 18:15:09 +08002859 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2860 return PERMISSION_GRANTED == mContext.checkPermission(
2861 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2862 || PERMISSION_GRANTED == mContext.checkPermission(
2863 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2864 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002865 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002866 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002867 }
2868
Chalard Jean9a396cc2018-02-21 18:43:54 +09002869 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002870 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002871 android.Manifest.permission.NETWORK_SETTINGS,
2872 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002873 }
2874
2875 private boolean checkSettingsPermission(int pid, int uid) {
2876 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002877 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2878 || PERMISSION_GRANTED == mContext.checkPermission(
2879 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002880 }
2881
paulhu8e96a752019-08-12 16:25:11 +08002882 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002883 enforceNetworkStackPermissionOr(mContext,
2884 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002885 }
2886
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002887 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002888 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002889 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002890 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002891 }
2892
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002893 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002894 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002895 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2896 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002897 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002898 }
2899
James Mattis8378aec2021-01-26 14:05:36 -08002900 private void enforceOemNetworkPreferencesPermission() {
2901 mContext.enforceCallingOrSelfPermission(
2902 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2903 "ConnectivityService");
2904 }
2905
James Mattisfa270db2021-05-31 17:11:10 -07002906 private void enforceManageTestNetworksPermission() {
2907 mContext.enforceCallingOrSelfPermission(
2908 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2909 "ConnectivityService");
2910 }
2911
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002912 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002913 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002914 android.Manifest.permission.NETWORK_STACK,
2915 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002916 }
2917
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002918 private boolean checkNetworkStackPermission(int pid, int uid) {
2919 return checkAnyPermissionOf(pid, uid,
2920 android.Manifest.permission.NETWORK_STACK,
2921 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2922 }
2923
paulhu1a407652019-03-22 16:35:06 +08002924 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2925 return checkAnyPermissionOf(pid, uid,
2926 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002927 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2928 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002929 }
2930
Paul Hu8fc2a552022-05-04 18:44:42 +08002931 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2932 boolean checkUidsAllowedList) {
2933 if (PermissionUtils.checkAnyPermissionOf(mContext,
2934 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2935 return true;
2936 }
2937
2938 // fallback to ConnectivityInternalPermission
2939 // TODO: Remove this fallback check after all apps have declared
2940 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2941 if (PermissionUtils.checkAnyPermissionOf(mContext,
2942 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2943 return true;
2944 }
2945
2946 // Check whether uid is in allowed on restricted networks list.
2947 if (checkUidsAllowedList
2948 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2949 return true;
2950 }
2951 return false;
2952 }
2953
2954 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2955 final int callingUid = mDeps.getCallingUid();
2956 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2957 throw new SecurityException("ConnectivityService: user " + callingUid
2958 + " has no permission to access restricted network.");
2959 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002960 }
2961
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002962 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002963 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002964 }
2965
Roshan Pius98f59ec2021-02-23 08:47:39 -08002966 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2967 return PERMISSION_GRANTED == mContext.checkPermission(
2968 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2969 }
2970
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002971 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002972 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002973 }
2974
2975 private void sendInetConditionBroadcast(NetworkInfo info) {
2976 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2977 }
2978
Wink Saville4f0de1e2011-08-04 15:01:58 -07002979 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002980 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002981 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002982 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002983 if (info.isFailover()) {
2984 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2985 info.setFailover(false);
2986 }
2987 if (info.getReason() != null) {
2988 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2989 }
2990 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002991 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2992 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002993 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002994 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002995 return intent;
2996 }
2997
2998 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2999 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3000 }
3001
Chiachang Wang3bc52762021-11-25 14:17:57 +08003002 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3003 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003004 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003005 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003006 if (!mSystemReady
3007 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003008 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003009 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003010 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003011 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003012 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003013 }
3014
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003015 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003016 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003017 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003018 final NetworkInfo ni = intent.getParcelableExtra(
3019 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003020 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3021 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
3022 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003023 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003024 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003025 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003026 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003027 } finally {
3028 Binder.restoreCallingIdentity(ident);
3029 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003030 }
3031 }
3032
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003033 /**
Aaron Huang96011892020-06-27 07:18:23 +08003034 * Called by SystemServer through ConnectivityManager when the system is ready.
3035 */
3036 @Override
3037 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003038 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003039 throw new SecurityException("Calling Uid is not system uid.");
3040 }
3041 systemReadyInternal();
3042 }
3043
3044 /**
3045 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003046 */
3047 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003048 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003049 // Load flags after PackageManager is ready to query module version
3050 mFlags.loadFlags(mDeps, mContext);
3051
Aaron Huang9a57acf2020-12-08 10:03:29 +08003052 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3053 // listening network request which is sent by MultipathPolicyTracker won't be added
3054 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3055 // be called after PermissionMonitor#startMonitoring().
3056 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3057 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3058 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003059 final ConditionVariable startMonitoringDone = new ConditionVariable();
3060 mHandler.post(() -> {
3061 mPermissionMonitor.startMonitoring();
3062 startMonitoringDone.open();
3063 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003064 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003065 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003066
Hugo Benichie5220992017-04-26 14:53:28 +09003067 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003068 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003069 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003070 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003071 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003072 }
3073 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003074
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003075 // Create network requests for always-on networks.
3076 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003077
3078 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003079 // Note that updating can be skipped here if the list is empty only because no uid
3080 // rules are applied before system ready. Normally, the empty uid list means to clear
3081 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003082 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3083 updateMobileDataPreferredUids();
3084 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003085
3086 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3087 if (SdkLevel.isAtLeastT()) {
3088 mBpfNetMaps.setPullAtomCallback(mContext);
3089 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003090 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3091 // have permission problem. While CV#block() is unbounded in time and can in principle block
3092 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3093 // could have blocked forever too.
3094 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003095 }
3096
The Android Open Source Project28527d22009-03-03 19:31:44 -08003097 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003098 * Start listening for default data network activity state changes.
3099 */
3100 @Override
3101 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003102 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003103 }
3104
3105 /**
3106 * Stop listening for default data network activity state changes.
3107 */
3108 @Override
3109 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003110 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003111 }
3112
3113 /**
3114 * Check whether the default network radio is currently active.
3115 */
3116 @Override
3117 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003118 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003119 }
3120
3121 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003122 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003123 * and set it on it's iface.
3124 */
Junyu Lai970963e2022-10-25 15:46:47 +08003125 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003126 final String iface = newLp.getInterfaceName();
3127 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003128 if (oldLp == null && mtu == 0) {
3129 // Silently ignore unset MTU value.
3130 return;
3131 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003132 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3133 if (VDBG) log("identical MTU - not setting");
3134 return;
3135 }
paulhucbbc3db2019-03-08 16:35:20 +08003136 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003137 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003138 return;
3139 }
sy.yun4aa73922013-09-02 05:24:09 +09003140
w19976e714f1d2014-08-05 15:18:11 -07003141 // Cannot set MTU without interface name
3142 if (TextUtils.isEmpty(iface)) {
3143 loge("Setting MTU size with null iface.");
3144 return;
3145 }
3146
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003147 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003148 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003149 mNetd.interfaceSetMtu(iface, mtu);
3150 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003151 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003152 }
3153 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003154
Chenbo Feng15416292018-11-08 17:36:21 -08003155 @VisibleForTesting
3156 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003157
Junyu Lai970963e2022-10-25 15:46:47 +08003158 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003159 String[] values = null;
3160 if (tcpBufferSizes != null) {
3161 values = tcpBufferSizes.split(",");
3162 }
3163
3164 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003165 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003166 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3167 values = tcpBufferSizes.split(",");
3168 }
3169
3170 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3171
3172 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003173 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003174
Chenbo Feng15416292018-11-08 17:36:21 -08003175 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3176 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3177 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003178 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003179 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003180 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003181 }
3182 }
3183
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003184 @Override
3185 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003186 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003187 NETWORK_RESTORE_DELAY_PROP_NAME);
3188 if(restoreDefaultNetworkDelayStr != null &&
3189 restoreDefaultNetworkDelayStr.length() != 0) {
3190 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003191 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003192 } catch (NumberFormatException e) {
3193 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003194 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003195 // if the system property isn't set, use the value for the apn type
3196 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3197
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003198 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3199 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003200 }
3201 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003202 }
3203
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003204 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003205 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003206 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003207 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003208 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003209 // Start gathering diagnostic information.
3210 netDiags.add(new NetworkDiagnostics(
3211 nai.network,
3212 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003213 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003214 DIAG_TIME_MS));
3215 }
3216
3217 for (NetworkDiagnostics netDiag : netDiags) {
3218 pw.println();
3219 netDiag.waitForMeasurements();
3220 netDiag.dump(pw);
3221 }
3222 }
3223
The Android Open Source Project28527d22009-03-03 19:31:44 -08003224 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003225 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3226 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003227 if (!checkDumpPermission(mContext, TAG, writer)) return;
3228
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003229 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003230 }
3231
lucaslin99473f62020-12-10 15:10:54 +08003232 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3233 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3234 != PackageManager.PERMISSION_GRANTED) {
3235 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003236 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003237 + " due to missing android.permission.DUMP permission");
3238 return false;
3239 } else {
3240 return true;
3241 }
3242 }
3243
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003244 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003245 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003246
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003247 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003248 dumpNetworkDiagnostics(pw);
3249 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003250 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003251 dumpNetworks(pw);
3252 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003253 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003254 dumpNetworkRequests(pw);
3255 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003256 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3257 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3258 dumpTrafficController(pw, fd, verbose);
3259 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003260 }
Erik Kline9647f382015-06-05 17:47:34 +09003261
Junyu Lai0da479b2022-04-20 15:06:29 +08003262 pw.println("NetworkProviders for:");
3263 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003264 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003265 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003266 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003267 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003268 pw.println();
3269
Chalard Jean5b409c72021-02-04 13:12:59 +09003270 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003271 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003272 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003273 pw.println("none");
3274 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003275 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003276 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003277 pw.println();
3278
James Mattis8b298a02021-06-01 22:34:04 -07003279 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003280 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003281 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003282 pw.decreaseIndent();
3283 pw.println();
3284
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003285 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003286 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003287 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003288 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003289 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003290
junyulaif2c67e42018-08-07 19:50:45 +08003291 pw.println("Status for known UIDs:");
3292 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003293 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003294 for (int i = 0; i < size; i++) {
3295 // Don't crash if the array is modified while dumping in bugreports.
3296 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003297 final int uid = mUidBlockedReasons.keyAt(i);
3298 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3299 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003300 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003301 } catch (ArrayIndexOutOfBoundsException e) {
3302 pw.println(" ArrayIndexOutOfBoundsException");
3303 } catch (ConcurrentModificationException e) {
3304 pw.println(" ConcurrentModificationException");
3305 }
3306 }
3307 pw.println();
3308 pw.decreaseIndent();
3309
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003310 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003311 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003312 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003313 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003314 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003315
Junyu Lai0da479b2022-04-20 15:06:29 +08003316 pw.println("Network Offers:");
3317 pw.increaseIndent();
3318 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3319 pw.println(offerInfo.offer);
3320 }
3321 pw.decreaseIndent();
3322 pw.println();
3323
Robert Greenwalt94e22142014-07-30 16:31:24 -07003324 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003325
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003326 pw.println();
markchien5e866652019-09-30 14:40:57 +08003327 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003328
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003329 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003330 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003331
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003332 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003333
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003334 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003335 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003336 pw.println("mNetworkRequestInfoLogs (most recent first):");
3337 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003338 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003339 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003340
3341 pw.println();
3342 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3343 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003344 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003345 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003346
3347 pw.println();
3348 pw.println("NetTransition WakeLock activity (most recent first):");
3349 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003350 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3351 pw.println("total releases: " + mTotalWakelockReleases);
3352 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3353 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3354 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3355 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3356 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3357 }
James Mattiscb1e0362021-04-06 17:07:42 -07003358 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003359
3360 pw.println();
3361 pw.println("bandwidth update requests (by uid):");
3362 pw.increaseIndent();
3363 synchronized (mBandwidthRequests) {
3364 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3365 pw.println("[" + mBandwidthRequests.keyAt(i)
3366 + "]: " + mBandwidthRequests.valueAt(i));
3367 }
3368 }
3369 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003370 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003371
James Mattiscb1e0362021-04-06 17:07:42 -07003372 pw.println();
3373 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3374 pw.increaseIndent();
3375 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003376 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003377 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003378
3379 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003380
3381 pw.println();
3382 pw.println("Permission Monitor:");
3383 pw.increaseIndent();
3384 mPermissionMonitor.dump(pw);
3385 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003386
3387 pw.println();
3388 pw.println("Legacy network activity:");
3389 pw.increaseIndent();
3390 mNetworkActivityTracker.dump(pw);
3391 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003392 }
3393
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003394 private void dumpNetworks(IndentingPrintWriter pw) {
3395 for (NetworkAgentInfo nai : networksSortedById()) {
3396 pw.println(nai.toString());
3397 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003398 pw.println("Nat464Xlat:");
3399 pw.increaseIndent();
3400 nai.dumpNat464Xlat(pw);
3401 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003402 pw.println(String.format(
3403 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3404 nai.numForegroundNetworkRequests(),
3405 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3406 nai.numBackgroundNetworkRequests(),
3407 nai.numNetworkRequests()));
3408 pw.increaseIndent();
3409 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3410 pw.println(nai.requestAt(i).toString());
3411 }
3412 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003413 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003414 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003415 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003416 pw.decreaseIndent();
3417 pw.decreaseIndent();
3418 }
3419 }
3420
James Mattis8b298a02021-06-01 22:34:04 -07003421 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3422 if (!mProfileNetworkPreferences.isEmpty()) {
3423 pw.println("Profile preferences:");
3424 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003425 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003426 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003427 }
James Mattis8b298a02021-06-01 22:34:04 -07003428 if (!mOemNetworkPreferences.isEmpty()) {
3429 pw.println("OEM preferences:");
3430 pw.increaseIndent();
3431 pw.println(mOemNetworkPreferences);
3432 pw.decreaseIndent();
3433 }
3434 if (!mMobileDataPreferredUids.isEmpty()) {
3435 pw.println("Mobile data preferred UIDs:");
3436 pw.increaseIndent();
3437 pw.println(mMobileDataPreferredUids);
3438 pw.decreaseIndent();
3439 }
James Mattis45d81842021-01-10 14:24:24 -08003440
James Mattis8b298a02021-06-01 22:34:04 -07003441 pw.println("Default requests:");
3442 pw.increaseIndent();
3443 dumpPerAppDefaultRequests(pw);
3444 pw.decreaseIndent();
3445 }
3446
3447 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003448 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3449 if (mDefaultRequest == defaultRequest) {
3450 continue;
3451 }
3452
James Mattis8b298a02021-06-01 22:34:04 -07003453 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3454 final String networkOutput;
3455 if (null == satisfier) {
3456 networkOutput = "null";
3457 } else if (mNoServiceNetwork.equals(satisfier)) {
3458 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003459 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003460 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003461 }
James Mattis8b298a02021-06-01 22:34:04 -07003462 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3463 ? "" : " asUid: " + defaultRequest.mAsUid;
3464 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3465 + defaultRequest.mPid + asUidString + "]";
3466 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3467 + " Preference order: " + defaultRequest.mPreferenceOrder
3468 + " Tracked UIDs: " + defaultRequest.getUids();
3469 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003470 }
3471 }
3472
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003473 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003474 NetworkRequestInfo[] infos = null;
3475 while (infos == null) {
3476 try {
3477 infos = requestsSortedById();
3478 } catch (ConcurrentModificationException e) {
3479 // mNetworkRequests should only be accessed from handler thread, except dump().
3480 // As dump() is never called in normal usage, it would be needlessly expensive
3481 // to lock the collection only for its benefit. Instead, retry getting the
3482 // requests if ConcurrentModificationException is thrown during dump().
3483 }
3484 }
3485 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003486 pw.println(nri.toString());
3487 }
3488 }
3489
Ken Chene6d511f2022-01-25 11:10:42 +08003490 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3491 boolean verbose) {
3492 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003493 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003494 } catch (ServiceSpecificException e) {
3495 pw.println(e.getMessage());
3496 } catch (IOException e) {
3497 loge("Dump BPF maps failed, " + e);
3498 }
3499 }
3500
Chalard Jean524f0b12021-10-25 21:11:56 +09003501 private void dumpAllRequestInfoLogsToLogcat() {
3502 try (PrintWriter logPw = new PrintWriter(new Writer() {
3503 @Override
3504 public void write(final char[] cbuf, final int off, final int len) {
3505 // This method is called with 0-length and 1-length arrays for empty strings
3506 // or strings containing only the DEL character.
3507 if (len <= 1) return;
3508 Log.e(TAG, new String(cbuf, off, len));
3509 }
3510 @Override public void flush() {}
3511 @Override public void close() {}
3512 })) {
3513 mNetworkRequestInfoLogs.dump(logPw);
3514 }
3515 }
3516
Hugo Benichia480ba52018-09-03 08:19:02 +09003517 /**
3518 * Return an array of all current NetworkAgentInfos sorted by network id.
3519 */
3520 private NetworkAgentInfo[] networksSortedById() {
3521 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003522 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003523 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003524 return networks;
3525 }
3526
3527 /**
3528 * Return an array of all current NetworkRequest sorted by request id.
3529 */
James Mattis258ea3c2020-11-15 15:04:40 -08003530 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003531 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003532 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003533 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003534 // Sort the array based off the NRI containing the min requestId in its requests.
3535 Arrays.sort(requests,
3536 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3537 Comparator.comparingInt(req -> req.requestId)).requestId
3538 )
3539 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003540 return requests;
3541 }
3542
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003543 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003544 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003545 if (officialNai != null && officialNai.equals(nai)) return true;
3546 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003547 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003548 " - " + nai);
3549 }
3550 return false;
3551 }
3552
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003553 private boolean isDisconnectRequest(Message msg) {
3554 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3555 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3556 return info.getState() == NetworkInfo.State.DISCONNECTED;
3557 }
3558
Robert Greenwalt2034b912009-08-12 16:08:25 -07003559 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003560 private class NetworkStateTrackerHandler extends Handler {
3561 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003562 super(looper);
3563 }
3564
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003565 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003566 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3567 final NetworkAgentInfo nai = arg.first;
3568 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003569 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003570 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003571 }
3572 return;
3573 }
3574
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003575 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003576 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003577 return;
3578 }
3579
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003580 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003581 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003582 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3583 final NetworkCapabilities sanitized =
3584 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003585 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003586 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003587 break;
3588 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003589 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003590 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003591 processLinkPropertiesFromAgent(nai, newLp);
3592 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003593 break;
3594 }
3595 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003596 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003597 updateNetworkInfo(nai, info);
3598 break;
3599 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003600 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003601 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003602 break;
3603 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003604 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003605 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003606 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003607 // Note that if the NAI had been connected, this would affect the
3608 // score, and therefore would require re-mixing the score and performing
3609 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003610 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003611 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3612 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003613 // Mark the network as temporarily accepting partial connectivity so that it
3614 // will be validated (and possibly become default) even if it only provides
3615 // partial internet access. Note that if user connects to partial connectivity
3616 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3617 // out of wifi coverage) and if the same wifi is available again, the device
3618 // will auto connect to this wifi even though the wifi has "no internet".
3619 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003620 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003621 break;
3622 }
junyulai011b1f12019-01-03 18:50:15 +08003623 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003624 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003625 break;
3626 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003627 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003628 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003629 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003630
3631 if (isLegacyLockdownNai(nai)
3632 && (underlying == null || underlying.size() != 1)) {
3633 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3634 + " must have exactly one underlying network: " + underlying);
3635 }
3636
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003637 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3638 nai.declaredUnderlyingNetworks = (underlying != null)
3639 ? underlying.toArray(new Network[0]) : null;
3640
3641 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3642 if (DBG) {
3643 log(nai.toShortString() + " changed underlying networks to "
3644 + Arrays.toString(nai.declaredUnderlyingNetworks));
3645 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003646 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003647 notifyIfacesChangedForNetworkStats();
3648 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003649 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003650 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003651 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3652 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3653 nai.teardownDelayMs = msg.arg1;
3654 } else {
3655 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3656 }
Chalard Jean550b5212021-03-05 23:07:53 +09003657 break;
3658 }
3659 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3660 nai.setLingerDuration((int) arg.second);
3661 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003662 }
Tyler Wear72388212021-09-09 14:49:02 -07003663 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3664 DscpPolicy policy = (DscpPolicy) arg.second;
3665 if (mDscpPolicyTracker != null) {
3666 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3667 }
3668 break;
3669 }
3670 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3671 if (mDscpPolicyTracker != null) {
3672 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3673 }
3674 break;
3675 }
3676 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3677 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003678 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003679 }
3680 break;
3681 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003682 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003683 if (!nai.isCreated()) {
3684 Log.d(TAG, "unregisterAfterReplacement on uncreated " + nai.toShortString()
3685 + ", tearing down instead");
3686 teardownUnneededNetwork(nai);
3687 break;
3688 }
3689
3690 if (nai.isDestroyed()) {
3691 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3692 + ", ignoring");
3693 break;
3694 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003695
3696 final int timeoutMs = (int) arg.second;
3697 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3698 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3699 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3700 }
3701
3702 // Marking a network awaiting replacement is used to ensure that any requests
3703 // satisfied by the network do not switch to another network until a
3704 // replacement is available or the wait for a replacement times out.
3705 // If the network is inactive (i.e., nascent or lingering), then there are no
3706 // such requests, and there is no point keeping it. Just tear it down.
3707 // Note that setLingerDuration(0) cannot be used to do this because the network
3708 // could be nascent.
3709 nai.clearInactivityState();
3710 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3711 Log.d(TAG, nai.toShortString()
3712 + " marked awaiting replacement is unneeded, tearing down instead");
3713 teardownUnneededNetwork(nai);
3714 break;
3715 }
3716
3717 Log.d(TAG, "Marking " + nai.toShortString()
3718 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3719 destroyNativeNetwork(nai);
3720
3721 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3722 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3723 // consider the fact that the network could already have disconnected or been
3724 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3725 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3726 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3727 mKeepaliveTracker.handleStopAllKeepalives(nai,
3728 SocketKeepalive.ERROR_INVALID_NETWORK);
3729
3730 nai.updateScoreForNetworkAgentUpdate();
3731 // This rematch is almost certainly not going to result in any changes, because
3732 // the destroyed flag is only just above the "current satisfier wins"
3733 // tie-breaker. But technically anything that affects scoring should rematch.
3734 rematchAllNetworksAndRequests();
3735 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3736 break;
3737 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003738 }
3739 }
3740
3741 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003742 final int netId = msg.arg2;
3743 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003744 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003745 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003746 switch (msg.what) {
3747 default:
3748 return false;
lucasline117e2e2019-10-22 18:27:33 +08003749 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003750 if (nai == null) {
3751 break;
3752 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003753 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3754 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003755 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003756 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003757 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003758 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003759 if (probePrivateDnsCompleted) {
3760 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3761 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003762 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003763 }
3764 // Only show the notification when the private DNS is broken and the
3765 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003766 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003767 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3768 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003769 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003770 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3771 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3772 // private DNS is broken, it means this network is being reevaluated.
3773 // Either probing private DNS is not necessary any more or it hasn't been
3774 // done yet. In either case, the networkCapabilities should be updated to
3775 // reflect the new status.
3776 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003777 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003778 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003779 }
3780 break;
3781 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003782 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003783 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3784
Erik Kline31b4a9e2018-01-11 21:07:29 +09003785 if (nai == null) break;
3786
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003787 handleNetworkTested(nai, results.mTestResult,
3788 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003789 break;
3790 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003791 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003792 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003793 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003794 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003795 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003796 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003797 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3798 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003799 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003800 if (nai == null) {
3801 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3802 break;
3803 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003804 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003805 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003806 (PendingIntent) msg.obj,
3807 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003808 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003809 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003810 break;
3811 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003812 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003813 if (nai == null) break;
3814
Erik Kline9a62f012018-03-21 07:18:33 -07003815 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003816 break;
3817 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003818 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003819 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003820 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003821 break;
3822 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003823 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003824 return true;
3825 }
3826
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003827 private void handleNetworkTested(
3828 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003829 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3830 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003831 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003832
3833 // If there is any kind of working networking, then the NAI has been evaluated
3834 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3835 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003836 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003837 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003838 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3839 // any callback that receives onAvailable for that rematch receives an extra caps
3840 // callback. To prevent that, update the score in the agent so the updates below won't
3841 // see an update to both caps and score at the same time.
3842 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003843 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3844
he_won.hwang881307a2022-03-15 21:23:52 +09003845 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3846 // Assume the validation failure is due to a temporary failure after roaming
3847 // and ignore it. NetworkMonitor will continue to retry validation. If it
3848 // continues to fail after the block timeout expires, the network will be
3849 // marked unvalidated. If it succeeds, then validation state will not change.
3850 return;
3851 }
3852
Chalard Jean254bd162022-08-25 13:04:51 +09003853 final boolean wasValidated = nai.isValidated();
3854 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003855 final boolean wasPortal = nai.captivePortalDetected();
3856 nai.setPartialConnectivity(partial);
3857 nai.setCaptivePortalDetected(portal);
3858 nai.updateScoreForNetworkAgentUpdate();
3859 final boolean partialConnectivityChanged = (wasPartial != partial);
3860 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003861
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003862 if (DBG) {
3863 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3864 ? " with redirect to " + redirectUrl
3865 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003866 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003867 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003868 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003869 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003870 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003871 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003872 if (valid) {
3873 handleFreshlyValidatedNetwork(nai);
3874 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3875 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003876 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003877 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003878 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003879 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003880 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003881 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003882 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003883 NotificationType.PRIVATE_DNS_BROKEN);
3884 // If network becomes valid, the hasShownBroken should be reset for
3885 // that network so that the notification will be fired when the private
3886 // DNS is broken again.
3887 nai.networkAgentConfig.hasShownBroken = false;
3888 }
3889 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003890 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09003891 } else if (portalChanged) {
3892 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3893 == getCaptivePortalMode()) {
3894 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3895 nai.onPreventAutomaticReconnect();
3896 teardownUnneededNetwork(nai);
3897 return;
3898 } else {
3899 updateCapabilitiesForNetwork(nai);
3900 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09003901 } else if (becameEvaluated) {
3902 // If valid or partial connectivity changed, updateCapabilities* has
3903 // done the rematch.
3904 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003905 }
3906 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003907
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003908 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003909 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003910 nai.onValidationStatusChanged(
3911 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3912 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003913
3914 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003915 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003916 // immediately. Re-notify partial connectivity silently if no internet
3917 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003918 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003919 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003920 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
3921 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003922 }
3923
Chalard Jean254bd162022-08-25 13:04:51 +09003924 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003925 handleNetworkUnvalidated(nai);
3926 }
3927 }
3928
Calvin Ondada1452016-10-11 15:10:46 -07003929 private int getCaptivePortalMode() {
3930 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003931 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3932 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003933 }
3934
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003935 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3936 switch (msg.what) {
3937 default:
3938 return false;
3939 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3940 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3941 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3942 handleLingerComplete(nai);
3943 }
3944 break;
3945 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003946 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3947 handleNetworkAgentRegistered(msg);
3948 break;
3949 }
3950 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3951 handleNetworkAgentDisconnected(msg);
3952 break;
3953 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003954 }
3955 return true;
3956 }
3957
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003958 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003959 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003960 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003961 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003962 maybeHandleNetworkAgentMessage(msg);
3963 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003964 }
3965 }
3966
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003967 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003968 private final int mNetId;
3969 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003970
3971 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003972 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003973 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003974 }
3975
3976 @Override
3977 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3978 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003979 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003980 }
3981
3982 @Override
3983 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003984 // Legacy version of notifyNetworkTestedWithExtras.
3985 // Would only be called if the system has a NetworkStack module older than the
3986 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003987 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003988 }
3989
3990 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003991 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003992 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3993 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003994 final Message msg = mTrackerHandler.obtainMessage(
3995 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003996 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003997 new NetworkTestedResults(
3998 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003999 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004000
4001 // Invoke ConnectivityReport generation for this Network test event.
4002 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4003 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004004
Cody Kestingf1120be2020-08-03 18:01:40 -07004005 // NetworkMonitor reports the network validation result as a bitmask while
4006 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4007 // logical value for ConnectivityDiagnostics.
4008 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4009 p.result);
4010
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004011 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004012 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004013 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4014 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4015
Aaron Huang959d3642021-01-21 15:47:41 +08004016 ConnectivityReportEvent reportEvent =
4017 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4018 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004019 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004020 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004021 }
4022
4023 @Override
4024 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4025 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4026 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004027 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004028 }
4029
4030 @Override
lucasline117e2e2019-10-22 18:27:33 +08004031 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4032 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4033 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004034 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004035 }
4036
4037 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004038 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4039 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4040 EVENT_CAPPORT_DATA_CHANGED,
4041 0, mNetId, data));
4042 }
4043
4044 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004045 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004046 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004047 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004048
4049 final PendingIntent pendingIntent;
4050 // Only the system server can register notifications with package "android"
4051 final long token = Binder.clearCallingIdentity();
4052 try {
paulhu7746e4e2020-06-09 19:07:03 +08004053 pendingIntent = PendingIntent.getBroadcast(
4054 mContext,
4055 0 /* requestCode */,
4056 intent,
4057 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004058 } finally {
4059 Binder.restoreCallingIdentity(token);
4060 }
4061 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4062 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004063 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004064 }
4065
4066 @Override
4067 public void hideProvisioningNotification() {
4068 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004069 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004070 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004071
4072 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004073 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004074 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004075 }
4076
4077 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004078 public int getInterfaceVersion() {
4079 return this.VERSION;
4080 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004081
4082 @Override
4083 public String getInterfaceHash() {
4084 return this.HASH;
4085 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004086 }
4087
Cody Kestingf1120be2020-08-03 18:01:40 -07004088 /**
4089 * Converts the given NetworkMonitor-specific validation result bitmask to a
4090 * ConnectivityDiagnostics-specific validation result int.
4091 */
4092 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4093 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4094 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4095 }
4096 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4097 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4098 }
4099 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4100 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4101 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4102 }
4103
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004104 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004105 log("Data stall detected with methods: " + p.detectionMethod);
4106
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004107 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004108 int detectionMethod = 0;
4109 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4110 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4111 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4112 }
4113 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4114 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4115 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4116 p.tcpMetricsCollectionPeriodMillis);
4117 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004118 }
4119
Cody Kestingf53a0752020-04-15 12:33:28 -07004120 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004121 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004122 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004123
4124 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4125 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4126 // the cost of going through two handlers.
4127 mConnectivityDiagnosticsHandler.sendMessage(msg);
4128 }
4129
Cody Kestingb37958e2020-05-15 10:36:01 -07004130 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4131 return (p.detectionMethod & detectionMethod) != 0;
4132 }
4133
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004134 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4135 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004136 }
4137
Erik Klinea73af002018-06-26 18:53:43 +09004138 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4139 if (nai == null) return;
4140 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4141 // in order to restart a validation pass from within netd.
4142 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4143 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004144 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004145 }
4146 }
4147
Erik Kline31b4a9e2018-01-11 21:07:29 +09004148 private void handlePrivateDnsSettingsChanged() {
4149 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4150
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004151 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004152 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004153 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004154 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4155 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004156 }
4157 }
4158
Erik Kline9a62f012018-03-21 07:18:33 -07004159 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4160 // Private DNS only ever applies to networks that might provide
4161 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004162 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004163
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004164 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004165 // schedule DNS resolutions. If a DNS resolution is required the
4166 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004167 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004168
4169 // With Private DNS bypass support, we can proceed to update the
4170 // Private DNS config immediately, even if we're in strict mode
4171 // and have not yet resolved the provider name into a set of IPs.
4172 updatePrivateDns(nai, cfg);
4173 }
4174
4175 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4176 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004177 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004178 }
4179
dalyk1720e542018-03-05 12:42:22 -05004180 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4181 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4182 if (nai == null) {
4183 return;
4184 }
4185 mDnsManager.updatePrivateDnsValidation(update);
4186 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4187 }
4188
paulhu7c0a2e62021-01-08 00:51:49 +08004189 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004190 int prefixLength) {
4191 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4192 if (nai == null) return;
4193
paulhu7c0a2e62021-01-08 00:51:49 +08004194 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4195 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004196
4197 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004198 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004199 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004200 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004201 prefixLength);
4202 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004203 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004204 return;
4205 }
4206 }
4207
Lorenzo Colittid523d142020-04-01 20:16:30 +09004208 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004209 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4210 }
4211
Hai Shalome58bdc62021-01-11 18:45:34 -08004212 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004213 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004214 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004215 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4216 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4217 }
4218
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004219 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004220 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004221 * @param nai the agent info to update
4222 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004223 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004224 */
junyulai2b6f0c22021-02-03 20:15:30 +08004225 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4226 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4227 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004228 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004229 // one lingered request, set inactive.
4230 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004231 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004232 if (DBG) log("Unsetting inactive " + nai.toShortString());
4233 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004234 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004235 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004236 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004237 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4238 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004239 }
junyulai2b6f0c22021-02-03 20:15:30 +08004240 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004241 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004242 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004243 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004244 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004245 }
4246
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004247 private void handleNetworkAgentRegistered(Message msg) {
4248 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4249 if (!mNetworkAgentInfos.contains(nai)) {
4250 return;
4251 }
4252
4253 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4254 if (VDBG) log("NetworkAgent registered");
4255 } else {
4256 loge("Error connecting NetworkAgent");
4257 mNetworkAgentInfos.remove(nai);
4258 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004259 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004260 synchronized (mNetworkForNetId) {
4261 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004262 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004263 mNetIdManager.releaseNetId(nai.network.getNetId());
4264 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004265 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004266 }
4267 }
4268 }
Paul Jensend5f53392014-11-25 15:26:53 -05004269
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004270 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004271 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004272 }
4273
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004274 @VisibleForTesting
4275 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004276 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004277 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004278
4279 // If the network never roamed, return false. The check below is not sufficient if time
4280 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4281 if (nai.lastRoamTime == 0) return false;
4282
he_won.hwang881307a2022-03-15 21:23:52 +09004283 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4284 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004285 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004286 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004287 final long currentTimeMs = SystemClock.elapsedRealtime();
4288 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004289 if (timeSinceLastRoam <= blockTimeOut) {
4290 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4291 return true;
4292 }
4293 }
4294 return false;
4295 }
4296
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004297 private void handleNetworkAgentDisconnected(Message msg) {
4298 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004299 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004300 }
4301
Chalard Jeand9fffc32018-05-11 20:19:20 +09004302 // Destroys a network, remove references to it from the internal state managed by
4303 // ConnectivityService, free its interfaces and clean up.
4304 // Must be called on the Handler thread.
4305 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004306 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004307
4308 if (!mNetworkAgentInfos.contains(nai)) return;
4309
Chalard Jeand9fffc32018-05-11 20:19:20 +09004310 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004311 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004312 }
lucaslinb25c9a62019-02-12 15:30:13 +08004313 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004314 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004315 // A network agent has disconnected.
4316 // TODO - if we move the logic to the network agent (have them disconnect
4317 // because they lost all their requests or because their score isn't good)
4318 // then they would disconnect organically, report their new state and then
4319 // disconnect the channel.
4320 if (nai.networkInfo.isConnected()) {
4321 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4322 null, null);
4323 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004324 final boolean wasDefault = isDefaultNetwork(nai);
4325 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004326 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004327 }
4328 notifyIfacesChangedForNetworkStats();
4329 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4330 // by other networks that are already connected. Perhaps that can be done by
4331 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4332 // of rematchAllNetworksAndRequests
4333 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004334 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004335
4336 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004337 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4338 // Disable wakeup packet monitoring for each interface.
4339 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4340 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004341 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004342 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004343 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004344 synchronized (mNetworkForNetId) {
4345 // Remove the NetworkAgent, but don't mark the netId as
4346 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004347 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004348 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004349 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004350 // Remove all previously satisfied requests.
4351 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004352 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004353 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004354 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004355 if (currentNetwork != null
4356 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004357 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004358 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4359 // rematch not to keep disconnected agents instead of setting it here ; this
4360 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004361 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004362 for (final NetworkOfferInfo noi : mNetworkOffers) {
4363 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004364 }
James Mattise3ef1912020-12-20 11:09:58 -08004365
Chalard Jean5b409c72021-02-04 13:12:59 +09004366 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004367 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004368 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004369 // network, because while incorrect this is the closest to the old (also
4370 // incorrect) behavior.
4371 mNetworkActivityTracker.updateDataActivityTracking(
4372 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004373 ensureNetworkTransitionWakelock(nai.toShortString());
4374 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004375 }
4376 }
junyulai2b6f0c22021-02-03 20:15:30 +08004377 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004378 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004379 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004380 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004381 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004382 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004383 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004384
4385 // Immediate teardown.
4386 if (nai.teardownDelayMs == 0) {
4387 destroyNetwork(nai);
4388 return;
4389 }
4390
4391 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004392 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304393 try {
4394 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4395 } catch (RemoteException e) {
4396 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4397 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004398 }
4399 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4400 }
4401
4402 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004403 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004404 // Tell netd to clean up the configuration for this network
4405 // (routing rules, DNS, etc).
4406 // This may be slow as it requires a lot of netd shelling out to ip and
4407 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004408 // after we've rematched networks with requests (which might change the default
4409 // network or service a new request from an app), so network traffic isn't interrupted
4410 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004411 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004412 }
Chalard Jean254bd162022-08-25 13:04:51 +09004413 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004414 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4415 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4416 // false if the network was never created.
4417 // TODO: delete when S is no longer supported.
4418 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004419 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004420 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004421 }
4422
Ken Chen6df7a902021-04-09 15:08:42 +08004423 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004424 try {
4425 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004426 final NativeNetworkConfig config;
4427 if (nai.isVPN()) {
4428 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004429 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004430 return false;
4431 }
4432 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4433 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004434 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004435 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004436 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004437 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004438 getNetworkPermission(nai.networkCapabilities),
4439 false /* secure */,
4440 VpnManager.TYPE_VPN_NONE,
4441 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004442 }
Ken Chen6df7a902021-04-09 15:08:42 +08004443 mNetd.networkCreate(config);
4444 mDnsResolver.createNetworkCache(nai.network.getNetId());
4445 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4446 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004447 return true;
4448 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004449 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004450 return false;
4451 }
4452 }
4453
Ken Chen6df7a902021-04-09 15:08:42 +08004454 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004455 if (mDscpPolicyTracker != null) {
4456 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4457 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004458 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004459 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004460 } catch (RemoteException | ServiceSpecificException e) {
4461 loge("Exception destroying network(networkDestroy): " + e);
4462 }
4463 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004464 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004465 } catch (RemoteException | ServiceSpecificException e) {
4466 loge("Exception destroying network: " + e);
4467 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004468 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4469 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4470 // gets created, could add data to DnsManager data structures that will never get deleted.
4471 mDnsManager.removeNetwork(nai.network);
4472
4473 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004474 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004475 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4476 }
4477
Chalard Jean254bd162022-08-25 13:04:51 +09004478 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004479 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004480 }
4481
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004482 // If this method proves to be too slow then we can maintain a separate
4483 // pendingIntent => NetworkRequestInfo map.
4484 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4485 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004486 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4487 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4488 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004489 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004490 return entry.getValue();
4491 }
4492 }
4493 return null;
4494 }
4495
Chalard Jean524f0b12021-10-25 21:11:56 +09004496 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4497 if (SdkLevel.isAtLeastT()) {
4498 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4499 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4500 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4501 // bug is fixed.
4502 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004503 throw new IllegalStateException("This NRI is already registered. New : " + nri
4504 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004505 }
4506 }
4507 }
4508 }
4509
Chalard Jeanac9ace02022-01-26 16:54:05 +09004510 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4511 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004512 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004513 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4514 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004515 }
4516 return false;
4517 }
4518
James Mattisf7027322020-12-13 16:28:14 -08004519 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004520 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004521 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4522 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4523 final NetworkRequestInfo existingRequest =
4524 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004525 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004526 if (DBG) {
4527 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4528 + nri.mRequests.get(0) + " because their intents matched.");
4529 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004530 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004531 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004532 }
Erik Kline05f2b402015-04-30 12:58:40 +09004533 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004534 }
4535
James Mattisf7027322020-12-13 16:28:14 -08004536 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004537 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004538 }
4539
James Mattis3ce3d3c2021-02-09 18:18:28 -08004540 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004541 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004542 for (final NetworkRequestInfo nri : nris) {
4543 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004544 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004545 for (final NetworkRequest req : nri.mRequests) {
4546 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004547 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004548 if (req.isListen()) {
4549 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4550 if (req.networkCapabilities.hasSignalStrength()
4551 && network.satisfiesImmutableCapabilitiesOf(req)) {
4552 updateSignalStrengthThresholds(network, "REGISTER", req);
4553 }
James Mattisf7027322020-12-13 16:28:14 -08004554 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004555 }
4556 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004557
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004558 // If this NRI has a satisfier already, it is replacing an older request that
4559 // has been removed. Track it.
4560 final NetworkRequest activeRequest = nri.getActiveRequest();
4561 if (null != activeRequest) {
4562 // If there is an active request, then for sure there is a satisfier.
4563 nri.getSatisfier().addRequest(activeRequest);
4564 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004565 }
James Mattisf7027322020-12-13 16:28:14 -08004566
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004567 if (mFlags.noRematchAllRequestsOnRegister()) {
4568 rematchNetworksAndRequests(nris);
4569 } else {
4570 rematchAllNetworksAndRequests();
4571 }
James Mattis45d81842021-01-10 14:24:24 -08004572
Chalard Jean0354d8c2021-01-12 10:58:56 +09004573 // Requests that have not been matched to a network will not have been sent to the
4574 // providers, because the old satisfier and the new satisfier are the same (null in this
4575 // case). Send these requests to the providers.
4576 for (final NetworkRequestInfo nri : nris) {
4577 for (final NetworkOfferInfo noi : mNetworkOffers) {
4578 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004579 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004580 }
4581 }
4582
James Mattisf7027322020-12-13 16:28:14 -08004583 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4584 final int callingUid) {
4585 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004586 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004587 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4588 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4589 handleReleaseNetworkRequest(
4590 nri.mRequests.get(0),
4591 callingUid,
4592 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004593 }
4594 }
4595
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004596 // Determines whether the network is the best (or could become the best, if it validated), for
4597 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4598 // on the value of reason:
4599 //
4600 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4601 // then it should be torn down.
4602 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4603 // then it should be lingered.
4604 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004605 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004606
Chalard Jean254bd162022-08-25 13:04:51 +09004607 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004608 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4609 return false;
4610 }
4611
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004612 final int numRequests;
4613 switch (reason) {
4614 case TEARDOWN:
4615 numRequests = nai.numRequestNetworkRequests();
4616 break;
4617 case LINGER:
4618 numRequests = nai.numForegroundNetworkRequests();
4619 break;
4620 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004621 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004622 return true;
4623 }
4624
Chalard Jean947acd42021-03-08 22:29:27 +09004625 if (numRequests > 0) return false;
4626
Paul Jensende49eb12015-06-25 15:30:08 -04004627 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004628 if (reason == UnneededFor.LINGER
4629 && !nri.isMultilayerRequest()
4630 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004631 // Background requests don't affect lingering.
4632 continue;
4633 }
4634
James Mattis3d229892020-11-16 16:46:28 -08004635 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004636 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004637 }
4638 }
Paul Jensende49eb12015-06-25 15:30:08 -04004639 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004640 }
4641
James Mattis3d229892020-11-16 16:46:28 -08004642 private boolean isNetworkPotentialSatisfier(
4643 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4644 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004645 // request, return immediately. For multilayer requests, check to see if any of the
4646 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004647 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4648 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004649 return false;
4650 }
4651 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004652 // This multilayer listen request is satisfied therefore no further requests need to be
4653 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004654 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004655 return false;
4656 }
James Mattis3d229892020-11-16 16:46:28 -08004657 // As non-multilayer listen requests have already returned, the below would only happen
4658 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004659 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004660 continue;
4661 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004662 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004663 // there is hope for it to become one if it validated, then it is needed.
4664 if (candidate.satisfies(req)) {
4665 // As soon as a network is found that satisfies a request, return. Specifically for
4666 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4667 // is important so as to not evaluate lower priority requests further in
4668 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004669 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4670 ? nri.getSatisfier() : null;
4671 // Note that this catches two important cases:
4672 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4673 // is currently satisfying the request. This is desirable when
4674 // cellular ends up validating but WiFi does not.
4675 // 2. Unvalidated WiFi will not be reaped when validated cellular
4676 // is currently satisfying the request. This is desirable when
4677 // WiFi ends up validating and out scoring cellular.
4678 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004679 }
4680 }
4681
4682 return false;
4683 }
4684
Erik Kline0c04b742016-07-07 16:50:58 +09004685 private NetworkRequestInfo getNriForAppRequest(
4686 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004687 // Looking up the app passed param request in mRequests isn't possible since it may return
4688 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4689 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004690 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4691 // to avoid potential race conditions when validating a package->uid mapping when sending
4692 // the callback on the very low-chance that an application shuts down prior to the callback
4693 // being sent.
4694 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4695 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004696
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004697 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004698 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004699 log(String.format("UID %d attempted to %s for unowned request %s",
4700 callingUid, requestedOperation, nri));
4701 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004702 }
Erik Kline0c04b742016-07-07 16:50:58 +09004703 }
4704
4705 return nri;
4706 }
4707
James Mattisf7027322020-12-13 16:28:14 -08004708 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4709 final String callingMethod) {
4710 if (nri.isMultilayerRequest()) {
4711 throw new IllegalStateException(
4712 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004713 }
4714 }
4715
James Mattisf7027322020-12-13 16:28:14 -08004716 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004717 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004718 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4719 // single NetworkRequest and thus does not apply to multilayer requests.
4720 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4721 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004722 return;
4723 }
James Mattis2516da32021-01-31 17:06:19 -08004724 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004725 return;
4726 }
James Mattisf7027322020-12-13 16:28:14 -08004727 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4728 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004729 }
4730 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004731 callCallbackForRequest(
4732 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004733 }
4734
James Mattisf7027322020-12-13 16:28:14 -08004735 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4736 final int callingUid,
4737 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004738 final NetworkRequestInfo nri =
4739 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4740 if (nri == null) {
4741 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004742 }
James Mattisf7027322020-12-13 16:28:14 -08004743 if (VDBG || (DBG && request.isRequest())) {
4744 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004745 }
4746 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004747 if (callOnUnavailable) {
4748 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4749 }
Erik Kline155a59a2015-11-25 12:49:38 +09004750 }
Erik Kline0c04b742016-07-07 16:50:58 +09004751
James Mattisa076c532020-12-02 14:12:41 -08004752 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004753 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004754 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004755 if (null == mNetworkRequests.remove(req)) {
4756 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4757 continue;
4758 }
James Mattisa076c532020-12-02 14:12:41 -08004759 if (req.isListen()) {
4760 removeListenRequestFromNetworks(req);
4761 }
4762 }
James Mattis8f036802021-06-20 16:26:01 -07004763 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004764 if (mDefaultNetworkRequests.remove(nri)) {
4765 // If this request was one of the defaults, then the UID rules need to be updated
4766 // WARNING : if the app(s) for which this network request is the default are doing
4767 // traffic, this will kill their connected sockets, even if an equivalent request
4768 // is going to be reinstated right away ; unconnected traffic will go on the default
4769 // until the new default is set, which will happen very soon.
4770 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4771 // remove ranges for those requests that won't have a replacement
4772 final NetworkAgentInfo satisfier = nri.getSatisfier();
4773 if (null != satisfier) {
4774 try {
paulhu0e79d952021-06-09 16:11:35 +08004775 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4776 satisfier.network.getNetId(),
4777 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004778 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004779 } catch (RemoteException e) {
4780 loge("Exception setting network preference default network", e);
4781 }
4782 }
4783 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004784 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004785 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004786 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004787
4788 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004789 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004790 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004791 }
4792 }
4793
Chalard Jean0354d8c2021-01-12 10:58:56 +09004794 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4795 // needed for this offer.
4796 for (final NetworkOfferInfo noi : mNetworkOffers) {
4797 for (final NetworkRequest req : nri.mRequests) {
4798 if (req.isRequest() && noi.offer.neededFor(req)) {
4799 noi.offer.onNetworkUnneeded(req);
4800 }
4801 }
4802 }
James Mattisa076c532020-12-02 14:12:41 -08004803 }
4804
James Mattis3ce3d3c2021-02-09 18:18:28 -08004805 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4806 for (final NetworkRequestInfo nri : nris) {
4807 if (mDefaultRequest == nri) {
4808 // Make sure we never remove the default request.
4809 continue;
4810 }
4811 handleRemoveNetworkRequest(nri);
4812 }
4813 }
4814
James Mattisa076c532020-12-02 14:12:41 -08004815 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4816 // listens don't have a singular affected Network. Check all networks to see
4817 // if this listen request applies and remove it.
4818 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4819 nai.removeRequest(req.requestId);
4820 if (req.networkCapabilities.hasSignalStrength()
4821 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4822 updateSignalStrengthThresholds(nai, "RELEASE", req);
4823 }
4824 }
4825 }
4826
4827 /**
4828 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4829 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4830 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4831 */
4832 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4833 boolean wasKept = false;
4834 final NetworkAgentInfo nai = nri.getSatisfier();
4835 if (nai != null) {
4836 final int requestLegacyType = nri.getActiveRequest().legacyType;
4837 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4838 nai.removeRequest(nri.getActiveRequest().requestId);
4839 if (VDBG || DDBG) {
4840 log(" Removing from current network " + nai.toShortString()
4841 + ", leaving " + nai.numNetworkRequests() + " requests.");
4842 }
4843 // If there are still lingered requests on this network, don't tear it down,
4844 // but resume lingering instead.
4845 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004846 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004847 notifyNetworkLosing(nai, now);
4848 }
4849 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4850 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4851 teardownUnneededNetwork(nai);
4852 } else {
4853 wasKept = true;
4854 }
James Mattisa076c532020-12-02 14:12:41 -08004855 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4856 // Went from foreground to background.
4857 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004858 }
4859
Erik Kline0c04b742016-07-07 16:50:58 +09004860 // Maintain the illusion. When this request arrived, we might have pretended
4861 // that a network connected to serve it, even though the network was already
4862 // connected. Now that this request has gone away, we might have to pretend
4863 // that the network disconnected. LegacyTypeTracker will generate that
4864 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004865 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004866 boolean doRemove = true;
4867 if (wasKept) {
4868 // check if any of the remaining requests for this network are for the
4869 // same legacy type - if so, don't remove the nai
4870 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4871 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004872 if (otherRequest.legacyType == requestLegacyType
4873 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004874 if (DBG) log(" still have other legacy request - leaving");
4875 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004876 }
4877 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004878 }
4879
Erik Kline0c04b742016-07-07 16:50:58 +09004880 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004881 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004882 }
4883 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004884 }
4885 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004886
Junyu Lai00d92df2022-07-05 11:01:52 +08004887 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004888 return checkAnyPermissionOf(
4889 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4890 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4891 }
4892
Lorenzo Colittid6459092016-07-04 12:55:44 +09004893 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004894 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004895 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004896 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004897 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004898 }
4899
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004900 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004901 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4902 enforceNetworkStackSettingsOrSetup();
4903 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4904 encodeBool(accept), encodeBool(always), network));
4905 }
4906
4907 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004908 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004909 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004910 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4911 }
4912
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004913 @Override
4914 public void setTestAllowBadWifiUntil(long timeMs) {
4915 enforceSettingsPermission();
4916 if (!Build.isDebuggable()) {
4917 throw new IllegalStateException("Does not support in non-debuggable build");
4918 }
4919
4920 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4921 throw new IllegalArgumentException("It should not exceed "
4922 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4923 }
4924
4925 mHandler.sendMessage(
4926 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4927 }
4928
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004929 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4930 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4931 " accept=" + accept + " always=" + always);
4932
4933 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4934 if (nai == null) {
4935 // Nothing to do.
4936 return;
4937 }
4938
Chalard Jean254bd162022-08-25 13:04:51 +09004939 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004940 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004941 return;
4942 }
4943
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004944 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004945 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004946 }
4947
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004948 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4949 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004950 // If network becomes partial connectivity and user already accepted to use this
4951 // network, we should respect the user's option and don't need to popup the
4952 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004953 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004954 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004955 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004956 }
4957
4958 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004959 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004960 }
4961
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004962 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004963 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004964 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004965 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004966 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004967 }
4968
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004969 }
4970
lucaslin2240ef62019-03-12 13:08:03 +08004971 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4972 boolean always) {
4973 if (DBG) {
4974 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4975 + " always=" + always);
4976 }
4977
4978 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4979 if (nai == null) {
4980 // Nothing to do.
4981 return;
4982 }
4983
Chalard Jean254bd162022-08-25 13:04:51 +09004984 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004985 // The network validated while the dialog box was up. Take no action.
4986 return;
4987 }
4988
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004989 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4990 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004991 }
4992
4993 // TODO: Use the current design or save the user choice into IpMemoryStore.
4994 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004995 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004996 }
4997
4998 if (!accept) {
4999 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005000 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005001 // Tear down the network.
5002 teardownUnneededNetwork(nai);
5003 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005004 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5005 // result in a partial connectivity result which will be processed by
5006 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005007 //
5008 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5009 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005010 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005011 }
5012 }
5013
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005014 private void handleSetAvoidUnvalidated(Network network) {
5015 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005016 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005017 // Nothing to do. The network either disconnected or revalidated.
5018 return;
5019 }
Chalard Jean254bd162022-08-25 13:04:51 +09005020 if (0L == nai.getAvoidUnvalidated()) {
5021 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005022 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005023 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005024 }
5025 }
5026
Chalard Jean5fb43c72022-09-08 19:03:14 +09005027 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005028 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005029 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005030 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005031 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005032 }
5033
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005034 @Override
5035 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005036 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005037 mHandler.post(() -> {
5038 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5039 if (nai == null) return;
5040 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005041 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005042 });
5043 }
5044
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005045 /**
5046 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5047 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005048 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005049 * @param appExtras Bundle to use as intent extras for the captive portal application.
5050 * Must be treated as opaque to avoid preventing the captive portal app to
5051 * update its arguments.
5052 */
5053 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005054 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005055 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5056 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005057
5058 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5059 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005060 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5061 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005062 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5063
lucaslin75ff7022020-12-17 04:14:35 +08005064 final long token = Binder.clearCallingIdentity();
5065 try {
5066 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5067 } finally {
5068 Binder.restoreCallingIdentity(token);
5069 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005070 }
5071
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005072 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5073 private final Network mNetwork;
5074
5075 private CaptivePortalImpl(Network network) {
5076 mNetwork = network;
5077 }
5078
5079 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005080 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005081 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5082 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005083 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5084 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5085 // Since the network will be disconnected, skip notifying NetworkMonitor
5086 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005087 }
5088
Chiachang Wang938bfba2020-01-09 13:50:55 +08005089 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005090 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005091 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005092 }
5093
5094 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005095 public void appRequest(final int request) {
5096 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5097 if (nm == null) return;
5098
5099 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005100 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005101 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005102 }
5103 }
5104
5105 @Nullable
5106 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5107 // getNetworkAgentInfoForNetwork is thread-safe
5108 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5109 if (nai == null) return null;
5110
5111 // nai.networkMonitor() is thread-safe
5112 return nai.networkMonitor();
5113 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005114 }
5115
Hugo Benichic9048bc2016-09-14 23:23:08 +00005116 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005117 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005118 }
5119
Chalard Jean020b93a2022-09-01 13:20:14 +09005120 private boolean activelyPreferBadWifi() {
5121 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5122 }
5123
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005124 /**
5125 * Return whether the device should maintain continuous, working connectivity by switching away
5126 * from WiFi networks having no connectivity.
5127 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5128 */
5129 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005130 if (!checkNetworkStackPermission()) {
5131 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5132 }
5133 return avoidBadWifi();
5134 }
5135
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005136 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005137 ensureRunningOnConnectivityServiceThread();
5138 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005139 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005140 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005141 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005142 if (avoidBadWifi) {
5143 // If the device is now avoiding bad wifi, remove notifications that might have
5144 // been put up when the device didn't.
5145 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5146 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005147 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005148 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5149 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5150 for (final NetworkOfferInfo noi : offersToUpdate) {
5151 updateOfferScore(noi.offer);
5152 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005153 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005154 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005155 }
5156
Erik Kline95ecfee2016-10-02 18:02:14 +09005157 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005158 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005159 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005160 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005161 if (!configRestrict) {
5162 pw.println("Bad Wi-Fi avoidance: unrestricted");
5163 return;
5164 }
5165
5166 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5167 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005168 pw.println("Config restrict: " + configRestrict);
5169 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005170
Chalard Jeane0fdea32022-09-14 21:44:22 +09005171 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005172 String description;
5173 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005174 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005175 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005176 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005177 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005178 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005179 description = "avoid";
5180 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005181 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005182 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005183 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005184
5185 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5186 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005187 if (null == configValue) {
5188 description = "unset";
5189 } else if (configValue) {
5190 description = "force true";
5191 } else {
5192 description = "force false";
5193 }
5194 pw.println("Actively prefer bad wifi conf: " + description);
5195 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005196 pw.println("Network overrides:");
5197 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005198 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005199 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005200 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005201 }
5202 }
5203 pw.decreaseIndent();
5204 pw.decreaseIndent();
5205 }
5206
paulhu7746e4e2020-06-09 19:07:03 +08005207 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5208 // unify the method.
5209 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5210 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5211 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5212 return settingsComponent != null
5213 ? settingsComponent.getPackageName() : "com.android.settings";
5214 }
5215
lucaslinb1e8e382019-01-24 15:55:30 +08005216 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005217 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005218 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005219 switch (type) {
5220 case NO_INTERNET:
5221 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005222 // High priority because it is only displayed for explicitly selected networks.
5223 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005224 break;
lucasline117e2e2019-10-22 18:27:33 +08005225 case PRIVATE_DNS_BROKEN:
5226 action = Settings.ACTION_WIRELESS_SETTINGS;
5227 // High priority because we should let user know why there is no internet.
5228 highPriority = true;
5229 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005230 case LOST_INTERNET:
5231 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005232 // High priority because it could help the user avoid unexpected data usage.
5233 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005234 break;
lucaslin2240ef62019-03-12 13:08:03 +08005235 case PARTIAL_CONNECTIVITY:
5236 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005237 // Don't bother the user with a high-priority notification if the network was not
5238 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005239 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005240 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005241 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005242 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005243 return;
5244 }
5245
5246 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005247 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005248 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005249 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005250 // Some OEMs have their own Settings package. Thus, need to get the current using
5251 // Settings package name instead of just use default name "com.android.settings".
5252 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5253 intent.setClassName(settingsPkgName,
5254 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005255 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005256
paulhu2af50222020-10-11 22:52:27 +08005257 PendingIntent pendingIntent = PendingIntent.getActivity(
5258 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005259 0 /* requestCode */,
5260 intent,
paulhu2af50222020-10-11 22:52:27 +08005261 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005262
Serik Beketayevec8ad212020-12-07 22:43:07 -08005263 mNotifier.showNotification(
5264 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005265 }
5266
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005267 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5268 // Don't prompt if the network is validated, and don't prompt on captive portals
5269 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005270 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005271 return false;
5272 }
5273
5274 // If a network has partial connectivity, always prompt unless the user has already accepted
5275 // partial connectivity and selected don't ask again. This ensures that if the device
5276 // automatically connects to a network that has partial Internet access, the user will
5277 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005278 // because we have prompted them.
5279 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005280 return true;
5281 }
5282
5283 // If a network has no Internet access, only prompt if the network was explicitly selected
5284 // and if the user has not already told us to use the network regardless of whether it
5285 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005286 if (nai.networkAgentConfig.explicitlySelected
5287 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005288 return true;
5289 }
5290
5291 return false;
5292 }
5293
Chalard Jean5fb43c72022-09-08 19:03:14 +09005294 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5295 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005296
Chalard Jean5fb43c72022-09-08 19:03:14 +09005297 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5298 if (null == nai) return;
5299
5300 if (nai.setEvaluated()) {
5301 // If setEvaluated() returned true, the network never had any form of connectivity.
5302 // This may have an impact on request matching if bad WiFi avoidance is off and the
5303 // network was found not to have Internet access.
5304 nai.updateScoreForNetworkAgentUpdate();
5305 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005306
5307 // Also, if this is WiFi and it should be preferred actively, now is the time to
5308 // prompt the user that they walked past and connected to a bad WiFi.
5309 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5310 && !avoidBadWifi()
5311 && activelyPreferBadWifi()) {
5312 // The notification will be removed if the network validates or disconnects.
5313 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5314 return;
5315 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005316 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005317
Chalard Jean5fb43c72022-09-08 19:03:14 +09005318 if (!shouldPromptUnvalidated(nai)) return;
5319
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005320 // Stop automatically reconnecting to this network in the future. Automatically connecting
5321 // to a network that provides no or limited connectivity is not useful, because the user
5322 // cannot use that network except through the notification shown by this method, and the
5323 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005324 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005325
Chalard Jean254bd162022-08-25 13:04:51 +09005326 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005327 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005328 } else {
5329 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5330 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005331 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005332
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005333 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5334 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005335 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005336
lucaslin2240ef62019-03-12 13:08:03 +08005337 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5338 return;
5339 }
5340
5341 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005342 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005343 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005344 }
5345
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005346 @Override
5347 public int getMultipathPreference(Network network) {
5348 enforceAccessPermission();
5349
5350 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005351 if (nai != null && nai.networkCapabilities
5352 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005353 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5354 }
5355
Aaron Huang9a57acf2020-12-08 10:03:29 +08005356 final NetworkPolicyManager netPolicyManager =
5357 mContext.getSystemService(NetworkPolicyManager.class);
5358
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005359 final long token = Binder.clearCallingIdentity();
5360 final int networkPreference;
5361 try {
5362 networkPreference = netPolicyManager.getMultipathPreference(network);
5363 } finally {
5364 Binder.restoreCallingIdentity(token);
5365 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005366 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005367 return networkPreference;
5368 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005369 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5370 }
5371
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005372 @Override
5373 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005374 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005375 }
5376
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005377 private class InternalHandler extends Handler {
5378 public InternalHandler(Looper looper) {
5379 super(looper);
5380 }
5381
5382 @Override
5383 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005384 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005385 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005386 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005387 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005388 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005389 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005390 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005391 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005392 break;
5393 }
Jason Monka69f1b02013-10-10 14:02:51 -04005394 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005395 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5396 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005397 break;
5398 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005399 case EVENT_REGISTER_NETWORK_PROVIDER: {
5400 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005401 break;
5402 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005403 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5404 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005405 break;
5406 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005407 case EVENT_REGISTER_NETWORK_OFFER: {
5408 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5409 break;
5410 }
5411 case EVENT_UNREGISTER_NETWORK_OFFER: {
5412 final NetworkOfferInfo offer =
5413 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5414 if (null != offer) {
5415 handleUnregisterNetworkOffer(offer);
5416 }
5417 break;
5418 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005419 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005420 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5421 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5422 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005423 break;
5424 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005425 case EVENT_REGISTER_NETWORK_REQUEST:
5426 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005427 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005428 break;
5429 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005430 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5431 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005432 handleRegisterNetworkRequestWithIntent(msg);
5433 break;
5434 }
Erik Kline155a59a2015-11-25 12:49:38 +09005435 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5436 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5437 handleTimedOutNetworkRequest(nri);
5438 break;
5439 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005440 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5441 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5442 break;
5443 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005444 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005445 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5446 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005447 break;
5448 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005449 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005450 Network network = (Network) msg.obj;
5451 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005452 break;
5453 }
lucaslin2240ef62019-03-12 13:08:03 +08005454 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5455 Network network = (Network) msg.obj;
5456 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5457 toBool(msg.arg2));
5458 break;
5459 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005460 case EVENT_SET_AVOID_UNVALIDATED: {
5461 handleSetAvoidUnvalidated((Network) msg.obj);
5462 break;
5463 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005464 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5465 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005466 break;
5467 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005468 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5469 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005470 break;
5471 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005472 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005473 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005474 mKeepaliveTracker.handleStartKeepalive(msg);
5475 break;
5476 }
5477 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005478 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005479 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5480 int slot = msg.arg1;
5481 int reason = msg.arg2;
5482 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5483 break;
5484 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005485 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5486 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5487 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005488 break;
5489 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005490 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5491 handlePrivateDnsSettingsChanged();
5492 break;
dalyk1720e542018-03-05 12:42:22 -05005493 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5494 handlePrivateDnsValidationUpdate(
5495 (PrivateDnsValidationUpdate) msg.obj);
5496 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005497 case EVENT_UID_BLOCKED_REASON_CHANGED:
5498 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005499 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005500 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5501 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5502 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005503 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005504 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5505 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005506 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005507 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005508 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005509 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005510 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5511 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005512 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005513 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005514 }
lucaslin1193a5d2021-01-21 02:04:15 +08005515 case EVENT_REPORT_NETWORK_ACTIVITY:
5516 mNetworkActivityTracker.handleReportNetworkActivity();
5517 break;
paulhu51f77dc2021-06-07 02:34:20 +00005518 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5519 handleMobileDataPreferredUidsChanged();
5520 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005521 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5522 final long timeMs = ((Long) msg.obj).longValue();
5523 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5524 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005525 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5526 handleIngressRateLimitChanged();
5527 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005528 case EVENT_USER_DOES_NOT_WANT:
5529 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5530 if (nai == null) break;
5531 nai.onPreventAutomaticReconnect();
5532 nai.disconnect();
5533 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005534 }
5535 }
5536 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005537
Lorenzo Colittid6459092016-07-04 12:55:44 +09005538 @Override
markchien5776f962019-12-16 20:15:20 +08005539 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005540 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005541 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005542 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5543 Context.TETHERING_SERVICE);
5544 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005545 }
5546
Lorenzo Colittid6459092016-07-04 12:55:44 +09005547 @Override
markchien5776f962019-12-16 20:15:20 +08005548 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005549 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005550 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005551 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5552 Context.TETHERING_SERVICE);
5553 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005554 }
5555
Lorenzo Colittid6459092016-07-04 12:55:44 +09005556 @Override
markchien5776f962019-12-16 20:15:20 +08005557 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005558 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005559 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005560 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5561 Context.TETHERING_SERVICE);
5562 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005563 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005564
markchien5776f962019-12-16 20:15:20 +08005565
Lorenzo Colittid6459092016-07-04 12:55:44 +09005566 @Override
markchien5776f962019-12-16 20:15:20 +08005567 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005568 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005569 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005570 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5571 Context.TETHERING_SERVICE);
5572
5573 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005574 }
5575
Lorenzo Colittid6459092016-07-04 12:55:44 +09005576 @Override
markchien5776f962019-12-16 20:15:20 +08005577 @Deprecated
5578 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005579 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005580 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5581 Context.TETHERING_SERVICE);
5582
5583 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005584 }
5585
Udam Saini8f7d6a72017-06-07 12:06:28 -07005586 @Override
markchien5776f962019-12-16 20:15:20 +08005587 @Deprecated
5588 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005589 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005590 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5591 Context.TETHERING_SERVICE);
5592 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005593 }
5594
Robert Greenwalte0b00512014-07-02 09:59:16 -07005595 // Called when we lose the default network and have no replacement yet.
5596 // This will automatically be cleared after X seconds or a new default network
5597 // becomes CONNECTED, whichever happens first. The timer is started by the
5598 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005599 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005600 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005601 if (mNetTransitionWakeLock.isHeld()) {
5602 return;
5603 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005604 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005605 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5606 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005607 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005608 mWakelockLogs.log("ACQUIRE for " + forWhom);
5609 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005610 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005611 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005612 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005613 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005614
Hugo Benichi471b62a2017-03-30 23:18:10 +09005615 // Called when we gain a new default network to release the network transition wakelock in a
5616 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5617 // message is cancelled.
5618 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005619 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005620 if (!mNetTransitionWakeLock.isHeld()) {
5621 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005622 }
5623 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005624 // Cancel self timeout on wakelock hold.
5625 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5626 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5627 mHandler.sendMessageDelayed(msg, 1000);
5628 }
5629
5630 // Called when either message of ensureNetworkTransitionWakelock or
5631 // scheduleReleaseNetworkTransitionWakelock is processed.
5632 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5633 String event = eventName(eventId);
5634 synchronized (this) {
5635 if (!mNetTransitionWakeLock.isHeld()) {
5636 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005637 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005638 return;
5639 }
5640 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005641 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5642 mTotalWakelockDurationMs += lockDuration;
5643 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5644 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005645 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005646 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005647 }
5648
Robert Greenwalt986c7412010-09-08 15:24:47 -07005649 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005650 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005651 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005652 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005653 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005654 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005655 }
5656
Lorenzo Colittid6459092016-07-04 12:55:44 +09005657 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005658 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005659 enforceAccessPermission();
5660 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005661 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005662 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005663
5664 final NetworkAgentInfo nai;
5665 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005666 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005667 } else {
5668 nai = getNetworkAgentInfoForNetwork(network);
5669 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005670
5671 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005672 mHandler.obtainMessage(
5673 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005674 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005675
Hugo Benichid6b510a2017-04-06 17:22:18 +09005676 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005677 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005678 if (nai == null
5679 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005680 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005681 return;
5682 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005683 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005684 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005685 mConnectivityDiagnosticsHandler.sendMessage(
5686 mConnectivityDiagnosticsHandler.obtainMessage(
5687 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5688 new ReportedNetworkConnectivityInfo(
5689 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005690 return;
5691 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005692 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005693 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005694 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005695 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005696 // Validating a network that has not yet connected could result in a call to
5697 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005698 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005699 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005700 }
paulhu7aeba372020-12-30 00:42:19 +08005701 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5702 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005703 return;
5704 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005705
5706 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5707 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5708 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5709 // completed.
5710 mConnectivityDiagnosticsHandler.sendMessage(
5711 mConnectivityDiagnosticsHandler.obtainMessage(
5712 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5713 new ReportedNetworkConnectivityInfo(
5714 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005715 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005716 }
5717
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005718 // TODO: call into netd.
5719 private boolean queryUserAccess(int uid, Network network) {
5720 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5721 if (nai == null) return false;
5722
5723 // Any UID can use its default network.
5724 if (nai == getDefaultNetworkForUid(uid)) return true;
5725
5726 // Privileged apps can use any network.
5727 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5728 return true;
5729 }
5730
5731 // An unprivileged UID can use a VPN iff the VPN applies to it.
5732 if (nai.isVPN()) {
5733 return nai.networkCapabilities.appliesToUid(uid);
5734 }
5735
5736 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5737 // sockets, i.e., if it is the owner.
5738 final NetworkAgentInfo vpn = getVpnForUid(uid);
5739 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5740 && uid != vpn.networkCapabilities.getOwnerUid()) {
5741 return false;
5742 }
5743
5744 // The UID's permission must be at least sufficient for the network. Since the restricted
5745 // permission was already checked above, that just leaves background networks.
5746 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5747 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5748 }
5749
5750 // Unrestricted network. Anyone gets to use it.
5751 return true;
5752 }
5753
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005754 /**
5755 * Returns information about the proxy a certain network is using. If given a null network, it
5756 * it will return the proxy for the bound network for the caller app or the default proxy if
5757 * none.
5758 *
5759 * @param network the network we want to get the proxy information for.
5760 * @return Proxy information if a network has a proxy configured, or otherwise null.
5761 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005762 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005763 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005764 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005765 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005766 if (network == null) {
5767 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005768 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005769 true);
5770 if (activeNetwork == null) {
5771 return null;
5772 }
5773 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005774 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005775 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5776 // caller may not have.
5777 return getLinkPropertiesProxyInfo(network);
5778 }
5779 // No proxy info available if the calling UID does not have network access.
5780 return null;
5781 }
5782
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005783
5784 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005785 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5786 if (nai == null) return null;
5787 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005788 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5789 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005790 }
5791 }
5792
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005793 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005794 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005795 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005796 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005797 }
5798
Chalard Jean777e2e52018-06-07 18:02:37 +09005799 @Override
5800 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005801 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005802 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005803 }
5804
Junyu Lai970963e2022-10-25 15:46:47 +08005805 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005806 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005807 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005808 proxy = null;
5809 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005810 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005811 }
5812
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005813 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5814 // when any network changes proxy.
5815 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5816 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08005817 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
5818 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05005819 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5820
Chalard Jean7d97afc2018-06-07 17:41:29 +09005821 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005822 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005823 }
5824 }
5825
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005826 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005827 final private HashMap<Uri, Integer> mUriEventMap;
5828 final private Context mContext;
5829 final private Handler mHandler;
5830
5831 SettingsObserver(Context context, Handler handler) {
5832 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005833 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005834 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005835 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005836 }
5837
Erik Kline05f2b402015-04-30 12:58:40 +09005838 void observe(Uri uri, int what) {
5839 mUriEventMap.put(uri, what);
5840 final ContentResolver resolver = mContext.getContentResolver();
5841 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005842 }
5843
5844 @Override
5845 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005846 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005847 }
5848
5849 @Override
5850 public void onChange(boolean selfChange, Uri uri) {
5851 final Integer what = mUriEventMap.get(uri);
5852 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005853 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005854 } else {
5855 loge("No matching event to send for URI=" + uri);
5856 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005857 }
5858 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005859
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005860 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005861 Log.d(TAG, s);
5862 }
5863
5864 private static void logw(String s) {
5865 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005866 }
5867
Daniel Brightf9e945b2020-06-15 16:10:01 -07005868 private static void logwtf(String s) {
5869 Log.wtf(TAG, s);
5870 }
5871
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005872 private static void logwtf(String s, Throwable t) {
5873 Log.wtf(TAG, s, t);
5874 }
5875
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005876 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005877 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005878 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005879
Hugo Benichi39621362017-02-11 17:04:43 +09005880 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005881 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005882 }
5883
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005884 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005885 * Return the information of all ongoing VPNs.
5886 *
5887 * <p>This method is used to update NetworkStatsService.
5888 *
5889 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005890 */
junyulai2050bed2021-01-23 09:46:34 +08005891 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005892 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005893 if (mLockdownEnabled) {
5894 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005895 }
junyulai2050bed2021-01-23 09:46:34 +08005896 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005897 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005898 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005899 if (info != null) {
5900 infoList.add(info);
5901 }
5902 }
junyulai2050bed2021-01-23 09:46:34 +08005903 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005904 }
5905
5906 /**
5907 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005908 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005909 */
junyulai2050bed2021-01-23 09:46:34 +08005910 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005911 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005912 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5913 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005914 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5915 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5916 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005917 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5918 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005919 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005920 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005921 }
5922 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005923
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005924 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005925
5926 List<String> interfaces = new ArrayList<>();
5927 for (Network network : underlyingNetworks) {
5928 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5929 if (underlyingNai == null) continue;
5930 LinkProperties lp = underlyingNai.linkProperties;
5931 for (String iface : lp.getAllInterfaceNames()) {
5932 if (!TextUtils.isEmpty(iface)) {
5933 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005934 }
5935 }
Benedict Wong34857f82019-06-12 17:46:15 +00005936 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005937
5938 if (interfaces.isEmpty()) return null;
5939
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005940 // Must be non-null or NetworkStatsService will crash.
5941 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5942 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005943 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005944 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005945
junyulai2050bed2021-01-23 09:46:34 +08005946 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5947 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005948 }
5949
James Mattisd31bdfa2020-12-23 16:37:26 -08005950 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005951 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5952 Network[] underlyingNetworks) {
5953 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005954 if (underlyingNetworks == null && defaultNetwork != null) {
5955 // null underlying networks means to track the default.
5956 underlyingNetworks = new Network[] { defaultNetwork };
5957 }
5958 return underlyingNetworks;
5959 }
5960
5961 // Returns true iff |network| is an underlying network of |nai|.
5962 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5963 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5964 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005965 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005966 final Network[] underlying = underlyingNetworksOrDefault(
5967 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005968 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005969 }
5970
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005971 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005972 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005973 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005974 * When underlying networks change, such networks may have to update capabilities to reflect
5975 * things like the metered bit, their transports, and so on. The capabilities are calculated
5976 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005977 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005978 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005979 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005980 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005981 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005982 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005983 }
5984 }
5985 }
5986
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005987 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5988 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5989 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5990 // a VPN is not up.
5991 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5992 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5993 for (UidRange range : blockedUidRanges) {
5994 if (range.contains(uid)) return true;
5995 }
5996 return false;
5997 }
5998
5999 @Override
6000 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006001 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006002 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6003 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6004 }
6005
6006 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6007 if (DBG) {
6008 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6009 + Arrays.toString(ranges));
6010 }
6011 // Cannot use a Set since the list of UID ranges might contain duplicates.
6012 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6013 for (int i = 0; i < ranges.length; i++) {
6014 if (requireVpn) {
6015 newVpnBlockedUidRanges.add(ranges[i]);
6016 } else {
6017 newVpnBlockedUidRanges.remove(ranges[i]);
6018 }
6019 }
6020
6021 try {
6022 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6023 } catch (RemoteException | ServiceSpecificException e) {
6024 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6025 + Arrays.toString(ranges) + "): netd command failed: " + e);
6026 }
6027
Motomu Utsumib08654c2022-05-11 05:56:26 +00006028 if (SdkLevel.isAtLeastT()) {
6029 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6030 }
6031
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006032 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6033 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006034 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6035 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006036 }
6037
6038 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6039 }
6040
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006041 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006042 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006043 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006044 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006045 }
6046
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006047 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6048 return mLockdownEnabled
6049 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6050 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006051 }
6052
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006053 private NetworkAgentInfo getLegacyLockdownNai() {
6054 if (!mLockdownEnabled) {
6055 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006056 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006057 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006058 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6059 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006060
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006061 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006062 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6063 // a local variable. There is no need to make a copy because its contents cannot change.
6064 final Network[] underlying = nai.declaredUnderlyingNetworks;
6065 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006066 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006067 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006068
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006069 // The legacy lockdown VPN always uses the default network.
6070 // If the VPN's underlying network is no longer the current default network, it means that
6071 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006072 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6073 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006074 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006075 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006076 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006077 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006078
6079 return nai;
6080 };
6081
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006082 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6083 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6084 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006085 private DetailedState getLegacyLockdownState(DetailedState origState) {
6086 if (origState != DetailedState.CONNECTED) {
6087 return origState;
6088 }
6089 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6090 ? DetailedState.CONNECTING
6091 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006092 }
6093
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006094 private void filterForLegacyLockdown(NetworkInfo ni) {
6095 if (!mLockdownEnabled || !ni.isConnected()) return;
6096 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6097 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6098 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6099 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6100 // network, this time with a state of CONNECTED.
6101 //
6102 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6103 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6104 // is not too far off the truth, since an always-on VPN, when not connected, is always
6105 // trying to reconnect.
6106 if (getLegacyLockdownNai() == null) {
6107 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6108 }
6109 }
6110
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006111 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006112 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006113 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006114 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006115 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6116 return;
6117 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006118 final long ident = Binder.clearCallingIdentity();
6119 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006120 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006121 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006122 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006123 } finally {
6124 Binder.restoreCallingIdentity(ident);
6125 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006126 }
Wink Savillecb117d32013-08-29 14:57:08 -07006127
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006128 @Override
6129 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006130 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006131 final long ident = Binder.clearCallingIdentity();
6132 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006133 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006134 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006135 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6136 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006137 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006138 } finally {
6139 Binder.restoreCallingIdentity(ident);
6140 }
6141 }
6142
James Mattis02220e22021-03-13 19:27:21 -08006143 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006144 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6145 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6146 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006147 }
6148
James Mattis02220e22021-03-13 19:27:21 -08006149 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006150 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006151 handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +09006152 List.of(new ProfileNetworkPreferenceInfo(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006153 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006154 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6155 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6156 }
junyulaid91e7052020-08-28 13:44:33 +08006157 }
6158
James Mattis02220e22021-03-13 19:27:21 -08006159 private void onPackageChanged(@NonNull final String packageName) {
6160 // This is necessary in case a package is added or removed, but also when it's replaced to
6161 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6162 // as one in the preferences, then it should follow the same routing as that other package,
6163 // which means updating the rules is never to be needed in this case (whether it joins or
6164 // leaves a UID with a preference).
6165 if (isMappedInOemNetworkPreference(packageName)) {
6166 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6167 }
6168 }
6169
6170 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006171 @Override
6172 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006173 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006174 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006175 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006176
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006177 // User should be filled for below intents, check the existence.
6178 if (user == null) {
6179 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6180 return;
6181 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006182
Lorenzo Colitticd675292021-02-04 17:32:07 +09006183 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006184 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006185 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006186 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006187 } else {
junyulaid91e7052020-08-28 13:44:33 +08006188 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006189 }
6190 }
6191 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006192
James Mattis02220e22021-03-13 19:27:21 -08006193 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6194 @Override
6195 public void onReceive(Context context, Intent intent) {
6196 ensureRunningOnConnectivityServiceThread();
6197 switch (intent.getAction()) {
6198 case Intent.ACTION_PACKAGE_ADDED:
6199 case Intent.ACTION_PACKAGE_REMOVED:
6200 case Intent.ACTION_PACKAGE_REPLACED:
6201 onPackageChanged(intent.getData().getSchemeSpecificPart());
6202 break;
6203 default:
6204 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6205 }
6206 }
6207 };
6208
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006209 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006210 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006211
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006212 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006213 public final String name;
6214 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006215 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006216 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006217
lifraf3a3492021-03-10 13:58:14 +08006218 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6219 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006220 this.name = name;
6221 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006222 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006223 mDeathRecipient = deathRecipient;
6224
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006225 if (mDeathRecipient == null) {
6226 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006227 }
6228 }
6229
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006230 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006231 try {
6232 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6233 } catch (RemoteException e) {
6234 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006235 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006236 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006237 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006238
James Mattis4fce5d12020-11-12 15:53:42 -08006239 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6240 for (int i = 0; i < requests.size(); i++) {
6241 ensureNetworkRequestHasType(requests.get(i));
6242 }
6243 }
6244
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006245 private void ensureNetworkRequestHasType(NetworkRequest request) {
6246 if (request.type == NetworkRequest.Type.NONE) {
6247 throw new IllegalArgumentException(
6248 "All NetworkRequests in ConnectivityService must have a type");
6249 }
6250 }
6251
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006252 /**
6253 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006254 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006255 */
James Mattis258ea3c2020-11-15 15:04:40 -08006256 @VisibleForTesting
6257 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006258 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6259 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006260 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006261
James Mattisa076c532020-12-02 14:12:41 -08006262 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6263 void setSatisfier(
6264 @Nullable final NetworkAgentInfo satisfier,
6265 @Nullable final NetworkRequest activeRequest) {
6266 mSatisfier = satisfier;
6267 mActiveRequest = activeRequest;
6268 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006269
James Mattisd31bdfa2020-12-23 16:37:26 -08006270 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006271 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006272 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006273 private NetworkAgentInfo mSatisfier;
6274 NetworkAgentInfo getSatisfier() {
6275 return mSatisfier;
6276 }
6277
6278 // The request in mRequests assigned to a network agent. This is null if none of the
6279 // requests in mRequests can be satisfied. This member has the constraint of only being
6280 // accessible on the handler thread.
6281 @Nullable
6282 private NetworkRequest mActiveRequest;
6283 NetworkRequest getActiveRequest() {
6284 return mActiveRequest;
6285 }
6286
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006287 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006288 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006289 @Nullable
6290 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006291
6292 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006293 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006294 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006295 final int mPid;
6296 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006297 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006298 @Nullable
6299 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006300
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006301 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006302 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006303
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006304 // Effective UID of this request. This is different from mUid when a privileged process
6305 // files a request on behalf of another UID. This UID is used to determine blocked status,
6306 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6307 // maximum limit of registered callbacks per UID.
6308 final int mAsUid;
6309
paulhu48291862021-07-14 14:53:57 +08006310 // Preference order of this request.
6311 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006312
James Mattis3ce3d3c2021-02-09 18:18:28 -08006313 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6314 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6315 // maintained for keying off of. This is only a concern when the original nri
6316 // mNetworkRequests changes which happens currently for apps that register callbacks to
6317 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6318 // that match the per-app default nri that currently tracks the calling app's uid so that
6319 // callbacks are fired at the appropriate time. When the callbacks fire,
6320 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6321 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6322 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6323 @NonNull
6324 private final NetworkRequest mNetworkRequestForCallback;
6325 NetworkRequest getNetworkRequestForCallback() {
6326 return mNetworkRequestForCallback;
6327 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006328
James Mattisd31bdfa2020-12-23 16:37:26 -08006329 /**
6330 * Get the list of UIDs this nri applies to.
6331 */
6332 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006333 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006334 // networkCapabilities.getUids() returns a defensive copy.
6335 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006336 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6337 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006338 }
6339
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006340 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6341 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006342 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006343 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006344 }
6345
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006346 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006347 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006348 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006349 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006350 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006351 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006352 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006353 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006354 mBinder = null;
6355 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006356 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006357 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006358 mPerUidCounter = getRequestCounter(this);
6359 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006360 /**
6361 * Location sensitive data not included in pending intent. Only included in
6362 * {@link NetworkCallback}.
6363 */
6364 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006365 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006366 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006367 }
6368
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006369 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006370 @Nullable final IBinder binder,
6371 @NetworkCallback.Flag int callbackFlags,
6372 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006373 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6374 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006375 }
6376
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006377 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006378 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006379 @Nullable final IBinder binder,
6380 @NetworkCallback.Flag int callbackFlags,
6381 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006382 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006383 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006384 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006385 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006386 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006387 mBinder = binder;
6388 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006389 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006390 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006391 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006392 mPerUidCounter = getRequestCounter(this);
6393 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006394 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006395 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006396 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006397 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006398 }
6399
James Mattis3ce3d3c2021-02-09 18:18:28 -08006400 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6401 @NonNull final List<NetworkRequest> r) {
6402 super();
6403 ensureAllNetworkRequestsHaveType(r);
6404 mRequests = initializeRequests(r);
6405 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006406 final NetworkAgentInfo satisfier = nri.getSatisfier();
6407 if (null != satisfier) {
6408 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6409 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006410 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006411 // As this code creates a new NRI with a new set of requests, figure out which of
6412 // the list of requests should be the active request. It is always the first
6413 // request of the list that can be satisfied by the satisfier since the order of
6414 // requests is a priority order.
6415 // Note even in the presence of a satisfier there may not be an active request,
6416 // when the satisfier is the no-service network.
6417 NetworkRequest activeRequest = null;
6418 for (final NetworkRequest candidate : r) {
6419 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6420 activeRequest = candidate;
6421 break;
6422 }
6423 }
6424 setSatisfier(satisfier, activeRequest);
6425 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006426 mMessenger = nri.mMessenger;
6427 mBinder = nri.mBinder;
6428 mPid = nri.mPid;
6429 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006430 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006431 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006432 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006433 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006434 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006435 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006436 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006437 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006438 }
6439
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006440 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006441 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006442 }
6443
paulhue9913722021-05-26 15:19:20 +08006444 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006445 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006446 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006447 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006448 }
6449
James Mattis2516da32021-01-31 17:06:19 -08006450 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6451 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6452 // false.
6453 boolean isBeingSatisfied() {
6454 return (null != mSatisfier && null != mActiveRequest);
6455 }
6456
James Mattis3d229892020-11-16 16:46:28 -08006457 boolean isMultilayerRequest() {
6458 return mRequests.size() > 1;
6459 }
6460
James Mattis45d81842021-01-10 14:24:24 -08006461 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6462 // Creating a defensive copy to prevent the sender from modifying the list being
6463 // reflected in the return value of this method.
6464 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006465 return Collections.unmodifiableList(tempRequests);
6466 }
6467
James Mattisb1392002021-03-31 13:57:52 -07006468 void linkDeathRecipient() {
6469 if (null != mBinder) {
6470 try {
6471 mBinder.linkToDeath(this, 0);
6472 } catch (RemoteException e) {
6473 binderDied();
6474 }
6475 }
6476 }
6477
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006478 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006479 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006480 try {
6481 mBinder.unlinkToDeath(this, 0);
6482 } catch (NoSuchElementException e) {
6483 // Temporary workaround for b/194394697 pending analysis of additional logs
6484 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6485 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006486 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006487 }
6488
paulhu48291862021-07-14 14:53:57 +08006489 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6490 // Compare two preference orders.
6491 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006492 }
6493
paulhu48291862021-07-14 14:53:57 +08006494 int getPreferenceOrderForNetd() {
6495 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6496 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6497 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006498 }
paulhu48291862021-07-14 14:53:57 +08006499 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006500 }
6501
James Mattis4fce5d12020-11-12 15:53:42 -08006502 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006503 public void binderDied() {
6504 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006505 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006506 // As an immutable collection, mRequests cannot change by the time the
6507 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6508 // is acceptable. Use handleReleaseNetworkRequest and not directly
6509 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6510 // the app already unregistered the request.
6511 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6512 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006513 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006514
James Mattis4fce5d12020-11-12 15:53:42 -08006515 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006516 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006517 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6518 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006519 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006520 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006521 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006522 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006523 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006524 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006525 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006526 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006527 }
6528
Junyu Lai00d92df2022-07-05 11:01:52 +08006529 // Keep backward compatibility since the ServiceSpecificException is used by
6530 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6531 public static class RequestInfoPerUidCounter extends PerUidCounter {
6532 RequestInfoPerUidCounter(int maxCountPerUid) {
6533 super(maxCountPerUid);
6534 }
6535
6536 @Override
6537 public synchronized void incrementCountOrThrow(int uid) {
6538 try {
6539 super.incrementCountOrThrow(uid);
6540 } catch (IllegalStateException e) {
6541 throw new ServiceSpecificException(
6542 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6543 "Uid " + uid + " exceeded its allotted requests limit");
6544 }
6545 }
6546
6547 @Override
6548 public synchronized void decrementCountOrThrow(int uid) {
6549 throw new UnsupportedOperationException("Use decrementCount instead.");
6550 }
6551
6552 public synchronized void decrementCount(int uid) {
6553 try {
6554 super.decrementCountOrThrow(uid);
6555 } catch (IllegalStateException e) {
6556 logwtf("Exception when decrement per uid request count: ", e);
6557 }
6558 }
6559 }
6560
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006561 // This checks that the passed capabilities either do not request a
6562 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006563 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006564 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006565 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006566 throw new SecurityException("Insufficient permissions to request a specific SSID");
6567 }
paulhu1a407652019-03-22 16:35:06 +08006568
6569 if (nc.hasSignalStrength()
6570 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6571 throw new SecurityException(
6572 "Insufficient permissions to request a specific signal strength");
6573 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006574 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006575
junyulai2217bec2021-04-14 23:33:31 +08006576 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006577 enforceNetworkFactoryPermission();
6578 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006579 }
6580
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006581 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006582 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006583 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006584 // mNetworkRequests may contain the same value multiple times in case of
6585 // multilayer requests. It won't matter in this case because the thresholds
6586 // will then be the same and be deduplicated as they enter the `thresholds` set.
6587 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006588 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6589 for (final NetworkRequest req : nri.mRequests) {
6590 if (req.networkCapabilities.hasSignalStrength()
6591 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6592 thresholds.add(req.networkCapabilities.getSignalStrength());
6593 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006594 }
6595 }
6596 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006597 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006598 }
6599
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006600 private void updateSignalStrengthThresholds(
6601 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006602 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006603
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006604 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006605 String detail;
6606 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6607 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6608 } else {
6609 detail = reason;
6610 }
6611 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006612 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006613 }
6614
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006615 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006616 }
6617
Chalard Jeandd421992021-12-16 23:16:02 +09006618 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006619 if (nc == null) {
6620 return;
6621 }
6622 NetworkSpecifier ns = nc.getNetworkSpecifier();
6623 if (ns == null) {
6624 return;
6625 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006626 if (ns instanceof MatchAllNetworkSpecifier) {
6627 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6628 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006629 }
6630
Chalard Jeandd421992021-12-16 23:16:02 +09006631 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006632 ensureValidNetworkSpecifier(nc);
6633 if (nc.isPrivateDnsBroken()) {
6634 throw new IllegalArgumentException("Can't request broken private DNS");
6635 }
Chalard Jeande665262022-02-25 16:12:12 +09006636 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006637 throw new IllegalArgumentException("Can't request access UIDs");
6638 }
lucasline117e2e2019-10-22 18:27:33 +08006639 }
6640
Chalard Jeandd421992021-12-16 23:16:02 +09006641 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6642 ensureListenableCapabilities(nc);
6643 final String badCapability = nc.describeFirstNonRequestableCapability();
6644 if (badCapability != null) {
6645 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6646 }
6647 }
6648
Chiachang Wang3bc52762021-11-25 14:17:57 +08006649 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6650 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006651 private boolean isTargetSdkAtleast(int version, int callingUid,
6652 @NonNull String callingPackageName) {
6653 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006654 final PackageManager pm =
6655 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006656 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006657 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006658 if (callingVersion < version) return false;
6659 } catch (PackageManager.NameNotFoundException e) { }
6660 return true;
6661 }
6662
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006663 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006664 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006665 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006666 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006667 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006668 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006669 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6670 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006671 throw new SecurityException("Insufficient permissions to specify legacy type");
6672 }
markchienfac84a22020-03-18 21:16:15 +08006673 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006674 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006675 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006676 // Privileged callers can track the default network of another UID by passing in a UID.
6677 if (asUid != Process.INVALID_UID) {
6678 enforceSettingsPermission();
6679 } else {
6680 asUid = callingUid;
6681 }
junyulaiad010792021-01-11 16:53:38 +08006682 final NetworkRequest.Type reqType;
6683 try {
6684 reqType = NetworkRequest.Type.values()[reqTypeInt];
6685 } catch (ArrayIndexOutOfBoundsException e) {
6686 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6687 }
6688 switch (reqType) {
6689 case TRACK_DEFAULT:
6690 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006691 // is unused and will be replaced by ones appropriate for the UID (usually, the
6692 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006693 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006694 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006695 enforceAccessPermission();
6696 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006697 case TRACK_SYSTEM_DEFAULT:
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08006698 enforceSettingsOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006699 networkCapabilities = new NetworkCapabilities(defaultNc);
6700 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006701 case BACKGROUND_REQUEST:
6702 enforceNetworkStackOrSettingsPermission();
6703 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006704 case REQUEST:
6705 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6706 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006707 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006708 // TODO: this is incorrect. We mark the request as metered or not depending on
6709 // the state of the app when the request is filed, but we never change the
6710 // request if the app changes network state. http://b/29964605
6711 enforceMeteredApnPolicy(networkCapabilities);
6712 break;
junyulai1b1c8742021-03-12 20:05:08 +08006713 case LISTEN_FOR_BEST:
6714 enforceAccessPermission();
6715 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6716 break;
junyulaiad010792021-01-11 16:53:38 +08006717 default:
6718 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006719 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006720 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006721 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006722 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006723
junyulai1b1c8742021-03-12 20:05:08 +08006724 // Enforce FOREGROUND if the caller does not have permission to use background network.
6725 if (reqType == LISTEN_FOR_BEST) {
6726 restrictBackgroundRequestForCaller(networkCapabilities);
6727 }
6728
6729 // Set the UID range for this request to the single UID of the requester, unless the
6730 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006731 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6732 // are no visible methods to set the UIDs, an app could use reflection to try and get
6733 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006734 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006735 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6736 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006737
Etan Cohen85000162017-02-05 10:42:27 -08006738 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006739 throw new IllegalArgumentException("Bad timeout specified");
6740 }
Etan Cohen9786d922015-11-18 10:56:15 -08006741
James Mattis3ce3d3c2021-02-09 18:18:28 -08006742 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006743 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006744 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006745 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006746 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006747 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006748
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006749 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6750 // copied from the default request above. (This is necessary to ensure, for example, that
6751 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6752 // changes don't alter request matching.
6753 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6754 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006755 throw new IllegalStateException(
6756 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006757 + networkCapabilities + " vs. " + defaultNc);
6758 }
6759
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006760 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006761 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006762 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006763 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006764 }
6765 return networkRequest;
6766 }
6767
James Mattis3ce3d3c2021-02-09 18:18:28 -08006768 /**
6769 * Return the nri to be used when registering a network request. Specifically, this is used with
6770 * requests registered to track the default request. If there is currently a per-app default
6771 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6772 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006773 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6774 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006775 * @param nr the network request for the nri.
6776 * @param msgr the messenger for the nri.
6777 * @param binder the binder for the nri.
6778 * @param callingAttributionTag the calling attribution tag for the nri.
6779 * @return the nri to register.
6780 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006781 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006782 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006783 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006784 @Nullable String callingAttributionTag) {
6785 final List<NetworkRequest> requests;
6786 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6787 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006788 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006789 } else {
6790 requests = Collections.singletonList(nr);
6791 }
Roshan Pius951c0032020-12-22 15:10:42 -08006792 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006793 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006794 }
6795
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006796 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006797 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006798 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006799 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6800 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6801 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6802 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006803 }
junyulai96bd9fe2022-03-08 17:36:42 +08006804 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006805 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006806 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006807 }
6808 }
6809
fenglu3f357402015-03-20 11:29:56 -07006810 @Override
fenglub00f4882015-04-21 17:12:05 -07006811 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006812 enforceAccessPermission();
6813 NetworkAgentInfo nai = null;
6814 if (network == null) {
6815 return false;
6816 }
6817 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006818 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006819 }
6820 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006821 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006822 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006823 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006824 Integer uidReqs = mBandwidthRequests.get(uid);
6825 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006826 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006827 }
6828 mBandwidthRequests.put(uid, ++uidReqs);
6829 }
fenglu3f357402015-03-20 11:29:56 -07006830 return true;
6831 }
6832 return false;
6833 }
6834
Felipe Leme0a5ae422016-06-20 16:36:29 -07006835 private boolean isSystem(int uid) {
6836 return uid < Process.FIRST_APPLICATION_UID;
6837 }
fenglu3f357402015-03-20 11:29:56 -07006838
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006839 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006840 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006841 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006842 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006843 return;
6844 }
Hugo Benichi39621362017-02-11 17:04:43 +09006845 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6846 // Policy already enforced.
6847 return;
6848 }
paulhuaf50d7d2020-12-24 19:47:34 +08006849 final long ident = Binder.clearCallingIdentity();
6850 try {
6851 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6852 // If UID is restricted, don't allow them to bring up metered APNs.
6853 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6854 }
6855 } finally {
6856 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006857 }
6858 }
6859
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006860 @Override
6861 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006862 PendingIntent operation, @NonNull String callingPackageName,
6863 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006864 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006865 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006866 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006867 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006868 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006869 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006870 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006871 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006872 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006873 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6874 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006875
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006876 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006877 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006878 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6879 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006880 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006881 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6882 nri));
6883 return networkRequest;
6884 }
6885
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006886 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6887 mHandler.sendMessageDelayed(
6888 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006889 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006890 }
6891
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006892 @Override
6893 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006894 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006895 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006896 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006897 }
6898
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006899 // In order to implement the compatibility measure for pre-M apps that call
6900 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6901 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6902 // This ensures it has permission to do so.
6903 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6904 if (nc == null) {
6905 return false;
6906 }
6907 int[] transportTypes = nc.getTransportTypes();
6908 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6909 return false;
6910 }
6911 try {
6912 mContext.enforceCallingOrSelfPermission(
6913 android.Manifest.permission.ACCESS_WIFI_STATE,
6914 "ConnectivityService");
6915 } catch (SecurityException e) {
6916 return false;
6917 }
6918 return true;
6919 }
6920
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006921 @Override
6922 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006923 Messenger messenger, IBinder binder,
6924 @NetworkCallback.Flag int callbackFlags,
6925 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006926 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006927 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6928 enforceAccessPermission();
6929 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006930
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006931 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006932 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006933 Binder.getCallingPid(), callingUid, callingPackageName);
6934 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006935 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6936 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6937 // onLost and onAvailable callbacks when networks move in and out of the background.
6938 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6939 // can't request networks.
6940 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006941 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006942
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006943 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006944 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006945 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006946 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006947 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006948 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006949
6950 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6951 return networkRequest;
6952 }
6953
6954 @Override
6955 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006956 PendingIntent operation, @NonNull String callingPackageName,
6957 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006958 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006959 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006960 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6961 enforceAccessPermission();
6962 }
Chalard Jeandd421992021-12-16 23:16:02 +09006963 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006964 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006965 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006966 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006967 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006968
6969 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006970 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006971 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6972 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006973 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006974
WeiZhang1cc3f172021-06-03 19:02:04 -05006975 mHandler.sendMessage(mHandler.obtainMessage(
6976 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006977 }
6978
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006979 /** Returns the next Network provider ID. */
6980 public final int nextNetworkProviderId() {
6981 return mNextNetworkProviderId.getAndIncrement();
6982 }
6983
Erik Kline0c04b742016-07-07 16:50:58 +09006984 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006985 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006986 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006987 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006988 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006989 }
6990
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006991 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6992 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006993 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6994 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6995 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006996 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006997 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006998 return;
6999 }
7000
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007001 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7002 mNetworkProviderInfos.put(npi.messenger, npi);
7003 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007004 }
7005
7006 @Override
7007 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007008 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007009 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007010 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007011 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007012 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7013 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007014 }
7015
7016 @Override
7017 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007018 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007019 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007020 }
7021
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007022 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007023 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007024 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7025 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007026 Objects.requireNonNull(score);
7027 Objects.requireNonNull(caps);
7028 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007029 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007030 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007031 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7032 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007033 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7034 }
7035
Chalard Jeanbb902a52021-08-18 01:35:19 +09007036 private void updateOfferScore(final NetworkOffer offer) {
7037 final boolean yieldToBadWiFi =
7038 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7039 final NetworkOffer newOffer = new NetworkOffer(
7040 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7041 offer.caps, offer.callback, offer.providerId);
7042 if (offer.equals(newOffer)) return;
7043 handleRegisterNetworkOffer(newOffer);
7044 }
7045
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007046 @Override
7047 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007048 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007049 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7050 }
7051
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007052 private void handleUnregisterNetworkProvider(Messenger messenger) {
7053 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7054 if (npi == null) {
7055 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007056 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007057 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007058 // Unregister all the offers from this provider
7059 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7060 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007061 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007062 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7063 toRemove.add(noi);
7064 }
7065 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007066 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007067 handleUnregisterNetworkOffer(noi);
7068 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007069 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007070 }
7071
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007072 @Override
James Mattisf7027322020-12-13 16:28:14 -08007073 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007074 if (request.hasTransport(TRANSPORT_TEST)) {
7075 enforceNetworkFactoryOrTestNetworksPermission();
7076 } else {
7077 enforceNetworkFactoryPermission();
7078 }
James Mattisf7027322020-12-13 16:28:14 -08007079 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7080 if (nri != null) {
7081 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7082 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7083 mHandler.post(() -> handleReleaseNetworkRequest(
7084 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7085 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007086 }
7087
Paul Jensen1f567382015-02-13 14:18:39 -05007088 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7089 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007090 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007091 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007092 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007093 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007094 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007095
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007096 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007097 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007098 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007099
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007100 // UID ranges for users that are currently blocked by VPNs.
7101 // This array is accessed and iterated on multiple threads without holding locks, so its
7102 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7103 // (on the handler thread).
7104 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7105
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007106 // Must only be accessed on the handler thread
7107 @NonNull
7108 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7109
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007110 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007111 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007112
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007113 // Current OEM network preferences. This object must only be written to on the handler thread.
7114 // Since it is immutable and always non-null, other threads may read it if they only care
7115 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007116 @NonNull
7117 private OemNetworkPreferences mOemNetworkPreferences =
7118 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007119 // Current per-profile network preferences. This object follows the same threading rules as
7120 // the OEM network preferences above.
7121 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007122 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7123 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007124
paulhu51f77dc2021-06-07 02:34:20 +00007125 // A set of UIDs that should use mobile data preferentially if available. This object follows
7126 // the same threading rules as the OEM network preferences above.
7127 @NonNull
7128 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7129
James Mattiscb1e0362021-04-06 17:07:42 -07007130 // OemNetworkPreferences activity String log entries.
7131 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7132 @NonNull
7133 private final LocalLog mOemNetworkPreferencesLogs =
7134 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7135
James Mattis02220e22021-03-13 19:27:21 -08007136 /**
7137 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7138 * @param packageName the package name to check existence of a mapping for.
7139 * @return true if a mapping exists, false otherwise
7140 */
7141 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7142 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7143 }
7144
James Mattise3ef1912020-12-20 11:09:58 -08007145 // The always-on request for an Internet-capable network that apps without a specific default
7146 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007147 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007148 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007149 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007150 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007151 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007152 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007153 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007154
James Mattisd31bdfa2020-12-23 16:37:26 -08007155 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7156 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7157 }
7158
7159 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007160 * Return the default network request currently tracking the given uid.
7161 * @param uid the uid to check.
7162 * @return the NetworkRequestInfo tracking the given uid.
7163 */
7164 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007165 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007166 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007167 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007168 // Checking the first request is sufficient as only multilayer requests will have more
7169 // than one request and for multilayer, all requests will track the same uids.
7170 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007171 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007172 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007173 highestPriorityNri = nri;
7174 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007175 }
7176 }
paulhuaa0743d2021-05-26 21:56:03 +08007177 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007178 }
7179
7180 /**
7181 * Get a copy of the network requests of the default request that is currently tracking the
7182 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007183 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7184 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007185 * @param requestorUid the uid to check the default for.
7186 * @param requestorPackageName the requestor's package name.
7187 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7188 */
7189 @NonNull
7190 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007191 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007192 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007193 getDefaultRequestTrackingUid(asUid).mRequests,
7194 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007195 }
7196
7197 /**
7198 * Copy the given nri's NetworkRequest collection.
7199 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007200 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7201 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007202 * @param requestorUid the uid to set on the copied collection.
7203 * @param requestorPackageName the package name to set on the copied collection.
7204 * @return the copied NetworkRequest collection.
7205 */
7206 @NonNull
7207 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007208 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7209 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007210 final List<NetworkRequest> requests = new ArrayList<>();
7211 for (final NetworkRequest nr : requestsToCopy) {
7212 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007213 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007214 nr.legacyType, nextNetworkRequestId(), nr.type));
7215 }
7216 return requests;
7217 }
7218
7219 @NonNull
7220 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007221 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7222 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007223 // These capabilities are for a TRACK_DEFAULT callback, so:
7224 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7225 // mDefaultRequest and a per-UID default request.
7226 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007227 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007228 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007229 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7230 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007231 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007232 restrictRequestUidsForCallerAndSetRequestorInfo(
7233 netCap, requestorUid, requestorPackageName);
7234 return netCap;
7235 }
7236
7237 /**
7238 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7239 * @param nr the network request to check for equality against.
7240 * @return the nri if one exists, null otherwise.
7241 */
7242 @Nullable
7243 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7244 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7245 if (nri.getNetworkRequestForCallback().equals(nr)) {
7246 return nri;
7247 }
7248 }
7249 return null;
7250 }
7251
7252 /**
7253 * Check if an nri is currently being managed by per-app default networking.
7254 * @param nri the nri to check.
7255 * @return true if this nri is currently being managed by per-app default networking.
7256 */
7257 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7258 // nri.mRequests.get(0) is only different from the original request filed in
7259 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7260 // functionality therefore if these two don't match, it means this particular nri is
7261 // currently being managed by a per-app default.
7262 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7263 }
7264
7265 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007266 * Determine if an nri is a managed default request that disallows default networking.
7267 * @param nri the request to evaluate
7268 * @return true if device-default networking is disallowed
7269 */
7270 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7271 // Check if this nri is a managed default that supports the default network at its
7272 // lowest priority request.
7273 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7274 final NetworkCapabilities lowestPriorityNetCap =
7275 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7276 return isPerAppDefaultRequest(nri)
7277 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7278 lowestPriorityNetCap));
7279 }
7280
Erik Kline05f2b402015-04-30 12:58:40 +09007281 // Request used to optionally keep mobile data active even when higher
7282 // priority networks like Wi-Fi are active.
7283 private final NetworkRequest mDefaultMobileDataRequest;
7284
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007285 // Request used to optionally keep wifi data active even when higher
7286 // priority networks like ethernet are active.
7287 private final NetworkRequest mDefaultWifiRequest;
7288
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007289 // Request used to optionally keep vehicle internal network always active
7290 private final NetworkRequest mDefaultVehicleRequest;
7291
James Mattisd31bdfa2020-12-23 16:37:26 -08007292 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7293 // network with no service. This NAI should never be matched against, nor should any public API
7294 // ever return the associated network. For this reason, this NAI is not in the list of available
7295 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7296 // default requests that don't support using the device default network which will ultimately
7297 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7298 @VisibleForTesting
7299 final NetworkAgentInfo mNoServiceNetwork;
7300
Chalard Jean5b409c72021-02-04 13:12:59 +09007301 // The NetworkAgentInfo currently satisfying the default request, if any.
7302 private NetworkAgentInfo getDefaultNetwork() {
7303 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007304 }
7305
James Mattis2516da32021-01-31 17:06:19 -08007306 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007307 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007308 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7309 // Currently, all network requests will have the same uids therefore checking the first
7310 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007311 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007312 if (null == uids) {
7313 continue;
7314 }
7315 for (final UidRange range : uids) {
7316 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007317 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007318 highestPriorityNri = nri;
7319 }
James Mattis2516da32021-01-31 17:06:19 -08007320 }
7321 }
7322 }
paulhuaa0743d2021-05-26 21:56:03 +08007323 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007324 }
7325
Varun Ananddf569952019-02-06 10:13:38 -08007326 @Nullable
7327 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7328 return nai != null ? nai.network : null;
7329 }
7330
7331 private void ensureRunningOnConnectivityServiceThread() {
7332 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7333 throw new IllegalStateException(
7334 "Not running on ConnectivityService thread: "
7335 + Thread.currentThread().getName());
7336 }
7337 }
7338
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007339 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007340 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7341 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007342 }
7343
Chalard Jean29d06db2018-05-02 21:14:54 +09007344 /**
7345 * Register a new agent with ConnectivityService to handle a network.
7346 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007347 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007348 * @param networkInfo the initial info associated with this network. It can be updated later :
7349 * see {@link #updateNetworkInfo}.
7350 * @param linkProperties the initial link properties of this network. They can be updated
7351 * later : see {@link #updateLinkProperties}.
7352 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007353 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007354 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007355 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007356 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007357 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007358 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007359 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007360 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007361 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7362 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007363 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7364 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7365 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007366 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007367 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007368 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007369 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007370 } else {
7371 enforceNetworkFactoryPermission();
7372 }
7373
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007374 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007375 final long token = Binder.clearCallingIdentity();
7376 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007377 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007378 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007379 } finally {
7380 Binder.restoreCallingIdentity(token);
7381 }
7382 }
7383
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007384 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007385 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007386 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7387 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007388
Chalard Jeandbc46952022-02-02 00:14:18 +09007389 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7390 // and mutate them at any time.
7391 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7392 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7393 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7394
Chalard Jean366c5252022-01-25 18:27:53 +09007395 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007396 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007397 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7398 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007399 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007400 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007401 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007402 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7403 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007404
Chalard Jeandbc46952022-02-02 00:14:18 +09007405 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007406 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007407 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007408 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007409 mDeps.getNetworkStack().makeNetworkMonitor(
7410 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007411 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7412 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007413 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007414 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007415 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007416 }
7417
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007418 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007419 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007420 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007421 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007422 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007423 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7424 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7425 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007426
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007427 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007428
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007429 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007430 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007431 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007432 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007433
7434 try {
7435 networkMonitor.start();
7436 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007437 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007438 }
Chalard Jean366c5252022-01-25 18:27:53 +09007439
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007440 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007441 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007442 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007443 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007444 }
7445
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007446 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7447 @NonNull public final NetworkOffer offer;
7448
7449 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7450 this.offer = offer;
7451 }
7452
7453 @Override
7454 public void binderDied() {
7455 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7456 }
7457 }
7458
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007459 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7460 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7461 if (npi.providerId == providerId) return true;
7462 }
7463 return false;
7464 }
7465
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007466 /**
7467 * Register or update a network offer.
7468 * @param newOffer The new offer. If the callback member is the same as an existing
7469 * offer, it is an update of that offer.
7470 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007471 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007472 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7473 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007474 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007475 // This may actually happen if a provider updates its score or registers and then
7476 // immediately unregisters. The offer would still be in the handler queue, but the
7477 // provider would have been removed.
7478 if (DBG) log("Received offer from an unregistered provider");
7479 return;
7480 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007481 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7482 if (null != existingOffer) {
7483 handleUnregisterNetworkOffer(existingOffer);
7484 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007485 if (DBG) {
7486 // handleUnregisterNetworkOffer has already logged the old offer
7487 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7488 }
7489 } else {
7490 if (DBG) {
7491 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7492 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007493 }
7494 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7495 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007496 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007497 } catch (RemoteException e) {
7498 noi.binderDied();
7499 return;
7500 }
7501 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007502 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007503 }
7504
7505 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7506 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007507 if (DBG) {
7508 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7509 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007510
7511 // If the provider removes the offer and dies immediately afterwards this
7512 // function may be called twice in a row, but the array will no longer contain
7513 // the offer.
7514 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007515 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007516 }
7517
7518 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7519 @NonNull final INetworkOfferCallback callback) {
7520 ensureRunningOnConnectivityServiceThread();
7521 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007522 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007523 }
7524 return null;
7525 }
7526
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007527 /**
7528 * Called when receiving LinkProperties directly from a NetworkAgent.
7529 * Stores into |nai| any data coming from the agent that might also be written to the network's
7530 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7531 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007532 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007533 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007534 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7535 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007536 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007537 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007538 }
7539
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007540 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007541 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007542 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007543
Lorenzo Colittid523d142020-04-01 20:16:30 +09007544 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7545 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7546 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007547 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007548
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007549 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007550
7551 // update filtering rules, need to happen after the interface update so netd knows about the
7552 // new interface (the interface name -> index map becomes initialized)
7553 updateVpnFiltering(newLp, oldLp, networkAgent);
7554
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007555 updateMtu(newLp, oldLp);
7556 // TODO - figure out what to do for clat
7557// for (LinkProperties lp : newLp.getStackedLinks()) {
7558// updateMtu(lp, null);
7559// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007560 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007561 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7562 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007563
Erik Klineb9888902016-04-05 13:30:49 +09007564 updateRoutes(newLp, oldLp, netId);
7565 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007566 // Make sure LinkProperties represents the latest private DNS status.
7567 // This does not need to be done before updateDnses because the
7568 // LinkProperties are not the source of the private DNS configuration.
7569 // updateDnses will fetch the private DNS configuration from DnsManager.
7570 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007571
Chalard Jean5b409c72021-02-04 13:12:59 +09007572 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007573 handleApplyDefaultProxy(newLp.getHttpProxy());
7574 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007575 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007576 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007577
7578 updateWakeOnLan(newLp);
7579
Hai Shalome58bdc62021-01-11 18:45:34 -08007580 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7581 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7582 // does, it needs to be merged here.
7583 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7584 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007585
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007586 // TODO - move this check to cover the whole function
7587 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007588 synchronized (networkAgent) {
7589 networkAgent.linkProperties = newLp;
7590 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007591 // Start or stop DNS64 detection and 464xlat according to network state.
7592 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007593 // Notify NSS when relevant events happened. Currently, NSS only cares about
7594 // interface changed to update clat interfaces accounting.
7595 final boolean interfacesChanged = oldLp == null
7596 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7597 if (interfacesChanged) {
7598 notifyIfacesChangedForNetworkStats();
7599 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007600 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7601 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007602 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007603 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007604
7605 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007606 }
7607
Hai Shalome58bdc62021-01-11 18:45:34 -08007608 /**
7609 * @param naData captive portal data from NetworkAgent
7610 * @param apiData captive portal data from capport API
7611 */
7612 @Nullable
7613 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7614 CaptivePortalData apiData) {
7615 if (naData == null || apiData == null) {
7616 return naData == null ? apiData : naData;
7617 }
7618 final CaptivePortalData.Builder captivePortalBuilder =
7619 new CaptivePortalData.Builder(naData);
7620
7621 if (apiData.isCaptive()) {
7622 captivePortalBuilder.setCaptive(true);
7623 }
7624 if (apiData.isSessionExtendable()) {
7625 captivePortalBuilder.setSessionExtendable(true);
7626 }
7627 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7628 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7629 // otherwise data would be inconsistent. Prefer the capport API info if present,
7630 // as it can generally be refreshed more often.
7631 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7632 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7633 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7634 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7635 // No source has time / bytes remaining information: surface the newest refresh time
7636 // for other fields
7637 captivePortalBuilder.setRefreshTime(
7638 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7639 }
7640
Hai Shalom7c6ab402021-02-04 19:34:06 -08007641 // Prioritize the user portal URL from the network agent if the source is authenticated.
7642 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7643 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7644 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7645 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007646 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007647 // Prioritize the venue information URL from the network agent if the source is
7648 // authenticated.
7649 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7650 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7651 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7652 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007653 }
7654 return captivePortalBuilder.build();
7655 }
7656
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007657 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007658 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007659 // marks on unsupported interfaces is harmless.
7660 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7661 return;
7662 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007663
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007664 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7665 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7666
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007667 // Mask/mark of zero will not detect anything interesting.
7668 // Don't install rules unless both values are nonzero.
7669 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007670 return;
7671 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007672
7673 final String prefix = "iface:" + iface;
7674 try {
7675 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007676 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007677 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007678 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007679 }
7680 } catch (Exception e) {
7681 loge("Exception modifying wakeup packet monitoring: " + e);
7682 }
7683
Joel Scherpelza235a812017-05-22 13:47:41 +09007684 }
7685
Junyu Lai970963e2022-10-25 15:46:47 +08007686 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007687 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007688 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007689 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007690 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007691 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007692 for (final String iface : interfaceDiff.added) {
7693 try {
7694 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007695 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007696 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007697 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7698 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007699 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007700 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007701 }
Paul Jensenbff73492014-04-28 10:33:11 -04007702 }
7703 }
Chalard Jean9589e722019-11-19 19:03:53 +09007704 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007705 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007706 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007707 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007708 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007709 } catch (Exception e) {
7710 loge("Exception removing interface: " + e);
7711 }
7712 }
7713 }
7714
Tyler Weare4314862019-12-05 14:55:30 -08007715 // TODO: move to frameworks/libs/net.
7716 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7717 final String nextHop;
7718
7719 switch (route.getType()) {
7720 case RouteInfo.RTN_UNICAST:
7721 if (route.hasGateway()) {
7722 nextHop = route.getGateway().getHostAddress();
7723 } else {
7724 nextHop = INetd.NEXTHOP_NONE;
7725 }
7726 break;
7727 case RouteInfo.RTN_UNREACHABLE:
7728 nextHop = INetd.NEXTHOP_UNREACHABLE;
7729 break;
7730 case RouteInfo.RTN_THROW:
7731 nextHop = INetd.NEXTHOP_THROW;
7732 break;
7733 default:
7734 nextHop = INetd.NEXTHOP_NONE;
7735 break;
7736 }
7737
7738 final RouteInfoParcel rip = new RouteInfoParcel();
7739 rip.ifName = route.getInterface();
7740 rip.destination = route.getDestination().toString();
7741 rip.nextHop = nextHop;
7742 rip.mtu = route.getMtu();
7743
7744 return rip;
7745 }
7746
Paul Jensene0fd4a82014-08-06 15:51:33 -04007747 /**
7748 * Have netd update routes from oldLp to newLp.
7749 * @return true if routes changed between oldLp and newLp
7750 */
Junyu Lai970963e2022-10-25 15:46:47 +08007751 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7752 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007753 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007754 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7755 new CompareOrUpdateResult<>(
7756 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08007757 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08007758 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007759
7760 // add routes before removing old in case it helps with continuous connectivity
7761
Chalard Jean9dd11612018-06-04 16:52:49 +09007762 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007763 for (RouteInfo route : routeDiff.added) {
7764 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007765 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007766 try {
Tyler Weare4314862019-12-05 14:55:30 -08007767 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007768 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007769 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007770 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007771 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007772 }
7773 }
7774 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007775 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007776 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007777 try {
Tyler Weare4314862019-12-05 14:55:30 -08007778 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007779 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007780 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007781 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007782 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007783 }
7784 }
7785
7786 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007787 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007788 try {
Tyler Weare4314862019-12-05 14:55:30 -08007789 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007790 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007791 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007792 }
7793 }
Tyler Weare4314862019-12-05 14:55:30 -08007794
7795 for (RouteInfo route : routeDiff.updated) {
7796 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7797 try {
7798 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7799 } catch (Exception e) {
7800 loge("Exception in networkUpdateRouteParcel: " + e);
7801 }
7802 }
7803 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7804 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007805 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007806
Junyu Lai970963e2022-10-25 15:46:47 +08007807 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7808 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09007809 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7810 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007811 }
Erik Klineb9888902016-04-05 13:30:49 +09007812
Erik Kline31b4a9e2018-01-11 21:07:29 +09007813 if (DBG) {
7814 final Collection<InetAddress> dnses = newLp.getDnsServers();
7815 log("Setting DNS servers for network " + netId + " to " + dnses);
7816 }
Erik Klineb9888902016-04-05 13:30:49 +09007817 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007818 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007819 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007820 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007821 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007822 }
Erik Kline54e35c02017-04-07 15:29:29 +09007823 }
7824
Junyu Lai970963e2022-10-25 15:46:47 +08007825 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7826 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007827 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7828 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007829 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7830 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007831
7832 if (!wasFiltering && !needsFiltering) {
7833 // Nothing to do.
7834 return;
7835 }
7836
7837 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7838 // Nothing changed.
7839 return;
7840 }
7841
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007842 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007843 if (ranges == null || ranges.isEmpty()) {
7844 return;
7845 }
7846
Qingxi Libb8da982020-01-17 17:54:27 -08007847 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007848 // TODO: this create a window of opportunity for apps to receive traffic between the time
7849 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007850 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007851 // old rules are being removed.
7852 if (wasFiltering) {
7853 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7854 }
7855 if (needsFiltering) {
7856 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7857 }
7858 }
7859
Valentin Iftime9fa35092019-09-24 13:32:13 +02007860 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007861 if (mWolSupportedInterfaces == null) {
7862 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007863 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007864 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007865 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7866 }
7867
Luke Huangb913c812018-08-24 20:33:16 +08007868 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007869 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007870 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007871 }
7872 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007873 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007874 }
Luke Huangb913c812018-08-24 20:33:16 +08007875 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007876 }
7877
Chalard Jean62edfd82019-12-02 18:39:29 +09007878 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7879 @NonNull final NetworkCapabilities newNc) {
7880 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7881 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007882 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007883 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007884 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007885 } catch (RemoteException | ServiceSpecificException e) {
7886 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007887 }
7888 }
7889 }
7890
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007891 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007892 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007893 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007894 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007895 underlyingNetworks = underlyingNetworksOrDefault(
7896 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09007897 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007898 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7899 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007900 // metered if any underlying is metered, or originally declared metered by the agent.
7901 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007902 boolean roaming = false; // roaming if any underlying is roaming
7903 boolean congested = false; // congested if any underlying is congested
7904 boolean suspended = true; // suspended if all underlying are suspended
7905
7906 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007907 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007908 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007909 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007910 for (Network underlyingNetwork : underlyingNetworks) {
7911 final NetworkAgentInfo underlying =
7912 getNetworkAgentInfoForNetwork(underlyingNetwork);
7913 if (underlying == null) continue;
7914
7915 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7916 hadUnderlyingNetworks = true;
7917 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007918 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007919 }
7920
7921 // Merge capabilities of this underlying network. For bandwidth, assume the
7922 // worst case.
7923 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7924 underlyingCaps.getLinkDownstreamBandwidthKbps());
7925 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7926 underlyingCaps.getLinkUpstreamBandwidthKbps());
7927 // If this underlying network is metered, the VPN is metered (it may cost money
7928 // to send packets on this network).
7929 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7930 // If this underlying network is roaming, the VPN is roaming (the billing structure
7931 // is different than the usual, local one).
7932 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7933 // If this underlying network is congested, the VPN is congested (the current
7934 // condition of the network affects the performance of this network).
7935 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7936 // If this network is not suspended, the VPN is not suspended (the VPN
7937 // is able to transfer some data).
7938 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007939 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007940 }
7941 }
7942 if (!hadUnderlyingNetworks) {
7943 // No idea what the underlying networks are; assume reasonable defaults
7944 metered = true;
7945 roaming = false;
7946 congested = false;
7947 suspended = false;
7948 }
7949
Chalard Jean1d420b32022-10-12 16:39:37 +09007950 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007951 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7952 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7953 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7954 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7955 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7956 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007957 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007958 }
7959
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007960 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007961 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7962 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7963 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007964 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007965 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007966 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007967 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007968 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7969 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007970 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007971 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007972 if (nai.everConnected()
7973 && !nai.isVPN()
7974 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007975 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007976 // does not cause any request (that is not a listen) currently matching that agent to
7977 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007978 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007979 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007980 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007981 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007982 }
7983
Paul Jensen53f08952015-06-16 14:27:36 -04007984 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007985 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007986 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007987 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007988 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007989 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007990 }
Chalard Jean254bd162022-08-25 13:04:51 +09007991 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007992 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007993 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007994 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007995 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007996 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007997 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007998 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007999 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008000 }
Chalard Jean254bd162022-08-25 13:04:51 +09008001 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008002 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8003 } else {
8004 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8005 }
lucasline117e2e2019-10-22 18:27:33 +08008006 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008007
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008008 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008009 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8010 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008011 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008012 }
8013
Lorenzo Colittibd079452021-07-02 11:47:57 +09008014 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008015 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008016 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008017 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008018 }
8019
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008020 return newNc;
8021 }
8022
Lorenzo Colitti44840702021-01-11 22:27:57 +09008023 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8024 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8025 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8026 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8027 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8028 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8029 if (prevSuspended != suspended) {
8030 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8031 // onResumed have been removed.
8032 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8033 : ConnectivityManager.CALLBACK_RESUMED);
8034 }
8035 if (prevSuspended != suspended || prevRoaming != roaming) {
8036 // updateNetworkInfo will mix in the suspended info from the capabilities and
8037 // take appropriate action for the network having possibly changed state.
8038 updateNetworkInfo(nai, nai.networkInfo);
8039 }
8040 }
8041
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008042 /**
8043 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8044 *
8045 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8046 * capabilities we manage and store in {@code nai}, such as validated status and captive
8047 * portal status)
8048 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8049 * potentially triggers rematches.
8050 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8051 * change.)
8052 *
8053 * @param oldScore score of the network before any of the changes that prompted us
8054 * to call this function.
8055 * @param nai the network having its capabilities updated.
8056 * @param nc the new network capabilities.
8057 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008058 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008059 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008060 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008061 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008062 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8063 if (null != differences) {
8064 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8065 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008066 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008067 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008068
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008069 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008070 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008071 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008072
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008073 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008074 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8075 // the change we're processing can't affect any requests, it can only affect the listens
8076 // on this network. We might have been called by rematchNetworkAndRequests when a
8077 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008078 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008079 } else {
8080 // If the requestable capabilities have changed or the score changed, we can't have been
8081 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008082 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008083 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008084 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008085 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008086
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008087 final boolean oldMetered = prevNc.isMetered();
8088 final boolean newMetered = newNc.isMetered();
8089 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008090
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008091 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008092 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8093 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008094 }
junyulaif2c67e42018-08-07 19:50:45 +08008095
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008096 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8097 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008098
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008099 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008100 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008101 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008102 }
8103
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008104 // This network might have been underlying another network. Propagate its capabilities.
8105 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008106
8107 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008108 mDnsManager.updateTransportsForNetwork(
8109 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008110 }
lucaslin53e8a262021-06-08 01:43:59 +08008111
8112 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008113 }
8114
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008115 /** Convenience method to update the capabilities for a given network. */
8116 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008117 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008118 }
8119
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008120 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008121 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008122 *
8123 * Ingress interface filtering enforces that all apps under the given network can only receive
8124 * packets from the network's interface (and loopback). This is important for VPNs because
8125 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8126 * non-VPN interfaces.
8127 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008128 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008129 * 1. the network is an app VPN (not legacy VPN)
8130 * 2. the VPN does not allow bypass
8131 * 3. the VPN is fully-routed
8132 * 4. the VPN interface is non-null
8133 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008134 * @see INetd#firewallAddUidInterfaceRules
8135 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008136 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008137 @Nullable
8138 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008139 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008140 if (nc == null || lp == null) return null;
8141 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008142 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008143 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008144 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008145 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008146 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008147 && !lp.hasExcludeRoute()) {
8148 return lp.getInterfaceName();
8149 }
8150 return null;
8151 }
8152
8153 /**
8154 * Returns whether we need to set interface filtering rule or not
8155 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008156 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008157 String isolationIface) {
8158 // Allow rules are always needed if VPN isolation is enabled.
8159 if (isolationIface != null) return true;
8160
8161 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8162 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8163 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8164 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008165 }
8166
Chiachang Wang28afaff2020-12-10 22:24:47 +08008167 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8168 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8169 int index = 0;
8170 for (UidRange range : ranges) {
8171 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8172 index++;
8173 }
8174 return stableRanges;
8175 }
8176
Chalard Jeane6c95272022-01-25 21:04:21 +09008177 private static UidRangeParcel[] intsToUidRangeStableParcels(
8178 final @NonNull ArraySet<Integer> uids) {
8179 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8180 int index = 0;
8181 for (int uid : uids) {
8182 stableRanges[index] = new UidRangeParcel(uid, uid);
8183 index++;
8184 }
8185 return stableRanges;
8186 }
8187
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008188 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8189 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8190 for (int i = 0; i < ranges.length; i++) {
8191 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8192 }
8193 return stableRanges;
8194 }
8195
Ken Chen5e65a852020-12-24 12:59:10 +08008196 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8197 int[] exemptUids) {
8198 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8199 try {
8200 mNetd.socketDestroy(ranges, exemptUids);
8201 } catch (Exception e) {
8202 loge("Exception in socket destroy: ", e);
8203 }
8204 }
8205 }
8206
paulhuaa0743d2021-05-26 21:56:03 +08008207 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008208 int[] exemptUids = new int[2];
8209 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8210 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8211 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8212 exemptUids[0] = VPN_UID;
8213 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8214 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8215
8216 maybeCloseSockets(nai, ranges, exemptUids);
8217 try {
8218 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008219 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008220 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008221 } else {
paulhu0e79d952021-06-09 16:11:35 +08008222 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008223 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008224 }
8225 } catch (Exception e) {
8226 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8227 " on netId " + nai.network.netId + ". " + e);
8228 }
8229 maybeCloseSockets(nai, ranges, exemptUids);
8230 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008231
lucaslin53e8a262021-06-08 01:43:59 +08008232 private boolean isProxySetOnAnyDefaultNetwork() {
8233 ensureRunningOnConnectivityServiceThread();
8234 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8235 final NetworkAgentInfo nai = nri.getSatisfier();
8236 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8237 return true;
8238 }
8239 }
8240 return false;
8241 }
8242
8243 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8244 NetworkCapabilities newNc) {
8245 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8246 // the proxy might be changed since the default network satisfied by the apps might also
8247 // changed.
8248 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8249 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008250 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8251 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008252 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008253 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8254 mProxyTracker.sendProxyBroadcast();
8255 }
8256 }
8257
Chalard Jeane6c95272022-01-25 21:04:21 +09008258 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8259 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008260 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8261 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008262 if (null == prevRanges) prevRanges = new ArraySet<>();
8263 if (null == newRanges) newRanges = new ArraySet<>();
8264 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8265
8266 prevRanges.removeAll(newRanges);
8267 newRanges.removeAll(prevRangesCopy);
8268
8269 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008270 // When updating the VPN uid routing rules, add the new range first then remove the old
8271 // range. If old range were removed first, there would be a window between the old
8272 // range being removed and the new range being added, during which UIDs contained
8273 // in both ranges are not subject to any VPN routing rules. Adding new range before
8274 // removing old range works because, unlike the filtering rules below, it's possible to
8275 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008276 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8277 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8278 // [1-5] & [1-2],[4-5] == [3]
8279 // Then we can do:
8280 // maybeCloseSockets([3])
8281 // mNetd.networkAddUidRanges([1-2],[4-5])
8282 // mNetd.networkRemoveUidRanges([1-5])
8283 // maybeCloseSockets([3])
8284 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8285 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008286 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008287 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008288 }
8289 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008290 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008291 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008292 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8293 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008294 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8295 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008296 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008297 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008298 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8299 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8300 // were added first and then newRanges got removed later, there would be only one uid
8301 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8302 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8303 // Note that this is in contrast with the (more robust) update of VPN routing rules
8304 // above, where the addition of new ranges happens before the removal of old ranges.
8305 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8306 // to be removed will never overlap with the new range to be added.
8307 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008308 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8309 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008310 }
8311 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008312 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008313 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008314 } catch (Exception e) {
8315 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008316 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008317 }
8318 }
8319
Chalard Jeande665262022-02-25 16:12:12 +09008320 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008321 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8322 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008323 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8324 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008325 if (prevEmpty && newEmpty) return;
8326
8327 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008328 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008329 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008330 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008331
8332 if (prevUids.equals(newUids)) return;
8333
8334 // This implementation is very simple and vastly faster for sets of Integers than
8335 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8336 // a key computed from the value and has storage for that.
8337 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8338 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8339 toRemove.removeAll(newUids);
8340 toAdd.removeAll(prevUids);
8341
8342 try {
8343 if (!toAdd.isEmpty()) {
8344 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8345 nai.network.netId,
8346 intsToUidRangeStableParcels(toAdd),
8347 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8348 }
8349 if (!toRemove.isEmpty()) {
8350 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8351 nai.network.netId,
8352 intsToUidRangeStableParcels(toRemove),
8353 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8354 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008355 } catch (ServiceSpecificException e) {
8356 // Has the interface disappeared since the network was built ?
8357 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008358 } catch (RemoteException e) {
8359 // Netd died. This usually causes a runtime restart anyway.
8360 }
8361 }
8362
Junyu Lai2ed7d412022-10-07 16:52:21 +08008363 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8364 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008365 ensureRunningOnConnectivityServiceThread();
8366
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008367 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008368 // Ignore updates for disconnected networks
8369 return;
8370 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008371 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008372 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008373 + "; created=" + nai.getCreatedTime()
8374 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008375 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008376 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8377 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008378 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008379 }
8380
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008381 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8382 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008383 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008384 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008385 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008386 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8387 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8388 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008389 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8390 // need to be sent as a separate extra.
8391 final NetworkRequest req = nri.isMultilayerRequest()
8392 ? nri.getActiveRequest()
8393 // Non-multilayer listen requests do not have an active request
8394 : nri.mRequests.get(0);
8395 if (req == null) {
8396 Log.wtf(TAG, "No request in NRI " + nri);
8397 }
8398 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008399 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008400 sendIntent(nri.mPendingIntent, intent);
8401 }
8402 // else not handled
8403 }
8404
8405 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8406 mPendingIntentWakeLock.acquire();
8407 try {
8408 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008409 final BroadcastOptions options = BroadcastOptions.makeBasic();
8410 if (SdkLevel.isAtLeastT()) {
8411 // Explicitly disallow the receiver from starting activities, to prevent apps from
8412 // utilizing the PendingIntent as a backdoor to do this.
8413 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8414 }
8415 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8416 null /* requiredPermission */,
8417 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008418 } catch (PendingIntent.CanceledException e) {
8419 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8420 mPendingIntentWakeLock.release();
8421 releasePendingNetworkRequest(pendingIntent);
8422 }
8423 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8424 }
8425
8426 @Override
8427 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8428 String resultData, Bundle resultExtras) {
8429 if (DBG) log("Finished sending " + pendingIntent);
8430 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008431 // Release with a delay so the receiving client has an opportunity to put in its
8432 // own request.
8433 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008434 }
8435
Chalard Jean46bfbf02022-02-02 00:56:25 +09008436 // networkAgent is only allowed to be null if notificationType is
8437 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8438 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008439 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008440 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008441 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008442 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008443 // Default request has no msgr. Also prevents callbacks from being invoked for
8444 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8445 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8446 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008447 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008448 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008449 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008450 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008451 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008452 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008453 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008454 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8455 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008456 }
Roshan Pius951c0032020-12-22 15:10:42 -08008457 final boolean includeLocationSensitiveInfo =
8458 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008459 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008460 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008461 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008462 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008463 networkCapabilitiesRestrictedForCallerPermissions(
8464 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8465 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008466 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008467 nri.mCallingAttributionTag);
8468 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008469 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8470 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008471 // For this notification, arg1 contains the blocked status.
8472 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008473 break;
8474 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008475 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008476 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008477 break;
8478 }
8479 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008480 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008481 final NetworkCapabilities netCap =
8482 networkCapabilitiesRestrictedForCallerPermissions(
8483 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8484 putParcelable(
8485 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008486 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008487 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008488 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008489 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008490 break;
8491 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008492 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008493 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8494 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008495 break;
8496 }
junyulaif2c67e42018-08-07 19:50:45 +08008497 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008498 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008499 msg.arg1 = arg1;
8500 break;
8501 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008502 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008503 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008504 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008505 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008506 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008507 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008508 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008509 }
James Mattis45d81842021-01-10 14:24:24 -08008510 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008511 } catch (RemoteException e) {
8512 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008513 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008514 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008515 }
8516
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008517 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8518 bundle.putParcelable(t.getClass().getSimpleName(), t);
8519 }
8520
Chalard Jean0702f982021-09-16 21:50:07 +09008521 /**
8522 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8523 *
8524 * When a request should be assigned to a new network, it is normally lingered to give
8525 * time for apps to gracefully migrate their connections. When both networks are on the same
8526 * radio, but that radio can't do time-sharing efficiently, this may end up being
8527 * counter-productive because any traffic on the old network may drastically reduce the
8528 * performance of the new network.
8529 * The stack supports a configuration to let modem vendors state that their radio can't
8530 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8531 * from one cell network to another can't be done gracefully.
8532 *
8533 * @param oldNai the old network serving the request
8534 * @param newNai the new network serving the request
8535 * @return whether the switch can be graceful
8536 */
8537 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8538 @NonNull final NetworkAgentInfo newSatisfier) {
8539 if (mCellularRadioTimesharingCapable) return true;
8540 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8541 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8542 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8543 }
8544
Paul Jensenaf94b982014-09-30 15:37:41 -04008545 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008546 if (nai.numRequestNetworkRequests() != 0) {
8547 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8548 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008549 // Ignore listening and track default requests.
8550 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008551 loge("Dead network still had at least " + nr);
8552 break;
8553 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008554 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008555 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008556 }
8557
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008558 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8559 if (oldNetwork == null) {
8560 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8561 return;
8562 }
Chalard Jean49707572019-12-10 21:07:02 +09008563 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008564
8565 // If we get here it means that the last linger timeout for this network expired. So there
8566 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008567 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008568
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008569 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008570 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008571 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008572 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008573 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008574 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008575 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008576 }
8577
James Mattise3ef1912020-12-20 11:09:58 -08008578 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8579 boolean isDefaultChanged = false;
8580 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8581 final NetworkReassignment.RequestReassignment reassignment =
8582 changes.getReassignment(defaultRequestInfo);
8583 if (null == reassignment) {
8584 continue;
8585 }
8586 // reassignment only contains those instances where the satisfying network changed.
8587 isDefaultChanged = true;
8588 // Notify system services of the new default.
8589 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8590 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008591
James Mattise3ef1912020-12-20 11:09:58 -08008592 if (isDefaultChanged) {
8593 // Hold a wakelock for a short time to help apps in migrating to a new default.
8594 scheduleReleaseNetworkTransitionWakelock();
8595 }
8596 }
8597
8598 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8599 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8600 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8601 if (DBG) {
8602 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8603 }
Chalard Jean8e382112019-12-03 20:45:30 +09008604
James Mattisd31bdfa2020-12-23 16:37:26 -08008605 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8606 if (newDefaultNetwork != null) {
8607 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008608 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008609
James Mattisd31bdfa2020-12-23 16:37:26 -08008610 // Set an app level managed default and return since further processing only applies to the
8611 // default network.
8612 if (mDefaultRequest != nri) {
8613 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8614 return;
8615 }
8616
8617 makeDefaultNetwork(newDefaultNetwork);
8618
James Mattise3ef1912020-12-20 11:09:58 -08008619 if (oldDefaultNetwork != null) {
8620 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8621 }
8622 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008623 handleApplyDefaultProxy(null != newDefaultNetwork
8624 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8625 updateTcpBufferSizes(null != newDefaultNetwork
8626 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008627 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008628 }
8629
James Mattisd31bdfa2020-12-23 16:37:26 -08008630 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8631 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8632 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8633 try {
8634 if (VDBG) {
8635 log("Setting default network for " + nri
8636 + " using UIDs " + nri.getUids()
8637 + " with old network " + (oldDefaultNetwork != null
8638 ? oldDefaultNetwork.network().getNetId() : "null")
8639 + " and new network " + (newDefaultNetwork != null
8640 ? newDefaultNetwork.network().getNetId() : "null"));
8641 }
8642 if (nri.getUids().isEmpty()) {
8643 throw new IllegalStateException("makeDefaultForApps called without specifying"
8644 + " any applications to set as the default." + nri);
8645 }
8646 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008647 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008648 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008649 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008650 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008651 }
8652 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008653 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008654 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008655 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008656 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008657 }
8658 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008659 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008660 }
8661 }
8662
8663 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8664 try {
8665 if (null != newDefaultNetwork) {
8666 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8667 } else {
8668 mNetd.networkClearDefault();
8669 }
8670 } catch (RemoteException | ServiceSpecificException e) {
8671 loge("Exception setting default network :" + e);
8672 }
8673 }
8674
Chalard Jean05cbe972019-12-09 11:50:38 +09008675 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008676 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008677 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008678 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008679 processNewlySatisfiedListenRequests(nai);
8680 }
8681
8682 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008683 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8684 if (nri.isMultilayerRequest()) {
8685 continue;
8686 }
8687 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008688 if (!nr.isListen()) continue;
8689 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008690 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008691 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8692 }
8693 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008694 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008695
Chalard Jeancd397a22019-11-22 22:33:33 +09008696 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008697 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8698 if (nri.isMultilayerRequest()) {
8699 continue;
8700 }
8701 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008702 if (!nr.isListen()) continue;
8703 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8704 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008705 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008706 }
8707 }
8708 }
8709
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008710 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008711 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008712 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008713 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008714 @Nullable public final NetworkRequest mOldNetworkRequest;
8715 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008716 @Nullable public final NetworkAgentInfo mOldNetwork;
8717 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008718 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008719 @Nullable final NetworkRequest oldNetworkRequest,
8720 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008721 @Nullable final NetworkAgentInfo oldNetwork,
8722 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008723 mNetworkRequestInfo = networkRequestInfo;
8724 mOldNetworkRequest = oldNetworkRequest;
8725 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008726 mOldNetwork = oldNetwork;
8727 mNewNetwork = newNetwork;
8728 }
Chalard Jean49707572019-12-10 21:07:02 +09008729
8730 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008731 final NetworkRequest requestToShow = null != mNewNetworkRequest
8732 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8733 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008734 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8735 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008736 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008737 }
8738
Chalard Jean46a62372019-12-10 21:25:24 +09008739 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008740
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008741 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008742 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008743 }
8744
8745 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008746 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008747 // The code is never supposed to add two reassignments of the same request. Make
8748 // sure this stays true, but without imposing this expensive check on all
8749 // reassignments on all user devices.
8750 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008751 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008752 throw new IllegalStateException("Trying to reassign ["
8753 + reassignment + "] but already have ["
8754 + existing + "]");
8755 }
8756 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008757 }
Chalard Jean46a62372019-12-10 21:25:24 +09008758 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008759 }
8760
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008761 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008762 // the passed request.
8763 @Nullable
8764 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008765 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008766 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008767 }
8768 return null;
8769 }
Chalard Jean49707572019-12-10 21:07:02 +09008770
8771 public String toString() {
8772 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8773 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008774 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008775 for (final RequestReassignment rr : getRequestReassignments()) {
8776 sj.add(rr.toString());
8777 }
8778 return sj.toString();
8779 }
8780
8781 public String debugString() {
8782 final StringBuilder sb = new StringBuilder();
8783 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008784 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008785 for (final RequestReassignment rr : getRequestReassignments()) {
8786 sb.append("\n ").append(rr);
8787 }
8788 return sb.append("\n").toString();
8789 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008790 }
8791
Chalard Jean24344d72019-12-04 13:32:31 +09008792 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008793 @Nullable final NetworkRequest previousRequest,
8794 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008795 @Nullable final NetworkAgentInfo previousSatisfier,
8796 @Nullable final NetworkAgentInfo newSatisfier,
8797 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008798 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008799 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008800 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008801 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008802 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008803 }
James Mattisa076c532020-12-02 14:12:41 -08008804 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008805 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008806 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008807 // If this network switch can't be supported gracefully, the request is not
8808 // lingered. This allows letting go of the network sooner to reclaim some
8809 // performance on the new network, since the radio can't do both at the same
8810 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008811 //
8812 // Also don't linger the request if the old network has been destroyed.
8813 // A destroyed network does not provide actual network connectivity, so
8814 // lingering it is not useful. In particular this ensures that a destroyed
8815 // network is outscored by its replacement,
8816 // then it is torn down immediately instead of being lingered, and any apps that
8817 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008818 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8819 }
Chalard Jean24344d72019-12-04 13:32:31 +09008820 } else {
8821 if (VDBG || DDBG) log(" accepting network in place of null");
8822 }
junyulai0ac374f2020-12-14 18:41:52 +08008823
8824 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8825 // and immediately satisfies a request then remove the timer. This will happen for
8826 // all networks except in the case of an underlying network for a VCN.
8827 if (newSatisfier.isNascent()) {
8828 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008829 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008830 }
8831
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008832 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008833 newSatisfier.unlingerRequest(newRequest.requestId);
8834 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008835 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008836 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008837 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008838 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008839 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008840 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008841 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008842 }
James Mattisa076c532020-12-02 14:12:41 -08008843 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008844 }
James Mattisa076c532020-12-02 14:12:41 -08008845 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008846 }
8847
James Mattisa076c532020-12-02 14:12:41 -08008848 /**
8849 * This function is triggered when something can affect what network should satisfy what
8850 * request, and it computes the network reassignment from the passed collection of requests to
8851 * network match to the one that the system should now have. That data is encoded in an
8852 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8853 * satisfier.
8854 *
8855 * After the reassignment is computed, it is applied to the state objects.
8856 *
8857 * @param networkRequests the nri objects to evaluate for possible network reassignment
8858 * @return NetworkReassignment listing of proposed network assignment changes
8859 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008860 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008861 private NetworkReassignment computeNetworkReassignment(
8862 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008863 final NetworkReassignment changes = new NetworkReassignment();
8864
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008865 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008866 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008867 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008868 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008869 }
Chalard Jean857a1712019-12-10 21:08:07 +09008870
James Mattisa076c532020-12-02 14:12:41 -08008871 for (final NetworkRequestInfo nri : networkRequests) {
8872 // Non-multilayer listen requests can be ignored.
8873 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8874 continue;
8875 }
8876 NetworkAgentInfo bestNetwork = null;
8877 NetworkRequest bestRequest = null;
8878 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008879 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008880 // Stop evaluating as the highest possible priority request is satisfied.
8881 if (null != bestNetwork) {
8882 bestRequest = req;
8883 break;
8884 }
8885 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008886 if (null == bestNetwork && isDefaultBlocked(nri)) {
8887 // Remove default networking if disallowed for managed default requests.
8888 bestNetwork = mNoServiceNetwork;
8889 }
8890 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008891 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008892 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008893 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008894 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008895 }
8896 return changes;
8897 }
8898
James Mattisa076c532020-12-02 14:12:41 -08008899 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8900 return new HashSet<>(mNetworkRequests.values());
8901 }
8902
Paul Jensenc88b39b2015-06-16 14:27:36 -04008903 /**
James Mattisa076c532020-12-02 14:12:41 -08008904 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008905 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008906 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008907 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008908 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8909 }
8910
8911 /**
8912 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8913 * being disconnected.
8914 */
8915 private void rematchNetworksAndRequests(
8916 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8917 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008918 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008919 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008920 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008921 final long computed = SystemClock.elapsedRealtime();
8922 applyNetworkReassignment(changes, start);
8923 final long applied = SystemClock.elapsedRealtime();
8924 issueNetworkNeeds();
8925 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008926 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008927 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8928 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008929 log(changes.debugString());
8930 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008931 // Shorter form, only one line of log
8932 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8933 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008934 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008935 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008936
Chalard Jeand7f762d2019-12-10 19:01:29 +09008937 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008938 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008939 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008940
8941 // Since most of the time there are only 0 or 1 background networks, it would probably
8942 // be more efficient to just use an ArrayList here. TODO : measure performance
8943 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8944 for (final NetworkAgentInfo nai : nais) {
8945 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8946 }
8947
Chalard Jeand7f762d2019-12-10 19:01:29 +09008948 // First, update the lists of satisfied requests in the network agents. This is necessary
8949 // because some code later depends on this state to be correct, most prominently computing
8950 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008951 for (final NetworkReassignment.RequestReassignment event :
8952 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008953 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8954 event.mOldNetworkRequest, event.mNewNetworkRequest,
8955 event.mOldNetwork, event.mNewNetwork,
8956 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008957 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008958
James Mattise3ef1912020-12-20 11:09:58 -08008959 // Process default network changes if applicable.
8960 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008961
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008962 // Notify requested networks are available after the default net is switched, but
8963 // before LegacyTypeTracker sends legacy broadcasts
8964 for (final NetworkReassignment.RequestReassignment event :
8965 changes.getRequestReassignments()) {
8966 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008967 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008968 } else {
James Mattisa076c532020-12-02 14:12:41 -08008969 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008970 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008971 }
8972 }
8973
junyulai0ac374f2020-12-14 18:41:52 +08008974 // Update the inactivity state before processing listen callbacks, because the background
8975 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008976 // just yet though, because they have to be sent after the listens are processed to keep
8977 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008978 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008979 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008980 // Rematching may have altered the inactivity state of some networks, so update all
8981 // inactivity timers. updateInactivityState reads the state from the network agent
8982 // and does nothing if the state has not changed : the source of truth is controlled
8983 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8984 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008985 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008986 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008987 }
8988 }
8989
Chalard Jeanb10ab412019-12-11 14:12:30 +09008990 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008991 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008992 // Process listen requests and update capabilities if the background state has
8993 // changed for this network. For consistency with previous behavior, send onLost
8994 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008995 processNewlyLostListenRequests(nai);
8996 if (oldBackground != nai.isBackgroundNetwork()) {
8997 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008998 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008999 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009000 }
9001
junyulai0ac374f2020-12-14 18:41:52 +08009002 for (final NetworkAgentInfo nai : inactiveNetworks) {
9003 // For nascent networks, if connecting with no foreground request, skip broadcasting
9004 // LOSING for backward compatibility. This is typical when mobile data connected while
9005 // wifi connected with mobile data always-on enabled.
9006 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009007 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009008 }
9009
James Mattise3ef1912020-12-20 11:09:58 -08009010 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009011
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009012 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009013 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009014 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009015 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009016 // This network has active linger timers and no requests, but is not
9017 // lingering. Linger it.
9018 //
9019 // One way (the only way?) this can happen if this network is unvalidated
9020 // and became unneeded due to another network improving its score to the
9021 // point where this network will no longer be able to satisfy any requests
9022 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009023 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009024 notifyNetworkLosing(nai, now);
9025 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009026 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009027 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009028 teardownUnneededNetwork(nai);
9029 }
9030 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009031 }
9032 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009033
Chalard Jean62edfd82019-12-02 18:39:29 +09009034 /**
9035 * Apply a change in background state resulting from rematching networks with requests.
9036 *
9037 * During rematch, a network may change background states by starting to satisfy or stopping
9038 * to satisfy a foreground request. Listens don't count for this. When a network changes
9039 * background states, its capabilities need to be updated and callbacks fired for the
9040 * capability change.
9041 *
9042 * @param nai The network that changed background states
9043 */
9044 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9045 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9046 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9047 updateNetworkPermissions(nai, newNc);
9048 nai.getAndSetNetworkCapabilities(newNc);
9049 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9050 }
9051
Chalard Jeanf0344532019-11-19 19:23:38 +09009052 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009053 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009054 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009055 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9056 changes.getReassignment(mDefaultRequest);
9057 final NetworkAgentInfo oldDefaultNetwork =
9058 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9059 final NetworkAgentInfo newDefaultNetwork =
9060 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009061
Chalard Jean5b409c72021-02-04 13:12:59 +09009062 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009063 // Maintain the illusion : since the legacy API only understands one network at a time,
9064 // if the default network changed, apps should see a disconnected broadcast for the
9065 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009066 if (oldDefaultNetwork != null) {
9067 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9068 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009069 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009070 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009071 // The new default network can be newly null if and only if the old default
9072 // network doesn't satisfy the default request any more because it lost a
9073 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009074 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009075 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009076 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009077 }
9078 }
9079
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009080 // Now that all the callbacks have been sent, send the legacy network broadcasts
9081 // as needed. This is necessary so that legacy requests correctly bind dns
9082 // requests to this network. The legacy users are listening for this broadcast
9083 // and will generally do a dns request so they can ensureRouteToHost and if
9084 // they do that before the callbacks happen they'll use the default network.
9085 //
9086 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9087 // callbacks, but if apps can receive the broadcast before the callback, they still might
9088 // have an inconsistent view of networking.
9089 //
9090 // This *does* introduce a race where if the user uses the new api
9091 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9092 // they may get old info. Reverse this after the old startUsing api is removed.
9093 // This is on top of the multiple intent sequencing referenced in the todo above.
9094 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009095 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009096 addNetworkToLegacyTypeTracker(nai);
9097 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009098 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009099 }
9100
Chalard Jean0354d8c2021-01-12 10:58:56 +09009101 private void issueNetworkNeeds() {
9102 ensureRunningOnConnectivityServiceThread();
9103 for (final NetworkOfferInfo noi : mNetworkOffers) {
9104 issueNetworkNeeds(noi);
9105 }
9106 }
9107
9108 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9109 ensureRunningOnConnectivityServiceThread();
9110 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9111 informOffer(nri, noi.offer, mNetworkRanker);
9112 }
9113 }
9114
9115 /**
9116 * Inform a NetworkOffer about any new situation of a request.
9117 *
9118 * This function handles updates to offers. A number of events may happen that require
9119 * updating the registrant for this offer about the situation :
9120 * • The offer itself was updated. This may lead the offer to no longer being able
9121 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9122 * or conversely being strengthened enough to beat the satisfier (and therefore
9123 * start being needed)
9124 * • The network satisfying a request changed (including cases where the request
9125 * starts or stops being satisfied). The new network may be a stronger or weaker
9126 * match than the old one, possibly affecting whether the offer is needed.
9127 * • The network satisfying a request updated their score. This may lead the offer
9128 * to no longer be able to beat it if the current satisfier got better, or
9129 * conversely start being a good choice if the current satisfier got weaker.
9130 *
9131 * @param nri The request
9132 * @param offer The offer. This may be an updated offer.
9133 */
9134 private static void informOffer(@NonNull NetworkRequestInfo nri,
9135 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9136 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9137 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009138
9139 // Multi-layer requests have a currently active request, the one being satisfied.
9140 // Since the system will try to bring up a better network than is currently satisfying
9141 // the request, NetworkProviders need to be told the offers matching the requests *above*
9142 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9143 // not needed, and the offer is needed for the active request iff the offer can beat
9144 // the satisfier.
9145 // For non-multilayer requests, the logic above gracefully degenerates to only the
9146 // last case.
9147 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9148 // providers that the offer is needed for this request, until the active request is found.
9149 // In a second phase, deal with the currently active request. In a third phase, inform
9150 // the providers that offer is unneeded for the remaining requests.
9151
9152 // First phase : inform providers of all requests above the active request.
9153 int i;
9154 for (i = 0; nri.mRequests.size() > i; ++i) {
9155 final NetworkRequest request = nri.mRequests.get(i);
9156 if (activeRequest == request) break; // Found the active request : go to phase 2
9157 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9158 // Since this request is higher-priority than the one currently satisfied, if the
9159 // offer can satisfy it, the provider should try and bring up the network for sure ;
9160 // no need to even ask the ranker – an offer that can satisfy is always better than
9161 // no network. Hence tell the provider so unless it already knew.
9162 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9163 offer.onNetworkNeeded(request);
9164 }
9165 }
9166
9167 // Second phase : deal with the active request (if any)
9168 if (null != activeRequest && activeRequest.isRequest()) {
9169 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009170 // If an offer can satisfy the request, it is considered needed if it is currently
9171 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009172 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009173 && satisfier.factorySerialNumber == offer.providerId
9174 && activeRequest.canBeSatisfiedBy(offer.caps);
9175 final boolean newNeeded = currentlyServing
9176 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009177 if (newNeeded != oldNeeded) {
9178 if (newNeeded) {
9179 offer.onNetworkNeeded(activeRequest);
9180 } else {
9181 // The offer used to be able to beat the satisfier. Now it can't.
9182 offer.onNetworkUnneeded(activeRequest);
9183 }
9184 }
9185 }
9186
9187 // Third phase : inform the providers that the offer isn't needed for any request
9188 // below the active one.
9189 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9190 final NetworkRequest request = nri.mRequests.get(i);
9191 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9192 // Since this request is lower-priority than the one currently satisfied, if the
9193 // offer can satisfy it, the provider should not try and bring up the network.
9194 // Hence tell the provider so unless it already knew.
9195 if (offer.neededFor(request)) {
9196 offer.onNetworkUnneeded(request);
9197 }
9198 }
9199 }
9200
Chalard Jean61c79252019-11-07 23:07:32 +09009201 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9202 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9203 NetworkRequest nr = nai.requestAt(i);
9204 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9205 // legacy type tracker filters out repeat adds
9206 mLegacyTypeTracker.add(nr.legacyType, nai);
9207 }
9208 }
9209
9210 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009211 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009212 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9213 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9214 if (nai.isVPN()) {
9215 mLegacyTypeTracker.add(TYPE_VPN, nai);
9216 }
9217 }
9218
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009219 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009220 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009221 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009222 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009223 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009224 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009225
Chalard Jean254bd162022-08-25 13:04:51 +09009226 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009227 // Don't repeat publish.
9228 if (newInetCondition == mDefaultInetConditionPublished) return;
9229
9230 mDefaultInetConditionPublished = newInetCondition;
9231 sendInetConditionBroadcast(nai.networkInfo);
9232 }
9233
Chalard Jeand61375d2020-01-14 22:46:36 +09009234 @NonNull
9235 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9236 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009237 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009238 final boolean suspended =
9239 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9240 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9241 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9242 // state. This is because the network could have been suspended before connecting,
9243 // or it could be disconnecting while being suspended, and in both these cases
9244 // the state should not be overridden. Note that the only detailed state that
9245 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9246 // worry about multiple different substates of CONNECTED.
9247 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9248 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009249 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9250 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9251 // network agent is created, then goes to suspended, then goes out of suspended without
9252 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009253 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009254 ? NetworkInfo.DetailedState.CONNECTED
9255 : NetworkInfo.DetailedState.CONNECTING,
9256 info.getReason(),
9257 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009258 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009259 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009260 return newInfo;
9261 }
9262
9263 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9264 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9265
Erik Kline99f301b2017-02-15 19:59:17 +09009266 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009267 NetworkInfo oldInfo = null;
9268 synchronized (networkAgent) {
9269 oldInfo = networkAgent.networkInfo;
9270 networkAgent.networkInfo = newInfo;
9271 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009272
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009273 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009274 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9275 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009276 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009277
Chalard Jean254bd162022-08-25 13:04:51 +09009278 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009279 && (state == NetworkInfo.State.CONNECTED
9280 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009281
9282 // A network that has just connected has zero requests and is thus a foreground network.
9283 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9284
Luke Huangfdd11f82019-04-09 18:41:49 +08009285 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009286 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009287 // Initialize the network's capabilities to their starting values according to the
9288 // underlying networks. This ensures that the capabilities are correct before
9289 // anything happens to the network.
9290 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009291 }
Chalard Jean254bd162022-08-25 13:04:51 +09009292 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009293 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009294 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009295 }
9296
Chalard Jean254bd162022-08-25 13:04:51 +09009297 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9298 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009299
lucaslin45e639b2019-04-03 17:09:28 +08009300 // NetworkCapabilities need to be set before sending the private DNS config to
9301 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009302 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9303
Erik Kline9a62f012018-03-21 07:18:33 -07009304 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009305 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9306 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009307
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009308 // If a rate limit has been configured and is applicable to this network (network
9309 // provides internet connectivity), apply it. The tc police filter cannot be attached
9310 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9311 // updateInterfaces -> INetd#networkAddInterface.
9312 // Note: in case of a system server crash, the NetworkController constructor in netd
9313 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9314 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9315 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9316 mIngressRateLimit);
9317 }
9318
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009319 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9320 // command must be sent after updating LinkProperties to maximize chances of
9321 // NetworkMonitor seeing the correct LinkProperties when starting.
9322 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009323 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009324 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009325 }
Chalard Jeand4900722022-02-06 12:25:38 +09009326 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9327 params.networkAgentConfig = networkAgent.networkAgentConfig;
9328 params.networkCapabilities = networkAgent.networkCapabilities;
9329 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9330 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009331 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9332 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9333 // call that would cause a Log.wtf to be emitted from the system_server process, and
9334 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9335 // process to check the interface version, just use an SDK check. NetworkStack will
9336 // always be new enough when running on T+.
9337 if (SdkLevel.isAtLeastT()) {
9338 networkAgent.networkMonitor().notifyNetworkConnected(params);
9339 } else {
9340 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9341 params.networkCapabilities);
9342 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009343 final long delay = activelyPreferBadWifi()
9344 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9345 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9346 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009347
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009348 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9349 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9350 // capabilities, so it only needs to be done once on initial connect, not every time the
9351 // network's capabilities change. Note that we do this before rematching the network,
9352 // so we could decide to tear it down immediately afterwards. That's fine though - on
9353 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9354 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009355 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009356
junyulai0ac374f2020-12-14 18:41:52 +08009357 // Before first rematching networks, put an inactivity timer without any request, this
9358 // allows {@code updateInactivityState} to update the state accordingly and prevent
9359 // tearing down for any {@code unneeded} evaluation in this period.
9360 // Note that the timer will not be rescheduled since the expiry time is
9361 // fixed after connection regardless of the network satisfying other requests or not.
9362 // But it will be removed as soon as the network satisfies a request for the first time.
9363 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9364 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009365 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009366
Paul Jensen05e85ee2014-09-11 11:00:39 -04009367 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009368 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009369
9370 // This has to happen after matching the requests, because callbacks are just requests.
9371 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009372 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009373 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009374 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009375 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009376 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009377 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009378 if (networkAgent.isVPN()) {
9379 // As the active or bound network changes for apps, broadcast the default proxy, as
9380 // apps may need to update their proxy data. This is called after disconnecting from
9381 // VPN to make sure we do not broadcast the old proxy data.
9382 // TODO(b/122649188): send the broadcast only to VPN users.
9383 mProxyTracker.sendProxyBroadcast();
9384 }
Chalard Jean254bd162022-08-25 13:04:51 +09009385 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9386 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009387 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009388 }
9389 }
9390
Chalard Jean28018572020-12-21 18:36:52 +09009391 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009392 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9393 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009394 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009395 }
9396
Erik Kline99f301b2017-02-15 19:59:17 +09009397 // Notify only this one new request of the current state. Transfer all the
9398 // current state by calling NetworkCapabilities and LinkProperties callbacks
9399 // so that callers can be guaranteed to have as close to atomicity in state
9400 // transfer as can be supported by this current API.
9401 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009402 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009403 if (nri.mPendingIntent != null) {
9404 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9405 // Attempt no subsequent state pushes where intents are involved.
9406 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009407 }
Erik Kline99f301b2017-02-15 19:59:17 +09009408
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009409 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009410 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009411 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9412 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9413 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009414 }
9415
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009416 // Notify the requests on this NAI that the network is now lingered.
9417 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009418 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009419 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9420 }
9421
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009422 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9423 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9424 return vpnBlocked
9425 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9426 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9427 }
9428
9429 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9430 if (blockedReasons == BLOCKED_REASON_NONE) {
9431 mUidBlockedReasons.delete(uid);
9432 } else {
9433 mUidBlockedReasons.put(uid, blockedReasons);
9434 }
9435 }
9436
junyulaif2c67e42018-08-07 19:50:45 +08009437 /**
9438 * Notify of the blocked state apps with a registered callback matching a given NAI.
9439 *
9440 * Unlike other callbacks, blocked status is different between each individual uid. So for
9441 * any given nai, all requests need to be considered according to the uid who filed it.
9442 *
9443 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009444 * @param oldMetered True if the previous network capabilities were metered.
9445 * @param newMetered True if the current network capabilities are metered.
9446 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9447 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009448 */
9449 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009450 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9451 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009452
9453 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9454 NetworkRequest nr = nai.requestAt(i);
9455 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009456
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009457 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9458 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9459 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009460 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009461 : oldVpnBlocked;
9462
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009463 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9464 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9465 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009466 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009467 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009468 }
9469 }
9470 }
9471
9472 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009473 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009474 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009475 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009476 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009477 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009478 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009479 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009480 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009481
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009482 final int oldBlockedState = getBlockedState(
9483 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9484 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9485 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009486 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009487 }
junyulaif2c67e42018-08-07 19:50:45 +08009488 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9489 NetworkRequest nr = nai.requestAt(i);
9490 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009491 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009492 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9493 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009494 }
9495 }
9496 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009497 }
9498
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009499 @VisibleForTesting
9500 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009501 // The NetworkInfo we actually send out has no bearing on the real
9502 // state of affairs. For example, if the default connection is mobile,
9503 // and a request for HIPRI has just gone away, we need to pretend that
9504 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9505 // the state to DISCONNECTED, even though the network is of type MOBILE
9506 // and is still connected.
9507 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9508 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009509 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009510 if (state != DetailedState.DISCONNECTED) {
9511 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009512 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009513 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009514 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009515 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9516 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9517 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9518 if (info.isFailover()) {
9519 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9520 nai.networkInfo.setFailover(false);
9521 }
9522 if (info.getReason() != null) {
9523 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9524 }
9525 if (info.getExtraInfo() != null) {
9526 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9527 }
9528 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009529 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009530 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009531 if (newDefaultAgent != null) {
9532 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9533 newDefaultAgent.networkInfo);
9534 } else {
9535 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9536 }
9537 }
9538 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9539 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009540 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009541 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009542 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009543 }
9544 }
9545 }
9546
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009547 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009548 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009549 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009550 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009551 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009552 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9553 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009554 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9555 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009556 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009557 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009558 } else {
9559 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9560 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009561 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009562 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009563
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009564 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9565 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9566 }
9567
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009568 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009569 * Returns the list of all interfaces that could be used by network traffic that does not
9570 * explicitly specify a network. This includes the default network, but also all VPNs that are
9571 * currently connected.
9572 *
9573 * Must be called on the handler thread.
9574 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009575 @NonNull
9576 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009577 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009578 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009579 final Set<Integer> activeNetIds = new ArraySet<>();
9580 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9581 if (nri.isBeingSatisfied()) {
9582 activeNetIds.add(nri.getSatisfier().network().netId);
9583 }
9584 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009585 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009586 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009587 defaultNetworks.add(nai.network);
9588 }
9589 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009590 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009591 }
9592
9593 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009594 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9595 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009596 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009597 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009598 ensureRunningOnConnectivityServiceThread();
9599 String activeIface = null;
9600 LinkProperties activeLinkProperties = getActiveLinkProperties();
9601 if (activeLinkProperties != null) {
9602 activeIface = activeLinkProperties.getInterfaceName();
9603 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009604
junyulai2050bed2021-01-23 09:46:34 +08009605 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009606 try {
junyulaide41fc22021-01-22 22:46:01 +08009607 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009608 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009609 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9610 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009611 } catch (Exception ignored) {
9612 }
9613 }
9614
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009615 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009616 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009617 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009618 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009619 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009620
9621 if (!TextUtils.isEmpty(settingUrl)) {
9622 return settingUrl;
9623 }
9624
9625 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009626 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009627 if (!TextUtils.isEmpty(settingUrl)) {
9628 return settingUrl;
9629 }
9630
9631 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009632 }
9633
9634 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009635 public void startNattKeepalive(Network network, int intervalSeconds,
9636 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009637 enforceKeepalivePermission();
9638 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009639 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009640 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009641 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009642 }
9643
9644 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009645 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009646 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009647 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009648 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009649 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009650 mKeepaliveTracker.startNattKeepalive(
9651 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9652 intervalSeconds, cb,
9653 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9654 } finally {
9655 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9656 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009657 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9658 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009659 }
9660 }
junyulaid05a1922019-01-15 11:32:44 +08009661 }
9662
9663 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009664 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009665 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009666 try {
9667 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009668 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009669 mKeepaliveTracker.startTcpKeepalive(
9670 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9671 } finally {
9672 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9673 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009674 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9675 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009676 }
9677 }
junyulai0835a1e2019-01-08 20:04:33 +08009678 }
9679
9680 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009681 public void stopKeepalive(Network network, int slot) {
9682 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009683 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009684 }
9685
9686 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009687 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009688 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009689
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009690 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009691 final long token = Binder.clearCallingIdentity();
9692 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009693 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9694 UserHandle.getUserHandleForUid(uid))) {
9695 return;
9696 }
9697
Heemin Seogdb8489d2019-06-12 09:21:44 -07009698 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9699 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009700
9701 // Turn airplane mode off
9702 setAirplaneMode(false);
9703
9704 // restore private DNS settings to default mode (opportunistic)
9705 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9706 UserHandle.getUserHandleForUid(uid))) {
9707 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9708 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9709 }
9710
9711 Settings.Global.putString(mContext.getContentResolver(),
9712 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009713 } finally {
9714 Binder.restoreCallingIdentity(token);
9715 }
Stuart Scottd5463642015-04-02 18:00:02 -07009716 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009717
Ricky Wai7097cc92018-01-23 04:09:45 +00009718 @Override
9719 public byte[] getNetworkWatchlistConfigHash() {
9720 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9721 if (nwm == null) {
9722 loge("Unable to get NetworkWatchlistManager");
9723 return null;
9724 }
9725 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9726 return nwm.getWatchlistConfigHash();
9727 }
9728
Hugo Benichibe0c7652016-05-31 16:28:06 +09009729 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009730 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009731 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009732 }
Hugo Benichif4210292017-04-21 15:07:12 +09009733
9734 private static boolean toBool(int encodedBoolean) {
9735 return encodedBoolean != 0; // Only 0 means false.
9736 }
9737
9738 private static int encodeBool(boolean b) {
9739 return b ? 1 : 0;
9740 }
mswest4632928412018-03-12 10:34:34 -07009741
9742 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009743 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9744 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9745 @NonNull String[] args) {
9746 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9747 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009748 }
9749
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009750 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009751 @Override
9752 public int onCommand(String cmd) {
9753 if (cmd == null) {
9754 return handleDefaultCommands(cmd);
9755 }
9756 final PrintWriter pw = getOutPrintWriter();
9757 try {
9758 switch (cmd) {
9759 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009760 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9761 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009762 final String action = getNextArg();
9763 if ("enable".equals(action)) {
9764 setAirplaneMode(true);
9765 return 0;
9766 } else if ("disable".equals(action)) {
9767 setAirplaneMode(false);
9768 return 0;
9769 } else if (action == null) {
9770 final ContentResolver cr = mContext.getContentResolver();
9771 final int enabled = Settings.Global.getInt(cr,
9772 Settings.Global.AIRPLANE_MODE_ON);
9773 pw.println(enabled == 0 ? "disabled" : "enabled");
9774 return 0;
9775 } else {
9776 onHelp();
9777 return -1;
9778 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009779 case "reevaluate":
9780 // Usage : adb shell cmd connectivity reevaluate <netId>
9781 // If netId is omitted, then reevaluate the default network
9782 final String netId = getNextArg();
9783 final NetworkAgentInfo nai;
9784 if (null == netId) {
9785 // Note that the command is running on the wrong thread to call this,
9786 // so this could in principle return stale data. But it can't crash.
9787 nai = getDefaultNetwork();
9788 } else {
9789 // If netId can't be parsed, this throws NumberFormatException, which
9790 // is passed back to adb who prints it.
9791 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
9792 }
9793 if (null == nai) {
9794 pw.println("Unknown network (net ID not found or no default network)");
9795 return 0;
9796 }
9797 Log.d(TAG, "Reevaluating network " + nai.network);
9798 reportNetworkConnectivity(nai.network, !nai.isValidated());
9799 return 0;
mswest4632928412018-03-12 10:34:34 -07009800 default:
9801 return handleDefaultCommands(cmd);
9802 }
9803 } catch (Exception e) {
9804 pw.println(e);
9805 }
9806 return -1;
9807 }
9808
9809 @Override
9810 public void onHelp() {
9811 PrintWriter pw = getOutPrintWriter();
9812 pw.println("Connectivity service commands:");
9813 pw.println(" help");
9814 pw.println(" Print this help text.");
9815 pw.println(" airplane-mode [enable|disable]");
9816 pw.println(" Turn airplane mode on or off.");
9817 pw.println(" airplane-mode");
9818 pw.println(" Get airplane mode.");
9819 }
9820 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009821
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009822 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009823 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9824 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9825 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009826 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009827 }
9828
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09009829 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
9830 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +09009831 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9832 final TransportInfo newInfo = nc.getTransportInfo();
9833 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9834 return;
9835 }
9836 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009837 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009838 }
9839 }
9840
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009841 /**
9842 * @param connectionInfo the connection to resolve.
9843 * @return {@code uid} if the connection is found and the app has permission to observe it
9844 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9845 * connection is not found.
9846 */
9847 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009848 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9849 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9850 }
9851
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009852 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009853 connectionInfo.local, connectionInfo.remote);
9854
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009855 if (uid == INVALID_UID) return uid; // Not found.
9856
9857 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9858 // VPN, if any, that applies to the UID that owns the connection.
9859 if (checkNetworkStackPermission()) return uid;
9860
9861 final NetworkAgentInfo vpn = getVpnForUid(uid);
9862 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009863 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009864 return INVALID_UID;
9865 }
9866
9867 return uid;
9868 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009869
Benedict Wong493e04b2018-11-09 14:45:34 -08009870 /**
9871 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9872 *
9873 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9874 */
9875 @Override
9876 public IBinder startOrGetTestNetworkService() {
9877 synchronized (mTNSLock) {
9878 TestNetworkService.enforceTestNetworkPermissions(mContext);
9879
9880 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009881 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009882 }
9883
9884 return mTNS;
9885 }
9886 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009887
Cody Kesting73708bf2019-12-18 10:57:50 -08009888 /**
9889 * Handler used for managing all Connectivity Diagnostics related functions.
9890 *
9891 * @see android.net.ConnectivityDiagnosticsManager
9892 *
9893 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9894 */
9895 @VisibleForTesting
9896 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009897 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9898
Cody Kesting73708bf2019-12-18 10:57:50 -08009899 /**
9900 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9901 * android.net.ConnectivityDiagnosticsManager}.
9902 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9903 * NetworkRequestInfo to be registered
9904 */
9905 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9906
9907 /**
9908 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9909 * android.net.ConnectivityDiagnosticsManager}.
9910 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9911 * arg1 = the uid of the caller
9912 */
9913 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9914
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009915 /**
9916 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009917 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009918 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9919 * NetworkMonitor.
9920 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009921 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009922 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009923
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009924 /**
9925 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9926 * been detected on the network.
9927 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9928 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9929 * arg2 = NetID.
9930 * data = PersistableBundle of extras passed from NetworkMonitor.
9931 */
9932 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9933
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009934 /**
9935 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9936 * the platform. This event will invoke {@link
9937 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9938 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009939 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009940 */
9941 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9942
Cody Kesting73708bf2019-12-18 10:57:50 -08009943 private ConnectivityDiagnosticsHandler(Looper looper) {
9944 super(looper);
9945 }
9946
9947 @Override
9948 public void handleMessage(Message msg) {
9949 switch (msg.what) {
9950 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9951 handleRegisterConnectivityDiagnosticsCallback(
9952 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9953 break;
9954 }
9955 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9956 handleUnregisterConnectivityDiagnosticsCallback(
9957 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9958 break;
9959 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009960 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009961 final ConnectivityReportEvent reportEvent =
9962 (ConnectivityReportEvent) msg.obj;
9963
Aaron Huang959d3642021-01-21 15:47:41 +08009964 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009965 break;
9966 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009967 case EVENT_DATA_STALL_SUSPECTED: {
9968 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009969 final Pair<Long, PersistableBundle> arg =
9970 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009971 if (nai == null) break;
9972
Aaron Huang959d3642021-01-21 15:47:41 +08009973 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009974 break;
9975 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009976 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009977 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009978 break;
9979 }
9980 default: {
9981 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9982 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009983 }
9984 }
9985 }
9986
9987 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9988 @VisibleForTesting
9989 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9990 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9991 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009992 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009993
9994 @VisibleForTesting
9995 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009996 @NonNull IConnectivityDiagnosticsCallback cb,
9997 @NonNull NetworkRequestInfo nri,
9998 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009999 mCb = cb;
10000 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010001 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010002 }
10003
10004 @Override
10005 public void binderDied() {
10006 log("ConnectivityDiagnosticsCallback IBinder died.");
10007 unregisterConnectivityDiagnosticsCallback(mCb);
10008 }
10009 }
10010
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010011 /**
10012 * Class used for sending information from {@link
10013 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10014 */
10015 private static class NetworkTestedResults {
10016 private final int mNetId;
10017 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010018 @Nullable private final String mRedirectUrl;
10019
10020 private NetworkTestedResults(
10021 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10022 mNetId = netId;
10023 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010024 mRedirectUrl = redirectUrl;
10025 }
10026 }
10027
10028 /**
10029 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10030 * ConnectivityDiagnosticsHandler}.
10031 */
10032 private static class ConnectivityReportEvent {
10033 private final long mTimestampMillis;
10034 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010035 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010036
Aaron Huang959d3642021-01-21 15:47:41 +080010037 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10038 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010039 mTimestampMillis = timestampMillis;
10040 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010041 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010042 }
10043 }
10044
Cody Kestingf1120be2020-08-03 18:01:40 -070010045 /**
10046 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10047 * ConnectivityDiagnosticsHandler}.
10048 */
10049 private static class ReportedNetworkConnectivityInfo {
10050 public final boolean hasConnectivity;
10051 public final boolean isNetworkRevalidating;
10052 public final int reporterUid;
10053 @NonNull public final NetworkAgentInfo nai;
10054
10055 private ReportedNetworkConnectivityInfo(
10056 boolean hasConnectivity,
10057 boolean isNetworkRevalidating,
10058 int reporterUid,
10059 @NonNull NetworkAgentInfo nai) {
10060 this.hasConnectivity = hasConnectivity;
10061 this.isNetworkRevalidating = isNetworkRevalidating;
10062 this.reporterUid = reporterUid;
10063 this.nai = nai;
10064 }
10065 }
10066
Cody Kesting73708bf2019-12-18 10:57:50 -080010067 private void handleRegisterConnectivityDiagnosticsCallback(
10068 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10069 ensureRunningOnConnectivityServiceThread();
10070
10071 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010072 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010073 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10074
James Mattis64b8b0f2020-11-24 17:40:49 -080010075 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10076 // confusing for these networks to change when an NRI is satisfied in another layer.
10077 if (nri.isMultilayerRequest()) {
10078 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10079 + "network requests.");
10080 }
10081
Cody Kesting73708bf2019-12-18 10:57:50 -080010082 // This means that the client registered the same callback multiple times. Do
10083 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010084 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010085 if (VDBG) log("Diagnostics callback is already registered");
10086
10087 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10088 // incremented when the NetworkRequestInfo is created as part of
10089 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010090 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010091 return;
10092 }
10093
Cody Kesting31f1ff62020-03-05 10:46:02 -080010094 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010095
10096 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010097 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010098 } catch (RemoteException e) {
10099 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010100 return;
10101 }
10102
10103 // Once registered, provide ConnectivityReports for matching Networks
10104 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10105 synchronized (mNetworkForNetId) {
10106 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10107 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010108 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10109 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010110 matchingNetworks.add(nai);
10111 }
10112 }
10113 }
10114 for (final NetworkAgentInfo nai : matchingNetworks) {
10115 final ConnectivityReport report = nai.getConnectivityReport();
10116 if (report == null) {
10117 continue;
10118 }
10119 if (!checkConnectivityDiagnosticsPermissions(
10120 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10121 continue;
10122 }
10123
10124 try {
10125 cb.onConnectivityReportAvailable(report);
10126 } catch (RemoteException e) {
10127 // Exception while sending the ConnectivityReport. Move on to the next network.
10128 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010129 }
10130 }
10131
10132 private void handleUnregisterConnectivityDiagnosticsCallback(
10133 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10134 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010135 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010136
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010137 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10138 mConnectivityDiagnosticsCallbacks.remove(iCb);
10139 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010140 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10141 return;
10142 }
10143
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010144 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010145
Cody Kesting70fa2b22020-12-02 12:16:56 -080010146 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10147 // (if the Binder died)
10148 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10149 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010150 return;
10151 }
10152
Cody Kesting46cb1672020-03-04 13:35:20 -080010153 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10154 // incremented when the NetworkRequestInfo is created as part of
10155 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010156 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010157
Cody Kesting31f1ff62020-03-05 10:46:02 -080010158 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010159 }
10160
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010161 private void handleNetworkTestedWithExtras(
10162 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10163 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010164 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010165 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010166 final ConnectivityReport report =
10167 new ConnectivityReport(
10168 reportEvent.mNai.network,
10169 reportEvent.mTimestampMillis,
10170 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010171 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010172 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010173 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010174
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010175 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010176 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010177 for (final IConnectivityDiagnosticsCallback cb : results) {
10178 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010179 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010180 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010181 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010182 }
10183 }
10184 }
10185
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010186 private void handleDataStallSuspected(
10187 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10188 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010189 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010190 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010191 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010192 new DataStallReport(
10193 nai.network,
10194 timestampMillis,
10195 detectionMethod,
10196 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010197 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010198 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010199 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010200 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010201 for (final IConnectivityDiagnosticsCallback cb : results) {
10202 try {
10203 cb.onDataStallSuspected(report);
10204 } catch (RemoteException ex) {
10205 loge("Error invoking onDataStallSuspected", ex);
10206 }
10207 }
10208 }
10209
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010210 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010211 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10212 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10213 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10214
10215 // If the Network is being re-validated as a result of this call to
10216 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10217 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010218 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010219 getMatchingPermissionedCallbacks(
10220 nai,
10221 reportedNetworkConnectivityInfo.isNetworkRevalidating
10222 ? Process.INVALID_UID
10223 : reportedNetworkConnectivityInfo.reporterUid);
10224
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010225 for (final IConnectivityDiagnosticsCallback cb : results) {
10226 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010227 cb.onNetworkConnectivityReported(
10228 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010229 } catch (RemoteException ex) {
10230 loge("Error invoking onNetworkConnectivityReported", ex);
10231 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010232
10233 // If the Network isn't re-validating, also provide the cached report. If there is no
10234 // cached report, the Network is still being validated and a report will be sent once
10235 // validation is complete. Note that networks which never undergo validation will still
10236 // have a cached ConnectivityReport with RESULT_SKIPPED.
10237 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10238 try {
10239 cb.onConnectivityReportAvailable(cachedReport);
10240 } catch (RemoteException ex) {
10241 loge("Error invoking onConnectivityReportAvailable", ex);
10242 }
10243 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010244 }
10245 }
10246
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010247 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010248 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10249 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010250 sanitized.setUids(null);
10251 sanitized.setAdministratorUids(new int[0]);
10252 sanitized.setOwnerUid(Process.INVALID_UID);
10253 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010254 }
10255
Cody Kestingf1120be2020-08-03 18:01:40 -070010256 /**
10257 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10258 *
10259 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10260 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010261 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010262 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010263 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010264 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010265 mConnectivityDiagnosticsCallbacks.entrySet()) {
10266 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10267 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010268
James Mattis64b8b0f2020-11-24 17:40:49 -080010269 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010270 if (!nai.satisfies(nri.mRequests.get(0))) {
10271 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010272 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010273
10274 // UID for this callback must either be:
10275 // - INVALID_UID (which sends callbacks to all UIDs), or
10276 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10277 // notified as a result)
10278 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10279 continue;
10280 }
10281
10282 if (!checkConnectivityDiagnosticsPermissions(
10283 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10284 continue;
10285 }
10286
10287 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010288 }
10289 return results;
10290 }
10291
Cody Kesting7474f672021-05-11 14:22:40 -070010292 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10293 @NonNull NetworkAgentInfo nai) {
10294 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10295 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10296 }
10297
Cody Kesting160ef392021-05-05 13:17:22 -070010298 private boolean hasLocationPermission(String packageName, int uid) {
10299 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10300 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10301 // call in a try-catch.
10302 try {
10303 if (!mLocationPermissionChecker.checkLocationPermission(
10304 packageName, null /* featureId */, uid, null /* message */)) {
10305 return false;
10306 }
10307 } catch (SecurityException e) {
10308 return false;
10309 }
10310
10311 return true;
10312 }
10313
10314 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10315 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010316 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010317 && virtual.networkCapabilities.getOwnerUid() == uid
10318 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10319 return true;
10320 }
10321 }
10322
10323 return false;
10324 }
10325
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010326 @VisibleForTesting
10327 boolean checkConnectivityDiagnosticsPermissions(
10328 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10329 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10330 return true;
10331 }
10332
Cody Kesting160ef392021-05-05 13:17:22 -070010333 // Administrator UIDs also contains the Owner UID
10334 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10335 if (!CollectionUtils.contains(administratorUids, callbackUid)
10336 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010337 return false;
10338 }
10339
Cody Kesting7474f672021-05-11 14:22:40 -070010340 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10341 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010342 }
10343
Cody Kestingd199a9d2019-12-17 12:55:28 -080010344 @Override
10345 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010346 @NonNull IConnectivityDiagnosticsCallback callback,
10347 @NonNull NetworkRequest request,
10348 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010349 Objects.requireNonNull(callback, "callback must not be null");
10350 Objects.requireNonNull(request, "request must not be null");
10351 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10352
Cody Kesting73708bf2019-12-18 10:57:50 -080010353 if (request.legacyType != TYPE_NONE) {
10354 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10355 + " Please use NetworkCapabilities instead.");
10356 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010357 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010358 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010359
10360 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10361 // and administrator uids to be safe.
10362 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010363 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010364
10365 final NetworkRequest requestWithId =
10366 new NetworkRequest(
10367 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10368
10369 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10370 //
10371 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10372 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10373 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010374 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010375 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010376 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010377
10378 mConnectivityDiagnosticsHandler.sendMessage(
10379 mConnectivityDiagnosticsHandler.obtainMessage(
10380 ConnectivityDiagnosticsHandler
10381 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10382 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010383 }
10384
10385 @Override
10386 public void unregisterConnectivityDiagnosticsCallback(
10387 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010388 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010389 mConnectivityDiagnosticsHandler.sendMessage(
10390 mConnectivityDiagnosticsHandler.obtainMessage(
10391 ConnectivityDiagnosticsHandler
10392 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010393 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010394 0,
10395 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010396 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010397
10398 @Override
10399 public void simulateDataStall(int detectionMethod, long timestampMillis,
10400 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010401 Objects.requireNonNull(network, "network must not be null");
10402 Objects.requireNonNull(extras, "extras must not be null");
10403
paulhu3ffffe72021-09-16 10:15:22 +080010404 enforceAnyPermissionOf(mContext,
10405 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010406 android.Manifest.permission.NETWORK_STACK);
10407 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10408 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010409 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010410 }
10411
10412 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010413 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010414 throw new SecurityException("Data Stall simulation is only possible for network "
10415 + "creators");
10416 }
10417
Cody Kesting652e3ec2020-05-21 12:08:21 -070010418 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10419 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10420 // Data Stall information as a DataStallReportParcelable and passing to
10421 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10422 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010423 final DataStallReportParcelable p = new DataStallReportParcelable();
10424 p.timestampMillis = timestampMillis;
10425 p.detectionMethod = detectionMethod;
10426
10427 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10428 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10429 }
10430 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10431 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10432 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10433 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10434 }
10435
Serik Beketayevec8ad212020-12-07 22:43:07 -080010436 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010437 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010438
lucaslin66f44212021-02-23 01:12:55 +080010439 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10440 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010441 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010442 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010443 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010444 }
lucaslin37a16d92021-01-21 19:48:09 +080010445
10446 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010447 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010448 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010449 nai.clatd.interfaceLinkStateChanged(iface, up);
10450 }
10451 }
10452
10453 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010454 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010455 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010456 nai.clatd.interfaceRemoved(iface);
10457 }
lucaslin66f44212021-02-23 01:12:55 +080010458 }
10459 }
10460
lucaslin1a8b4c62021-01-21 02:02:55 +080010461 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10462
10463 /**
10464 * Class used for updating network activity tracking with netd and notify network activity
10465 * changes.
10466 */
10467 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010468 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010469 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010470 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010471 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10472 new RemoteCallbackList<>();
10473 // Indicate the current system default network activity is active or not.
10474 @GuardedBy("mActiveIdleTimers")
10475 private boolean mNetworkActive;
10476 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010477 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010478 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010479
Chalard Jean46bfbf02022-02-02 00:56:25 +090010480 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010481 public final int timeout;
10482 public final int transportType;
10483
10484 IdleTimerParams(int timeout, int transport) {
10485 this.timeout = timeout;
10486 this.transportType = transport;
10487 }
10488 }
10489
10490 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010491 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010492 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010493 mNetd = netd;
10494 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010495 }
10496
lucaslin66f44212021-02-23 01:12:55 +080010497 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10498 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10499 synchronized (mActiveIdleTimers) {
10500 mNetworkActive = active;
10501 // If there are no idle timers, it means that system is not monitoring
10502 // activity, so the system default network for those default network
10503 // unspecified apps is always considered active.
10504 //
10505 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10506 // any network activity change event. Whenever this event is received,
10507 // the mActiveIdleTimers should be always not empty. The legacy behavior
10508 // is no-op. Remove to refer to mNetworkActive only.
10509 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10510 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10511 }
10512 }
10513 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010514
lucaslin1193a5d2021-01-21 02:04:15 +080010515 // The network activity should only be updated from ConnectivityService handler thread
10516 // when mActiveIdleTimers lock is held.
10517 @GuardedBy("mActiveIdleTimers")
10518 private void reportNetworkActive() {
10519 final int length = mNetworkActivityListeners.beginBroadcast();
10520 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10521 try {
10522 for (int i = 0; i < length; i++) {
10523 try {
10524 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10525 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010526 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010527 }
10528 }
10529 } finally {
10530 mNetworkActivityListeners.finishBroadcast();
10531 }
10532 }
10533
10534 @GuardedBy("mActiveIdleTimers")
10535 public void handleReportNetworkActivity() {
10536 synchronized (mActiveIdleTimers) {
10537 reportNetworkActive();
10538 }
10539 }
10540
lucaslin1a8b4c62021-01-21 02:02:55 +080010541 // This is deprecated and only to support legacy use cases.
10542 private int transportTypeToLegacyType(int type) {
10543 switch (type) {
10544 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010545 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010546 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010547 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010548 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010549 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010550 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010551 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010552 default:
10553 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10554 }
10555 return ConnectivityManager.TYPE_NONE;
10556 }
10557
10558 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10559 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10560 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10561 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10562 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10563 final long ident = Binder.clearCallingIdentity();
10564 try {
10565 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10566 RECEIVE_DATA_ACTIVITY_CHANGE,
10567 null /* resultReceiver */,
10568 null /* scheduler */,
10569 0 /* initialCode */,
10570 null /* initialData */,
10571 null /* initialExtra */);
10572 } finally {
10573 Binder.restoreCallingIdentity(ident);
10574 }
10575 }
10576
10577 /**
10578 * Setup data activity tracking for the given network.
10579 *
10580 * Every {@code setupDataActivityTracking} should be paired with a
10581 * {@link #removeDataActivityTracking} for cleanup.
10582 */
10583 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10584 final String iface = networkAgent.linkProperties.getInterfaceName();
10585
10586 final int timeout;
10587 final int type;
10588
10589 if (networkAgent.networkCapabilities.hasTransport(
10590 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10591 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010592 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010593 10);
10594 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10595 } else if (networkAgent.networkCapabilities.hasTransport(
10596 NetworkCapabilities.TRANSPORT_WIFI)) {
10597 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010598 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010599 15);
10600 type = NetworkCapabilities.TRANSPORT_WIFI;
10601 } else {
10602 return; // do not track any other networks
10603 }
10604
lucaslinb961efc2021-01-21 02:03:17 +080010605 updateRadioPowerState(true /* isActive */, type);
10606
lucaslin1a8b4c62021-01-21 02:02:55 +080010607 if (timeout > 0 && iface != null) {
10608 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010609 synchronized (mActiveIdleTimers) {
10610 // Networks start up.
10611 mNetworkActive = true;
10612 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10613 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10614 reportNetworkActive();
10615 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010616 } catch (Exception e) {
10617 // You shall not crash!
10618 loge("Exception in setupDataActivityTracking " + e);
10619 }
10620 }
10621 }
10622
10623 /**
10624 * Remove data activity tracking when network disconnects.
10625 */
10626 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10627 final String iface = networkAgent.linkProperties.getInterfaceName();
10628 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10629
lucaslinb961efc2021-01-21 02:03:17 +080010630 if (iface == null) return;
10631
10632 final int type;
10633 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10634 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10635 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10636 type = NetworkCapabilities.TRANSPORT_WIFI;
10637 } else {
10638 return; // do not track any other networks
10639 }
10640
10641 try {
10642 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010643 synchronized (mActiveIdleTimers) {
10644 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10645 // The call fails silently if no idle timer setup for this interface
10646 mNetd.idletimerRemoveInterface(iface, params.timeout,
10647 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010648 }
lucaslinb961efc2021-01-21 02:03:17 +080010649 } catch (Exception e) {
10650 // You shall not crash!
10651 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010652 }
10653 }
10654
10655 /**
10656 * Update data activity tracking when network state is updated.
10657 */
10658 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10659 NetworkAgentInfo oldNetwork) {
10660 if (newNetwork != null) {
10661 setupDataActivityTracking(newNetwork);
10662 }
10663 if (oldNetwork != null) {
10664 removeDataActivityTracking(oldNetwork);
10665 }
10666 }
lucaslinb961efc2021-01-21 02:03:17 +080010667
10668 private void updateRadioPowerState(boolean isActive, int transportType) {
10669 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10670 switch (transportType) {
10671 case NetworkCapabilities.TRANSPORT_CELLULAR:
10672 bs.reportMobileRadioPowerState(isActive, NO_UID);
10673 break;
10674 case NetworkCapabilities.TRANSPORT_WIFI:
10675 bs.reportWifiRadioPowerState(isActive, NO_UID);
10676 break;
10677 default:
10678 logw("Untracked transport type:" + transportType);
10679 }
10680 }
lucaslin1193a5d2021-01-21 02:04:15 +080010681
10682 public boolean isDefaultNetworkActive() {
10683 synchronized (mActiveIdleTimers) {
10684 // If there are no idle timers, it means that system is not monitoring activity,
10685 // so the default network is always considered active.
10686 //
10687 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10688 // tracking is disabled (negative idle timer value configured), or no active default
10689 // network. In the latter case, this reports active but it should report inactive.
10690 return mNetworkActive || mActiveIdleTimers.isEmpty();
10691 }
10692 }
10693
10694 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10695 mNetworkActivityListeners.register(l);
10696 }
10697
10698 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10699 mNetworkActivityListeners.unregister(l);
10700 }
lucaslin012f7a12021-01-21 02:04:35 +080010701
10702 public void dump(IndentingPrintWriter pw) {
10703 synchronized (mActiveIdleTimers) {
10704 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10705 pw.println("Idle timers:");
10706 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10707 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10708 final IdleTimerParams params = ent.getValue();
10709 pw.print(" timeout="); pw.print(params.timeout);
10710 pw.print(" type="); pw.println(params.transportType);
10711 }
10712 }
10713 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010714 }
James Mattis47db0582021-01-01 14:13:35 -080010715
Daniel Brightf9e945b2020-06-15 16:10:01 -070010716 /**
10717 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10718 *
10719 * @param socketInfo the socket information
10720 * @param callback the callback to register
10721 */
10722 @Override
10723 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10724 @NonNull final IQosCallback callback) {
10725 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10726 if (nai == null || nai.networkCapabilities == null) {
10727 try {
10728 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10729 } catch (final RemoteException ex) {
10730 loge("registerQosCallbackInternal: RemoteException", ex);
10731 }
10732 return;
10733 }
10734 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10735 }
10736
10737 /**
10738 * Register a {@link IQosCallback} with base {@link QosFilter}.
10739 *
10740 * @param filter the filter to register
10741 * @param callback the callback to register
10742 * @param nai the agent information related to the filter's network
10743 */
10744 @VisibleForTesting
10745 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10746 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010747 Objects.requireNonNull(filter, "filter must be non-null");
10748 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010749
10750 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010751 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10752 // on this network is unregistered when the app loses permission or b) no QoS
10753 // callbacks are sent for restricted networks unless the app currently has permission
10754 // to access restricted networks.
10755 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010756 }
10757 mQosCallbackTracker.registerCallback(callback, filter, nai);
10758 }
10759
10760 /**
10761 * Unregisters the given callback.
10762 *
10763 * @param callback the callback to unregister
10764 */
10765 @Override
10766 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010767 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010768 mQosCallbackTracker.unregisterCallback(callback);
10769 }
James Mattis47db0582021-01-01 14:13:35 -080010770
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010771 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10772 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10773 // Enterprise device can be fully managed like device owner and such use case
10774 // also should be supported. Calling app check for work profile and fully managed device
10775 // is already done in DevicePolicyManager.
10776 // This check is an extra caution to be sure device is fully managed or not.
10777 final UserManager um = mContext.getSystemService(UserManager.class);
10778 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10779 if (um.isManagedProfile(profile.getIdentifier())) {
10780 return true;
10781 }
10782 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10783 return false;
10784 }
10785
James Mattis45d81842021-01-10 14:24:24 -080010786 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010787 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010788 *
10789 * See the documentation for the individual preferences for a description of the supported
10790 * behaviors.
10791 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010792 * @param profile If the device owner is set, any profile is allowed.
10793 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010794 * @param preferences the list of profile network preferences for the
10795 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010796 * @param listener an optional listener to listen for completion of the operation.
10797 */
10798 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010799 public void setProfileNetworkPreferences(
10800 @NonNull final UserHandle profile,
10801 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010802 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010803 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010804 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010805
10806 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010807 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10808 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10809 .build();
10810 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010811 }
10812
paulhu3ffffe72021-09-16 10:15:22 +080010813 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010814 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010815 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010816 }
10817 if (profile.getIdentifier() < 0) {
10818 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10819 + "UserHandle.CURRENT not supported)");
10820 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010821 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10822 throw new IllegalArgumentException("Profile must be a managed profile "
10823 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010824 }
paulhuaa0743d2021-05-26 21:56:03 +080010825
Chalard Jean0606fc82022-12-14 20:34:43 +090010826 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010827 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010828 for (final ProfileNetworkPreference preference : preferences) {
10829 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010830 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010831 switch (preference.getPreference()) {
10832 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10833 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010834 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010835 if (preference.getPreferenceEnterpriseId() != 0) {
10836 throw new IllegalArgumentException(
10837 "Invalid enterprise identifier in setProfileNetworkPreferences");
10838 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010839 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010840 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10841 allowFallback = false;
10842 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010843 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010844 // This code is needed even though there is a check later on,
10845 // because isRangeAlreadyInPreferenceList assumes that every preference
10846 // has a UID list.
10847 if (hasDefaultPreference) {
10848 throw new IllegalArgumentException(
10849 "Default profile preference should not be set along with other "
10850 + "preference");
10851 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010852 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10853 throw new IllegalArgumentException(
10854 "Invalid enterprise identifier in setProfileNetworkPreferences");
10855 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010856 final Set<UidRange> uidRangeSet =
10857 getUidListToBeAppliedForNetworkPreference(profile, preference);
10858 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10859 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10860 } else {
10861 throw new IllegalArgumentException(
10862 "Overlapping uid range in setProfileNetworkPreferences");
10863 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010864 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010865 nc.addEnterpriseId(
10866 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010867 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10868 break;
10869 default:
10870 throw new IllegalArgumentException(
10871 "Invalid preference in setProfileNetworkPreferences");
10872 }
Chalard Jean0606fc82022-12-14 20:34:43 +090010873 preferenceList.add(new ProfileNetworkPreferenceInfo(profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010874 if (hasDefaultPreference && preferenceList.size() > 1) {
10875 throw new IllegalArgumentException(
10876 "Default profile preference should not be set along with other preference");
10877 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010878 }
10879 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010880 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010881 }
10882
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010883 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10884 @NonNull final UserHandle profile,
10885 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10886 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010887 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10888 profileNetworkPreference.getIncludedUids());
10889
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010890 if (uidRangeSet.size() > 0) {
10891 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10892 throw new IllegalArgumentException(
10893 "Allow uid range is outside the uid range of profile.");
10894 }
10895 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010896 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010897 profileNetworkPreference.getExcludedUids());
10898 if (disallowUidRangeSet.size() > 0) {
10899 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10900 throw new IllegalArgumentException(
10901 "disallow uid range is outside the uid range of profile.");
10902 }
10903 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10904 disallowUidRangeSet);
10905 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010906 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010907 uidRangeSet.add(profileUids);
10908 }
10909 }
10910 return uidRangeSet;
10911 }
10912
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010913 private boolean isEnterpriseIdentifierValid(
10914 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010915 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010916 return true;
10917 }
10918 return false;
10919 }
10920
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010921 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090010922 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010923 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090010924 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010925 // The NRI for a user should contain the request for capabilities.
10926 // If fallback to default network is needed then NRI should include
10927 // the request for the default network. Create an image of it to
10928 // have the correct UIDs in it (also a request can only be part of one NRI, because
10929 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010930 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10931 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010932 if (pref.allowFallback) {
10933 nrs.add(createDefaultInternetRequestForTransport(
10934 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10935 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010936 if (VDBG) {
10937 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10938 pref.capabilities.getUids()));
10939 }
10940
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010941 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010942 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010943 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010944 result.add(nri);
10945 }
10946 return result;
10947 }
10948
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010949 /**
10950 * Compare if the given UID range sets have the same UIDs.
10951 *
10952 */
10953 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090010954 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010955 @NonNull Set<UidRange> uidRangeSet) {
10956 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10957 return false;
10958 }
Chalard Jean0606fc82022-12-14 20:34:43 +090010959 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010960 if (UidRangeUtils.doesRangeSetOverlap(
10961 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10962 return true;
10963 }
10964 }
10965 return false;
10966 }
10967
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010968 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090010969 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010970 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010971 /*
10972 * handleSetProfileNetworkPreference is always called for single user.
10973 * preferenceList only contains preferences for different uids within the same user
10974 * (enforced by getUidListToBeAppliedForNetworkPreference).
10975 * Clear all the existing preferences for the user before applying new preferences.
10976 *
10977 */
Chalard Jean0606fc82022-12-14 20:34:43 +090010978 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
10979 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010980 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10981 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010982
paulhu74128522021-09-28 02:29:03 +000010983 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10984 addPerAppDefaultNetworkRequests(
10985 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010986
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010987 // Finally, rematch.
10988 rematchAllNetworksAndRequests();
10989
10990 if (null != listener) {
10991 try {
10992 listener.onComplete();
10993 } catch (RemoteException e) {
10994 loge("Listener for setProfileNetworkPreference has died");
10995 }
10996 }
10997 }
10998
paulhu51f77dc2021-06-07 02:34:20 +000010999 @VisibleForTesting
11000 @NonNull
11001 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11002 @NonNull final Set<Integer> uids) {
11003 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11004 if (uids.size() == 0) {
11005 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11006 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11007 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11008 return nris;
11009 }
11010
11011 final List<NetworkRequest> requests = new ArrayList<>();
11012 // The NRI should be comprised of two layers:
11013 // - The request for the mobile network preferred.
11014 // - The request for the default network, for fallback.
11015 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011016 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011017 requests.add(createDefaultInternetRequestForTransport(
11018 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11019 final Set<UidRange> ranges = new ArraySet<>();
11020 for (final int uid : uids) {
11021 ranges.add(new UidRange(uid, uid));
11022 }
11023 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011024 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011025 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011026 return nris;
11027 }
11028
11029 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011030 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011031 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11032 addPerAppDefaultNetworkRequests(
11033 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011034 // Finally, rematch.
11035 rematchAllNetworksAndRequests();
11036 }
11037
Patrick Rohr2857ac42022-01-21 14:58:16 +010011038 private void handleIngressRateLimitChanged() {
11039 final long oldIngressRateLimit = mIngressRateLimit;
11040 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11041 mContext);
11042 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11043 if (canNetworkBeRateLimited(networkAgent)) {
11044 // If rate limit has previously been enabled, remove the old limit first.
11045 if (oldIngressRateLimit >= 0) {
11046 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11047 }
11048 if (mIngressRateLimit >= 0) {
11049 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11050 mIngressRateLimit);
11051 }
11052 }
11053 }
11054 }
11055
11056 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011057 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11058 if (!SdkLevel.isAtLeastT()) return false;
11059
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011060 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11061 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11062 // internet connectivity can be rate limited.
11063 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11064 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011065 return false;
11066 }
11067
11068 final String iface = networkAgent.linkProperties.getInterfaceName();
11069 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011070 // This may happen in tests, but if there is no interface then there is nothing that
11071 // can be rate limited.
11072 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011073 return false;
11074 }
11075 return true;
11076 }
11077
James Mattis45d81842021-01-10 14:24:24 -080011078 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011079 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11080 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011081 }
11082
11083 /**
11084 * Used by automotive devices to set the network preferences used to direct traffic at an
11085 * application level as per the given OemNetworkPreferences. An example use-case would be an
11086 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11087 * vehicle via a particular network.
11088 *
11089 * Calling this will overwrite the existing preference.
11090 *
James Mattisda32cfe2021-01-26 16:23:52 -080011091 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011092 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011093 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011094 */
James Mattis47db0582021-01-01 14:13:35 -080011095 @Override
James Mattis45d81842021-01-10 14:24:24 -080011096 public void setOemNetworkPreference(
11097 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011098 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011099
James Mattisfa270db2021-05-31 17:11:10 -070011100 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11101 // Only bypass the permission/device checks if this is a valid test request.
11102 if (isValidTestOemNetworkPreference(preference)) {
11103 enforceManageTestNetworksPermission();
11104 } else {
11105 enforceAutomotiveDevice();
11106 enforceOemNetworkPreferencesPermission();
11107 validateOemNetworkPreferences(preference);
11108 }
James Mattis45d81842021-01-10 14:24:24 -080011109
James Mattis45d81842021-01-10 14:24:24 -080011110 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11111 new Pair<>(preference, listener)));
11112 }
11113
James Mattisfa270db2021-05-31 17:11:10 -070011114 /**
11115 * Check the validity of an OEM network preference to be used for testing purposes.
11116 * @param preference the preference to validate
11117 * @return true if this is a valid OEM network preference test request.
11118 */
11119 private boolean isValidTestOemNetworkPreference(
11120 @NonNull final OemNetworkPreferences preference) {
11121 // Allow for clearing of an existing OemNetworkPreference used for testing.
11122 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11123 // changes after this check is complete. This is an unlikely scenario as calling of this API
11124 // is controlled by the OEM therefore the added complexity is not worth adding given those
11125 // circumstances. That said, it is an edge case to be aware of hence this comment.
11126 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11127 && isTestOemNetworkPreference(mOemNetworkPreferences);
11128 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11129 }
11130
11131 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11132 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11133 return prefMap.size() == 1
11134 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11135 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11136 }
11137
James Mattis45d81842021-01-10 14:24:24 -080011138 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11139 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11140 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011141 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11142 throw new IllegalArgumentException(
11143 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11144 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011145 }
11146 }
11147 }
11148
11149 private void handleSetOemNetworkPreference(
11150 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011151 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011152 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11153 if (DBG) {
11154 log("set OEM network preferences :" + preference.toString());
11155 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011156
James Mattiscb1e0362021-04-06 17:07:42 -070011157 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011158 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11159 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11160 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011161 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011162
11163 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011164 try {
11165 listener.onComplete();
11166 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011167 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011168 }
James Mattis45d81842021-01-10 14:24:24 -080011169 }
11170 }
11171
paulhu74128522021-09-28 02:29:03 +000011172 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011173 // Skip the requests which are set by other network preference. Because the uid range rules
11174 // should stay in netd.
11175 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011176 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011177 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011178 }
11179
James Mattis3ce3d3c2021-02-09 18:18:28 -080011180 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11181 ensureRunningOnConnectivityServiceThread();
11182 mDefaultNetworkRequests.addAll(nris);
11183 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11184 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011185 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011186 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11187 nrisToRegister.addAll(
11188 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11189 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011190 }
11191
11192 /**
11193 * All current requests that are tracking the default network need to be assessed as to whether
11194 * or not the current set of per-application default requests will be changing their default
11195 * network. If so, those requests will need to be updated so that they will send callbacks for
11196 * default network changes at the appropriate time. Additionally, those requests tracking the
11197 * default that were previously updated by this flow will need to be reassessed.
11198 * @return the nris which will need to be updated.
11199 */
11200 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11201 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11202 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11203 // same nri in the map's values for each of its NetworkRequest objects.
11204 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011205 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011206 // Include this nri if it is currently being tracked.
11207 if (isPerAppTrackedNri(nri)) {
11208 defaultCallbackRequests.add(nri);
11209 continue;
11210 }
11211 // We only track callbacks for requests tracking the default.
11212 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11213 continue;
11214 }
11215 // Include this nri if it will be tracked by the new per-app default requests.
11216 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011217 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011218 if (isNriGoingToBeTracked) {
11219 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011220 }
11221 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011222 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011223 }
11224
James Mattis3ce3d3c2021-02-09 18:18:28 -080011225 /**
11226 * Create nris for those network requests that are currently tracking the default network that
11227 * are being controlled by a per-application default.
11228 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11229 * foundation when creating the nri. Important items include the calling uid's original
11230 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11231 * requests are assumed to have already been validated as needing to be updated.
11232 * @return the Set of nris to use when registering network requests.
11233 */
11234 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11235 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11236 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11237 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11238 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011239 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011240
Chalard Jean9473c982021-07-29 20:03:04 +090011241 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011242 if (trackingNri == mDefaultRequest) {
11243 callbackRequestsToRegister.add(new NetworkRequestInfo(
11244 callbackRequest,
11245 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11246 continue;
11247 }
11248
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011249 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011250 callbackRequestsToRegister.add(new NetworkRequestInfo(
11251 callbackRequest,
11252 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011253 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011254 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011255 }
11256 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011257 }
11258
Chalard Jean17215832021-03-01 14:06:28 +090011259 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11260 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011261 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011262 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011263 }
11264 }
11265
James Mattis45d81842021-01-10 14:24:24 -080011266 /**
11267 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11268 */
11269 @VisibleForTesting
11270 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011271 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011272 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011273 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011274 final SparseArray<Set<Integer>> uids =
11275 createUidsFromOemNetworkPreferences(preference);
11276 for (int i = 0; i < uids.size(); i++) {
11277 final int key = uids.keyAt(i);
11278 final Set<Integer> value = uids.valueAt(i);
11279 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11280 // No need to add an nri without any requests.
11281 if (0 == nri.mRequests.size()) {
11282 continue;
11283 }
11284 nris.add(nri);
11285 }
11286
11287 return nris;
11288 }
11289
11290 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11291 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011292 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011293 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011294 final List<UserHandle> users =
11295 mContext.getSystemService(UserManager.class).getUserHandles(true);
11296 if (null == users || users.size() == 0) {
11297 if (VDBG || DDBG) {
11298 log("No users currently available for setting the OEM network preference.");
11299 }
James Mattisb6b6a432021-06-01 22:30:36 -070011300 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011301 }
James Mattis45d81842021-01-10 14:24:24 -080011302 for (final Map.Entry<String, Integer> entry :
11303 preference.getNetworkPreferences().entrySet()) {
11304 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011305 // Add the rules for all users as this policy is device wide.
11306 for (final UserHandle user : users) {
11307 try {
11308 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11309 if (!prefToUids.contains(pref)) {
11310 prefToUids.put(pref, new ArraySet<>());
11311 }
11312 prefToUids.get(pref).add(uid);
11313 } catch (PackageManager.NameNotFoundException e) {
11314 // Although this may seem like an error scenario, it is ok that uninstalled
11315 // packages are sent on a network preference as the system will watch for
11316 // package installations associated with this network preference and update
11317 // accordingly. This is done to minimize race conditions on app install.
11318 continue;
James Mattis45d81842021-01-10 14:24:24 -080011319 }
James Mattis45d81842021-01-10 14:24:24 -080011320 }
11321 }
James Mattisb6b6a432021-06-01 22:30:36 -070011322 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011323 }
11324
11325 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11326 @OemNetworkPreferences.OemNetworkPreference final int preference,
11327 @NonNull final Set<Integer> uids) {
11328 final List<NetworkRequest> requests = new ArrayList<>();
11329 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11330 switch (preference) {
11331 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11332 requests.add(createUnmeteredNetworkRequest());
11333 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011334 requests.add(createDefaultInternetRequestForTransport(
11335 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011336 break;
11337 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11338 requests.add(createUnmeteredNetworkRequest());
11339 requests.add(createOemPaidNetworkRequest());
11340 break;
11341 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11342 requests.add(createOemPaidNetworkRequest());
11343 break;
11344 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11345 requests.add(createOemPrivateNetworkRequest());
11346 break;
James Mattisfa270db2021-05-31 17:11:10 -070011347 case OEM_NETWORK_PREFERENCE_TEST:
11348 requests.add(createUnmeteredNetworkRequest());
11349 requests.add(createTestNetworkRequest());
11350 requests.add(createDefaultRequest());
11351 break;
11352 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11353 requests.add(createTestNetworkRequest());
11354 break;
James Mattis45d81842021-01-10 14:24:24 -080011355 default:
11356 // This should never happen.
11357 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11358 + " called with invalid preference of " + preference);
11359 }
11360
James Mattisfa270db2021-05-31 17:11:10 -070011361 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011362 for (final int uid : uids) {
11363 ranges.add(new UidRange(uid, uid));
11364 }
11365 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011366 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011367 }
11368
11369 private NetworkRequest createUnmeteredNetworkRequest() {
11370 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11371 .addCapability(NET_CAPABILITY_NOT_METERED)
11372 .addCapability(NET_CAPABILITY_VALIDATED);
11373 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11374 }
11375
11376 private NetworkRequest createOemPaidNetworkRequest() {
11377 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11378 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11379 .addCapability(NET_CAPABILITY_OEM_PAID)
11380 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11381 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11382 }
11383
11384 private NetworkRequest createOemPrivateNetworkRequest() {
11385 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11386 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11387 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11388 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11389 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11390 }
11391
11392 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011393 final NetworkCapabilities netcap = new NetworkCapabilities();
11394 netcap.addCapability(NET_CAPABILITY_INTERNET);
11395 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11396 return netcap;
11397 }
11398
11399 private NetworkRequest createTestNetworkRequest() {
11400 final NetworkCapabilities netcap = new NetworkCapabilities();
11401 netcap.clearAll();
11402 netcap.addTransportType(TRANSPORT_TEST);
11403 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011404 }
James Mattis47db0582021-01-01 14:13:35 -080011405 }
markchien738ad912021-12-09 18:15:45 +080011406
11407 @Override
11408 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11409 enforceNetworkStackOrSettingsPermission();
11410
11411 try {
11412 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011413 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011414 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011415 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011416 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011417 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011418 throw new IllegalStateException(e);
11419 }
11420 }
11421
11422 @Override
11423 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11424 enforceNetworkStackOrSettingsPermission();
11425
11426 try {
11427 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011428 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011429 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011430 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011431 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011432 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011433 throw new IllegalStateException(e);
11434 }
11435 }
markchiene1561fa2021-12-09 22:00:56 +080011436
11437 @Override
markchien3c04e662022-03-22 16:29:56 +080011438 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011439 enforceNetworkStackOrSettingsPermission();
11440
markchien3c04e662022-03-22 16:29:56 +080011441 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11442 int firewallRule = getFirewallRuleType(chain, rule);
11443
11444 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11445 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11446 }
11447
markchiene1561fa2021-12-09 22:00:56 +080011448 try {
markchien3c04e662022-03-22 16:29:56 +080011449 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011450 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011451 throw new IllegalStateException(e);
11452 }
11453 }
markchien98a6f952022-01-13 23:43:53 +080011454
markchien3c04e662022-03-22 16:29:56 +080011455 private int getFirewallRuleType(int chain, int rule) {
11456 final int defaultRule;
11457 switch (chain) {
11458 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011459 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11460 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011461 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011462 defaultRule = FIREWALL_RULE_ALLOW;
11463 break;
11464 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11465 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11466 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11467 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11468 defaultRule = FIREWALL_RULE_DENY;
11469 break;
11470 default:
11471 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11472 }
11473 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11474
11475 return rule;
11476 }
11477
markchien98a6f952022-01-13 23:43:53 +080011478 @Override
11479 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11480 enforceNetworkStackOrSettingsPermission();
11481
11482 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011483 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011484 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011485 throw new IllegalStateException(e);
11486 }
11487 }
11488
markchien00a0bed2022-01-13 23:46:13 +080011489 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011490 public boolean getFirewallChainEnabled(final int chain) {
11491 enforceNetworkStackOrSettingsPermission();
11492
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011493 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011494 }
11495
11496 @Override
markchien00a0bed2022-01-13 23:46:13 +080011497 public void replaceFirewallChain(final int chain, final int[] uids) {
11498 enforceNetworkStackOrSettingsPermission();
11499
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011500 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011501 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011502
11503 @Override
11504 public IBinder getCompanionDeviceManagerProxyService() {
11505 enforceNetworkStackPermission(mContext);
11506 return mCdmps;
11507 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011508}